PhpStorm Laravel 5 Form/Html not found issue - php
So I've seen this question a million times around the internet already, but my problem is slightly different.
I've created a new Laravel project and tried to use Html and Form classes. They did not exist so I did everything to include them to my project. And voila! It works... Kinda...
The classes Html and Form seem to be working. If I create a form and refresh in my browser, there's no error and the form is showing. But... PhpStorm does not recognize the classes, it keeps whining about undefined class Html and Form. With this there's the problem that the auto-complete for those classes do not work at all.
I've also included the _ide_helper.php class by 'barryvdh' (found on https://github.com/barryvdh/laravel-ide-helper) But that did not help with this problem.
I'm out of ideas, can anyone help me on this one? Would be greatly appreciated.
Cheers!
This works for me, do you have your composer.json file set up properly?
Make sure the scripts section is set up properly and then run composer dump-autoload.
composer.json
"scripts": {
"post-update-cmd": [
"php artisan clear-compiled",
"php artisan ide-helper:generate",
"php artisan optimize"
] ...
},
Here is what my _ide_helper.php file looks like.
_ide_helper.php
class Form extends \Illuminate\Html\FormFacade{
/**
* Open up a new HTML form.
*
* #param array $options
* #return string
* #static
*/
public static function open($options = array()){
return \Illuminate\Html\FormBuilder::open($options);
}
/**
* Create a new model based form builder.
*
* #param mixed $model
* #param array $options
* #return string
* #static
*/
public static function model($model, $options = array()){
return \Illuminate\Html\FormBuilder::model($model, $options);
}
/**
* Set the model instance on the form builder.
*
* #param mixed $model
* #return void
* #static
*/
public static function setModel($model){
\Illuminate\Html\FormBuilder::setModel($model);
}
/**
* Close the current form.
*
* #return string
* #static
*/
public static function close(){
return \Illuminate\Html\FormBuilder::close();
}
/**
* Generate a hidden field with the current CSRF token.
*
* #return string
* #static
*/
public static function token(){
return \Illuminate\Html\FormBuilder::token();
}
/**
* Create a form label element.
*
* #param string $name
* #param string $value
* #param array $options
* #return string
* #static
*/
public static function label($name, $value = null, $options = array()){
return \Illuminate\Html\FormBuilder::label($name, $value, $options);
}
/**
* Create a form input field.
*
* #param string $type
* #param string $name
* #param string $value
* #param array $options
* #return string
* #static
*/
public static function input($type, $name, $value = null, $options = array()){
return \Illuminate\Html\FormBuilder::input($type, $name, $value, $options);
}
/**
* Create a text input field.
*
* #param string $name
* #param string $value
* #param array $options
* #return string
* #static
*/
public static function text($name, $value = null, $options = array()){
return \Illuminate\Html\FormBuilder::text($name, $value, $options);
}
/**
* Create a password input field.
*
* #param string $name
* #param array $options
* #return string
* #static
*/
public static function password($name, $options = array()){
return \Illuminate\Html\FormBuilder::password($name, $options);
}
/**
* Create a hidden input field.
*
* #param string $name
* #param string $value
* #param array $options
* #return string
* #static
*/
public static function hidden($name, $value = null, $options = array()){
return \Illuminate\Html\FormBuilder::hidden($name, $value, $options);
}
/**
* Create an e-mail input field.
*
* #param string $name
* #param string $value
* #param array $options
* #return string
* #static
*/
public static function email($name, $value = null, $options = array()){
return \Illuminate\Html\FormBuilder::email($name, $value, $options);
}
/**
* Create a url input field.
*
* #param string $name
* #param string $value
* #param array $options
* #return string
* #static
*/
public static function url($name, $value = null, $options = array()){
return \Illuminate\Html\FormBuilder::url($name, $value, $options);
}
/**
* Create a file input field.
*
* #param string $name
* #param array $options
* #return string
* #static
*/
public static function file($name, $options = array()){
return \Illuminate\Html\FormBuilder::file($name, $options);
}
/**
* Create a textarea input field.
*
* #param string $name
* #param string $value
* #param array $options
* #return string
* #static
*/
public static function textarea($name, $value = null, $options = array()){
return \Illuminate\Html\FormBuilder::textarea($name, $value, $options);
}
/**
* Create a select box field.
*
* #param string $name
* #param array $list
* #param string $selected
* #param array $options
* #return string
* #static
*/
public static function select($name, $list = array(), $selected = null, $options = array()){
return \Illuminate\Html\FormBuilder::select($name, $list, $selected, $options);
}
/**
* Create a select range field.
*
* #param string $name
* #param string $begin
* #param string $end
* #param string $selected
* #param array $options
* #return string
* #static
*/
public static function selectRange($name, $begin, $end, $selected = null, $options = array()){
return \Illuminate\Html\FormBuilder::selectRange($name, $begin, $end, $selected, $options);
}
/**
* Create a select year field.
*
* #param string $name
* #param string $begin
* #param string $end
* #param string $selected
* #param array $options
* #return string
* #static
*/
public static function selectYear(){
return \Illuminate\Html\FormBuilder::selectYear();
}
/**
* Create a select month field.
*
* #param string $name
* #param string $selected
* #param array $options
* #param string $format
* #return string
* #static
*/
public static function selectMonth($name, $selected = null, $options = array(), $format = '%B'){
return \Illuminate\Html\FormBuilder::selectMonth($name, $selected, $options, $format);
}
/**
* Get the select option for the given value.
*
* #param string $display
* #param string $value
* #param string $selected
* #return string
* #static
*/
public static function getSelectOption($display, $value, $selected){
return \Illuminate\Html\FormBuilder::getSelectOption($display, $value, $selected);
}
/**
* Create a checkbox input field.
*
* #param string $name
* #param mixed $value
* #param bool $checked
* #param array $options
* #return string
* #static
*/
public static function checkbox($name, $value = 1, $checked = null, $options = array()){
return \Illuminate\Html\FormBuilder::checkbox($name, $value, $checked, $options);
}
/**
* Create a radio button input field.
*
* #param string $name
* #param mixed $value
* #param bool $checked
* #param array $options
* #return string
* #static
*/
public static function radio($name, $value = null, $checked = null, $options = array()){
return \Illuminate\Html\FormBuilder::radio($name, $value, $checked, $options);
}
/**
* Create a HTML reset input element.
*
* #param string $value
* #param array $attributes
* #return string
* #static
*/
public static function reset($value, $attributes = array()){
return \Illuminate\Html\FormBuilder::reset($value, $attributes);
}
/**
* Create a HTML image input element.
*
* #param string $url
* #param string $name
* #param array $attributes
* #return string
* #static
*/
public static function image($url, $name = null, $attributes = array()){
return \Illuminate\Html\FormBuilder::image($url, $name, $attributes);
}
/**
* Create a submit button element.
*
* #param string $value
* #param array $options
* #return string
* #static
*/
public static function submit($value = null, $options = array()){
return \Illuminate\Html\FormBuilder::submit($value, $options);
}
/**
* Create a button element.
*
* #param string $value
* #param array $options
* #return string
* #static
*/
public static function button($value = null, $options = array()){
return \Illuminate\Html\FormBuilder::button($value, $options);
}
/**
* Get the ID attribute for a field name.
*
* #param string $name
* #param array $attributes
* #return string
* #static
*/
public static function getIdAttribute($name, $attributes){
return \Illuminate\Html\FormBuilder::getIdAttribute($name, $attributes);
}
/**
* Get the value that should be assigned to the field.
*
* #param string $name
* #param string $value
* #return string
* #static
*/
public static function getValueAttribute($name, $value = null){
return \Illuminate\Html\FormBuilder::getValueAttribute($name, $value);
}
/**
* Get a value from the session's old input.
*
* #param string $name
* #return string
* #static
*/
public static function old($name){
return \Illuminate\Html\FormBuilder::old($name);
}
/**
* Determine if the old input is empty.
*
* #return bool
* #static
*/
public static function oldInputIsEmpty(){
return \Illuminate\Html\FormBuilder::oldInputIsEmpty();
}
/**
* Get the session store implementation.
*
* #return \Illuminate\Session\Store $session
* #static
*/
public static function getSessionStore(){
return \Illuminate\Html\FormBuilder::getSessionStore();
}
/**
* Set the session store implementation.
*
* #param \Illuminate\Session\Store $session
* #return $this
* #static
*/
public static function setSessionStore($session){
return \Illuminate\Html\FormBuilder::setSessionStore($session);
}
/**
* Register a custom macro.
*
* #param string $name
* #param callable $macro
* #return void
* #static
*/
public static function macro($name, $macro){
\Illuminate\Html\FormBuilder::macro($name, $macro);
}
/**
* Checks if macro is registered.
*
* #param string $name
* #return bool
* #static
*/
public static function hasMacro($name){
return \Illuminate\Html\FormBuilder::hasMacro($name);
}
}
class Html extends \Illuminate\Html\HtmlFacade{
/**
* Convert an HTML string to entities.
*
* #param string $value
* #return string
* #static
*/
public static function entities($value){
return \Illuminate\Html\HtmlBuilder::entities($value);
}
/**
* Convert entities to HTML characters.
*
* #param string $value
* #return string
* #static
*/
public static function decode($value){
return \Illuminate\Html\HtmlBuilder::decode($value);
}
/**
* Generate a link to a JavaScript file.
*
* #param string $url
* #param array $attributes
* #param bool $secure
* #return string
* #static
*/
public static function script($url, $attributes = array(), $secure = null){
return \Illuminate\Html\HtmlBuilder::script($url, $attributes, $secure);
}
/**
* Generate a link to a CSS file.
*
* #param string $url
* #param array $attributes
* #param bool $secure
* #return string
* #static
*/
public static function style($url, $attributes = array(), $secure = null){
return \Illuminate\Html\HtmlBuilder::style($url, $attributes, $secure);
}
/**
* Generate an HTML image element.
*
* #param string $url
* #param string $alt
* #param array $attributes
* #param bool $secure
* #return string
* #static
*/
public static function image($url, $alt = null, $attributes = array(), $secure = null){
return \Illuminate\Html\HtmlBuilder::image($url, $alt, $attributes, $secure);
}
/**
* Generate a HTML link.
*
* #param string $url
* #param string $title
* #param array $attributes
* #param bool $secure
* #return string
* #static
*/
public static function link($url, $title = null, $attributes = array(), $secure = null){
return \Illuminate\Html\HtmlBuilder::link($url, $title, $attributes, $secure);
}
/**
* Generate a HTTPS HTML link.
*
* #param string $url
* #param string $title
* #param array $attributes
* #return string
* #static
*/
public static function secureLink($url, $title = null, $attributes = array()){
return \Illuminate\Html\HtmlBuilder::secureLink($url, $title, $attributes);
}
/**
* Generate a HTML link to an asset.
*
* #param string $url
* #param string $title
* #param array $attributes
* #param bool $secure
* #return string
* #static
*/
public static function linkAsset($url, $title = null, $attributes = array(), $secure = null){
return \Illuminate\Html\HtmlBuilder::linkAsset($url, $title, $attributes, $secure);
}
/**
* Generate a HTTPS HTML link to an asset.
*
* #param string $url
* #param string $title
* #param array $attributes
* #return string
* #static
*/
public static function linkSecureAsset($url, $title = null, $attributes = array()){
return \Illuminate\Html\HtmlBuilder::linkSecureAsset($url, $title, $attributes);
}
/**
* Generate a HTML link to a named route.
*
* #param string $name
* #param string $title
* #param array $parameters
* #param array $attributes
* #return string
* #static
*/
public static function linkRoute($name, $title = null, $parameters = array(), $attributes = array()){
return \Illuminate\Html\HtmlBuilder::linkRoute($name, $title, $parameters, $attributes);
}
/**
* Generate a HTML link to a controller action.
*
* #param string $action
* #param string $title
* #param array $parameters
* #param array $attributes
* #return string
* #static
*/
public static function linkAction($action, $title = null, $parameters = array(), $attributes = array()){
return \Illuminate\Html\HtmlBuilder::linkAction($action, $title, $parameters, $attributes);
}
/**
* Generate a HTML link to an email address.
*
* #param string $email
* #param string $title
* #param array $attributes
* #return string
* #static
*/
public static function mailto($email, $title = null, $attributes = array()){
return \Illuminate\Html\HtmlBuilder::mailto($email, $title, $attributes);
}
/**
* Obfuscate an e-mail address to prevent spam-bots from sniffing it.
*
* #param string $email
* #return string
* #static
*/
public static function email($email){
return \Illuminate\Html\HtmlBuilder::email($email);
}
/**
* Generate an ordered list of items.
*
* #param array $list
* #param array $attributes
* #return string
* #static
*/
public static function ol($list, $attributes = array()){
return \Illuminate\Html\HtmlBuilder::ol($list, $attributes);
}
/**
* Generate an un-ordered list of items.
*
* #param array $list
* #param array $attributes
* #return string
* #static
*/
public static function ul($list, $attributes = array()){
return \Illuminate\Html\HtmlBuilder::ul($list, $attributes);
}
/**
* Build an HTML attribute string from an array.
*
* #param array $attributes
* #return string
* #static
*/
public static function attributes($attributes){
return \Illuminate\Html\HtmlBuilder::attributes($attributes);
}
/**
* Obfuscate a string to prevent spam-bots from sniffing it.
*
* #param string $value
* #return string
* #static
*/
public static function obfuscate($value){
return \Illuminate\Html\HtmlBuilder::obfuscate($value);
}
/**
* Register a custom macro.
*
* #param string $name
* #param callable $macro
* #return void
* #static
*/
public static function macro($name, $macro){
\Illuminate\Html\HtmlBuilder::macro($name, $macro);
}
/**
* Checks if macro is registered.
*
* #param string $name
* #return bool
* #static
*/
public static function hasMacro($name){
return \Illuminate\Html\HtmlBuilder::hasMacro($name);
}
}
EDIT
Do you have you config/app.php and composer.json files set up properly?
app.php
'providers' => [
...
Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class,
Illuminate\Html\HtmlServiceProvider::class,
...
];
'aliases' => [
...
'Form' => Illuminate\Html\FormFacade::class,
'Html' => Illuminate\Html\HtmlFacade::class,
...
];
composer.json
"require": {
...
"illuminate/html": "~5.0",
...
},
"require-dev": {
...
"barryvdh/laravel-ide-helper": "~2.0",
...
},
Related
Convert Laravel Script into normal php for WG Openid Login
ive an Laravel Openid Script for Wargaming Openid Login. at the moment i dont use laravel. So i will convert it into an normal PHP Script for an MVC Model based CMS called ilch 2.x For iLch i do some plugins. But im so stupid to convert it. The Problems comes from the request parts of this script. but i cant solf the problems. My Skills are not so good. ` <?php declare(strict_types=1); namespace Azate\Laravel\WargamingAuth; use GuzzleHttp\Client as GuzzleClient; use Illuminate\Contracts\Config\Repository as ConfigRepository; use Illuminate\Contracts\Routing\UrlGenerator; use Illuminate\Http\Request; /** * Class WargamingAuth * * #package Azate\Laravel\WargamingAuth */ class WargamingAuth { /** * Config repository. * * #var ConfigRepository */ protected $configRepository; /** * Illuminate request class. * * #var Request */ protected $request; /** * Illuminate url class. * * #var UrlGenerator */ protected $urlGenerator; /** * Region. * * #var string */ protected $region; /** * Realm * * #var string */ protected $realm; /** * Callback url. * * #var string */ protected $callbackUrl; /** * Creates new instance. * * #param ConfigRepository $configRepository * #param Request $request * #param UrlGenerator $urlGenerator */ public function __construct( ConfigRepository $configRepository, Request $request, UrlGenerator $urlGenerator ) { $this->configRepository = $configRepository; $this->request = $request; $this->urlGenerator = $urlGenerator; $this->region = $this->configRepository->get('wargamingAuth.defaultRegion'); $this->realm = $this->configRepository->get('app.url'); $this->callbackUrl = $this->urlGenerator->route( $this->configRepository->get('wargamingAuth.callbackRoute') ); } /** * Returns the region. * * #return string */ public function getRegion(): string { return $this->region; } /** * Set the region. * * #param string $region */ public function setRegion(string $region) { $this->region = $region; } /** * Returns the realm. * * #return string */ public function getRealm(): string { return $this->realm; } /** * Set the realm. * * #param string $realm */ public function setRealm(string $realm) { $this->realm = $realm; } /** * Returns the OpenID URL. * * #return string */ public function getOpenIdUrl(): string { return 'https://' . $this->region . '.wargaming.net/id/openid/'; } /** * Returns the redirect URL. * * #return string */ public function redirectUrl(): string { $params = [ 'openid.ax.if_available' => 'ext0,ext1', 'openid.ax.mode' => 'fetch_request', 'openid.ax.type.ext0' => 'http://axschema.openid.wargaming.net/spa/id', 'openid.ax.type.ext1' => 'http://axschema.org/namePerson/friendly', 'openid.claimed_id' => 'http://specs.openid.net/auth/2.0/identifier_select', 'openid.identity' => 'http://specs.openid.net/auth/2.0/identifier_select', 'openid.mode' => 'checkid_setup', 'openid.ns' => 'http://specs.openid.net/auth/2.0', 'openid.ns.ax' => 'http://openid.net/srv/ax/1.0', 'openid.realm' => $this->realm, 'openid.return_to' => $this->callbackUrl, ]; return $this->getOpenIdUrl() . '?' . http_build_query($params, '', '&'); } /** * OpenID Positive Assertions. * * #return bool */ private function isPositiveAssertion(): bool { $hasFields = $this->request->has([ 'openid_assoc_handle', 'openid_claimed_id', 'openid_identity', 'openid_mode', 'openid_ns', 'openid_op_endpoint', 'openid_response_nonce', 'openid_return_to', 'openid_sig', 'openid_signed', ]); $isModeIdRes = $this->request->get('openid_mode') === 'id_res'; return $hasFields && $isModeIdRes; } /** * OpenID Verifying the Return URL. * * #return bool */ public function verifyingReturnUrl(): bool { return $this->request->get('openid_return_to') === $this->request->url(); } /** * Get param list for OpenID validation * * #return array */ private function getOpenIdValidationParams(): array { $params = []; $signedParams = explode(',', $this->request->get('openid_signed')); foreach ($signedParams as $item) { $params['openid.' . $item] = $this->request->get('openid_' . str_replace('.', '_', $item)); } $params['openid.mode'] = 'check_authentication'; $params['openid.sig'] = $this->request->get('openid_sig'); return $params; } /** * OpenID Verifying Signatures (Wargaming uses Direct Verification). * * #return bool * * #throws \GuzzleHttp\Exception\GuzzleException */ public function verifyingSignatures(): bool { $httpClient = new GuzzleClient; $response = $httpClient->request('POST', $this->getOpenIdUrl(), [ 'form_params' => $this->getOpenIdValidationParams(), ]); $content = $response->getBody()->getContents(); return strpos($content, 'is_valid:true') !== false; } /** * Process to verify an OpenID assertion. * * #return bool * * #throws \GuzzleHttp\Exception\GuzzleException */ public function verify(): bool { return $this->isPositiveAssertion() && $this->verifyingReturnUrl() && $this->verifyingSignatures(); } /** * Returns the user data. * * #return array */ public function user(): array { return [ 'id' => $this->request->get('openid_ax_value_ext0_1'), 'nickname' => $this->request->get('openid_ax_value_ext1_1'), ]; } } ` I hope i can get help from you I fail with the requests especially with has()
vendor/laravel/framework/src/Illuminate/Session/Store.php:142
* #return string */ protected function prepareForUnserialize($data) { return $data; } /** * Save the session data to storage. * * #return void */ public function save() { $this->ageFlashData(); $this->handler->write($this->getId(), $this->prepareForStorage( serialize($this->attributes) )); $this->started = false; } /** * Prepare the serialized session data for storage. * * #param string $data * #return string */ protected function prepareForStorage($data)
Upload Laravel in host
I uploaded my project from wamp to my host. When I open my site, site shows : (1/1) InvalidArgumentException View [welcome] not found. ..... in FileViewFinder.php line 137 FileViewFinder.php: <?php namespace Illuminate\View; use InvalidArgumentException; use Illuminate\Filesystem\Filesystem; class FileViewFinder implements ViewFinderInterface { /** * The filesystem instance. * * #var \Illuminate\Filesystem\Filesystem */ protected $files; /** * The array of active view paths. * * #var array */ protected $paths; /** * The array of views that have been located. * * #var array */ protected $views = []; /** * The namespace to file path hints. * * #var array */ protected $hints = []; /** * Register a view extension with the finder. * * #var array */ protected $extensions = ['blade.php', 'php', 'css']; /** * Create a new file view loader instance. * * #param \Illuminate\Filesystem\Filesystem $files * #param array $paths * #param array $extensions * #return void */ public function __construct(Filesystem $files, array $paths, array $extensions = null) { $this->files = $files; $this->paths = $paths; if (isset($extensions)) { $this->extensions = $extensions; } } /** * Get the fully qualified location of the view. * * #param string $name * #return string */ public function find($name) { if (isset($this->views[$name])) { return $this->views[$name]; } if ($this->hasHintInformation($name = trim($name))) { return $this->views[$name] = $this->findNamespacedView($name); } return $this->views[$name] = $this->findInPaths($name, $this->paths); } /** * Get the path to a template with a named path. * * #param string $name * #return string */ protected function findNamespacedView($name) { list($namespace, $view) = $this->parseNamespaceSegments($name); return $this->findInPaths($view, $this->hints[$namespace]); } /** * Get the segments of a template with a named path. * * #param string $name * #return array * * #throws \InvalidArgumentException */ protected function parseNamespaceSegments($name) { $segments = explode(static::HINT_PATH_DELIMITER, $name); if (count($segments) != 2) { throw new InvalidArgumentException("View [$name] has an invalid name."); } if (! isset($this->hints[$segments[0]])) { throw new InvalidArgumentException("No hint path defined for [{$segments[0]}]."); } return $segments; } /** * Find the given view in the list of paths. * * #param string $name * #param array $paths * #return string * * #throws \InvalidArgumentException */ protected function findInPaths($name, $paths) { foreach ((array) $paths as $path) { foreach ($this->getPossibleViewFiles($name) as $file) { if ($this->files->exists($viewPath = $path.'/'.$file)) { return $viewPath; } } } throw new InvalidArgumentException("View [$name] not found."); } /** * Get an array of possible view files. * * #param string $name * #return array */ protected function getPossibleViewFiles($name) { return array_map(function ($extension) use ($name) { return str_replace('.', '/', $name).'.'.$extension; }, $this->extensions); } /** * Add a location to the finder. * * #param string $location * #return void */ public function addLocation($location) { $this->paths[] = $location; } /** * Prepend a location to the finder. * * #param string $location * #return void */ public function prependLocation($location) { array_unshift($this->paths, $location); } /** * Add a namespace hint to the finder. * * #param string $namespace * #param string|array $hints * #return void */ public function addNamespace($namespace, $hints) { $hints = (array) $hints; if (isset($this->hints[$namespace])) { $hints = array_merge($this->hints[$namespace], $hints); } $this->hints[$namespace] = $hints; } /** * Prepend a namespace hint to the finder. * * #param string $namespace * #param string|array $hints * #return void */ public function prependNamespace($namespace, $hints) { $hints = (array) $hints; if (isset($this->hints[$namespace])) { $hints = array_merge($hints, $this->hints[$namespace]); } $this->hints[$namespace] = $hints; } /** * Replace the namespace hints for the given namespace. * * #param string $namespace * #param string|array $hints * #return void */ public function replaceNamespace($namespace, $hints) { $this->hints[$namespace] = (array) $hints; } /** * Register an extension with the view finder. * * #param string $extension * #return void */ public function addExtension($extension) { if (($index = array_search($extension, $this->extensions)) !== false) { unset($this->extensions[$index]); } array_unshift($this->extensions, $extension); } /** * Returns whether or not the view name has any hint information. * * #param string $name * #return bool */ public function hasHintInformation($name) { return strpos($name, static::HINT_PATH_DELIMITER) > 0; } /** * Flush the cache of located views. * * #return void */ public function flush() { $this->views = []; } /** * Get the filesystem instance. * * #return \Illuminate\Filesystem\Filesystem */ public function getFilesystem() { return $this->files; } /** * Get the active view paths. * * #return array */ public function getPaths() { return $this->paths; } /** * Get the namespace to file path hints. * * #return array */ public function getHints() { return $this->hints; } /** * Get registered extensions. * * #return array */ public function getExtensions() { return $this->extensions; } } I tried several times but I could not solve this problem I also edited the APP_URL in the .env file, but did not change How can I fix it?
Try to clear your project cache: php artisan config:cache and php artisan cache:clear maybe the cache is looking for the file in a wrong place.
You can connect your host with vagrant ssh , after that go to your project location using CL and run this command: php artisan config:cache to regenerate the configuration. Hope that helps you!
CollectionType field showing empty after manually submitting Symfony Form
I have OneToMany relationship Book <----* BookImage Book: oneToMany: bookImages: targetEntity: BookImage mappedBy: book cascade: [persist,remove] BookImage: manyToOne: book: targetEntity: Book inversedBy: bookImages joinColumn: name: book_id referencedColumnName: id So my Form has a collectionType field. BookType: $builder->add('bookImages', 'collection', array( 'type' => new BookImageType(), 'allow_add' => true, // 'allow_delete' => true, 'by_reference' =>false )); BookImageType: $builder->add('imageName','text',array( 'constraints' => array( new NotBlank(), ) )); $builder->add('imageUrl','text',array( 'constraints' => array( new NotBlank(), ) )); Controller to save the data via Ajax Call: public function addNewSellBookAction(Request $request) { $serializer = $this->container->get('jms_serializer'); $userId = $this->get('security.token_storage')->getToken()->getUser()->getId(); $em = $this->getDoctrine()->getManager(); $content = $request->get('book'); $bookData = json_decode($content, true); $book = new Book(); $bookImage1 = new BookImage(); $bookImage1->setImageName("Amazon Book Image"); $bookImage1->setImageUrl("http://url1.com"); $book->addBookImage($bookImage1); $bookImage2 = new BookImage(); $bookImage2->setImageName("Amazon Book Image"); $bookImage2->setImageUrl("http://url1.com"); $book->addBookImage($bookImage2); $bookData['bookSeller']=$userId; $bookForm = $this->createForm(new BookType(), $book); var_dump($bookForm->getData()->getBookImages()); //Image Data Before Submit $bookForm->submit($bookData); var_dump($bookForm->getData()->getBookImages()); //Image Data After Submit if($bookForm->isValid()){ $em->persist($book); $em->flush(); return $this->createJsonResponse('success',array('successTitle'=>"Book Successfully added to sell List")); }else{ $error= $serializer->serialize($bookForm,'json'); return new Response($error,200); } } Now BookImage Data Before & After Submit are: object(Doctrine\Common\Collections\ArrayCollection)[580] private 'elements' => array (size=2) 0 => object(AppBundle\Entity\BookImage)[581] protected 'id' => null private 'imageName' => string 'Amazon Book Image' (length=17) private 'imageUrl' => string 'http://url1.com' (length=15) private 'titleImage' => null private 'book' => object(AppBundle\Entity\Book)[578] ... 1 => object(AppBundle\Entity\BookImage)[582] protected 'id' => null private 'imageName' => string 'Amazon Book Image' (length=17) private 'imageUrl' => string 'http://url1.com' (length=15) private 'titleImage' => null private 'book' => object(AppBundle\Entity\Book)[578] ... object(Doctrine\Common\Collections\ArrayCollection)[580] private 'elements' => array (size=2) 0 => object(AppBundle\Entity\BookImage)[581] protected 'id' => null private 'imageName' => null private 'imageUrl' => null private 'titleImage' => boolean false private 'book' => object(AppBundle\Entity\Book)[578] ... 1 => object(AppBundle\Entity\BookImage)[582] protected 'id' => null private 'imageName' => null private 'imageUrl' => null private 'titleImage' => boolean false private 'book' => object(AppBundle\Entity\Book)[578] Why after submitting data the collectionType field value got null or empty? Though the other fields have the value perfectly. Can anyone explain? or do I have any problem with the structure? Thanks in advance. Book Entity class Book { /** * Constructor */ public function __construct() { $this->messages = new ArrayCollection(); $this->bookImages = new ArrayCollection(); } /** * #var integer * */ protected $id; /** * #var string * */ private $bookTitle; /** * #var string * */ private $bookDirectorAuthorArtist; /** * #var string * */ private $bookEdition; /** * #var string * */ private $bookIsbn10; /** * #var string * */ private $bookIsbn13; /** * #var string * */ private $bookPublisher; /** * #var date * */ private $bookPublishDate; /** * #var string * */ private $bookBinding; /** * #var string * */ private $bookPage; /** * #var string * */ private $bookPriceSell; /** * #var string * */ private $bookLanguage; /** * #var text * */ private $bookDescription; /** * #var string * */ private $bookCondition; /** * #var string * */ private $bookIsHighlighted; /** * #var string * */ private $bookHasNotes; /** * #var string * */ private $bookComment; /** * #var string * */ private $bookContactMethod; /** * #var string * */ private $bookContactHomeNumber; /** * #var string * */ private $bookContactCellNumber; /** * #var string * */ private $bookContactEmail; /** * #var string * */ private $bookIsAvailablePublic; /** * #var boolean * */ private $bookPaymentMethodCaShOnExchange; /** * #var boolean * */ private $bookPaymentMethodCheque; /** * #var date * */ private $bookAvailableDate; private $bookImages; private $bookBuyer; private $bookSeller; private $messages; /** * Get id * * #return integer */ public function getId() { return $this->id; } /** * Set bookTitle * * #param string $bookTitle * #return Book */ public function setBookTitle($bookTitle) { $this->bookTitle = $bookTitle; return $this; } /** * Get bookTitle * * #return string */ public function getBookTitle() { return $this->bookTitle; } /** * Set bookDirectorAuthorArtist * * #param string $bookDirectorAuthorArtist * #return Book */ public function setBookDirectorAuthorArtist($bookDirectorAuthorArtist) { $this->bookDirectorAuthorArtist = $bookDirectorAuthorArtist; return $this; } /** * Get bookDirectorAuthorArtist * * #return string */ public function getBookDirectorAuthorArtist() { return $this->bookDirectorAuthorArtist; } /** * Set bookEdition * * #param string $bookEdition * #return Book */ public function setBookEdition($bookEdition) { $this->bookEdition = $bookEdition; return $this; } /** * Get bookEdition * * #return string */ public function getBookEdition() { return $this->bookEdition; } /** * Set bookIsbn10 * * #param string $bookIsbn10 * #return Book */ public function setBookIsbn10($bookIsbn10) { $this->bookIsbn10 = $bookIsbn10; return $this; } /** * Get bookIsbn10 * * #return string */ public function getBookIsbn10() { return $this->bookIsbn10; } /** * Set bookIsbn13 * * #param string $bookIsbn13 * #return Book */ public function setBookIsbn13($bookIsbn13) { $this->bookIsbn13 = $bookIsbn13; return $this; } /** * Get bookIsbn13 * * #return string */ public function getBookIsbn13() { return $this->bookIsbn13; } /** * Set bookPublisher * * #param string $bookPublisher * #return Book */ public function setBookPublisher($bookPublisher) { $this->bookPublisher = $bookPublisher; return $this; } /** * Get bookPublisher * * #return string */ public function getBookPublisher() { return $this->bookPublisher; } /** * Set bookPublishDate * * #param \DateTime $bookPublishDate * #return Book */ public function setBookPublishDate($bookPublishDate) { $this->bookPublishDate = $bookPublishDate; return $this; } /** * Get bookPublishDate * * #return \DateTime */ public function getBookPublishDate() { return $this->bookPublishDate; } /** * Set bookBinding * * #param string $bookBinding * #return Book */ public function setBookBinding($bookBinding) { $this->bookBinding = $bookBinding; return $this; } /** * Get bookBinding * * #return string */ public function getBookBinding() { return $this->bookBinding; } /** * Set bookPage * * #param string $bookPage * #return Book */ public function setBookPage($bookPage) { $this->bookPage = $bookPage; return $this; } /** * Get bookPage * * #return string */ public function getBookPage() { return $this->bookPage; } /** * Set bookLanguage * * #param string $bookLanguage * #return Book */ public function setBookLanguage($bookLanguage) { $this->bookLanguage = $bookLanguage; return $this; } /** * Get bookLanguage * * #return string */ public function getBookLanguage() { return $this->bookLanguage; } /** * Add messages * * #param \AppBundle\Entity\Message $messages * #return Book */ public function addMessage(\AppBundle\Entity\Message $messages) { $this->messages[] = $messages; return $this; } /** * Remove messages * * #param \AppBundle\Entity\Message $messages */ public function removeMessage(\AppBundle\Entity\Message $messages) { $this->messages->removeElement($messages); } /** * Get messages * * #return \Doctrine\Common\Collections\Collection */ public function getMessages() { return $this->messages; } /** * Set bookBuyer * * #param \AppBundle\Entity\User $bookBuyer * #return Book */ public function setBookBuyer(\AppBundle\Entity\User $bookBuyer = null) { $this->bookBuyer = $bookBuyer; return $this; } /** * Get bookBuyer * * #return \AppBundle\Entity\User */ public function getBookBuyer() { return $this->bookBuyer; } /** * Set bookSeller * * #param \AppBundle\Entity\User $bookSeller * #return Book */ public function setBookSeller(\AppBundle\Entity\User $bookSeller = null) { $this->bookSeller = $bookSeller; return $this; } /** * Get bookSeller * * #return \AppBundle\Entity\User */ public function getBookSeller() { return $this->bookSeller; } /** * Set bookPriceSell * * #param string $bookPriceSell * #return Book */ public function setBookPriceSell($bookPriceSell) { $this->bookPriceSell = $bookPriceSell; return $this; } /** * Get bookPriceSell * * #return string */ public function getBookPriceSell() { return $this->bookPriceSell; } /** * Set bookDescription * * #param string $bookDescription * #return Book */ public function setBookDescription($bookDescription) { $this->bookDescription = $bookDescription; return $this; } /** * Get bookDescription * * #return string */ public function getBookDescription() { return $this->bookDescription; } /** * Set bookCondition * * #param string $bookCondition * #return Book */ public function setBookCondition($bookCondition) { $this->bookCondition = $bookCondition; return $this; } /** * Get bookCondition * * #return string */ public function getBookCondition() { return $this->bookCondition; } /** * Set bookIsHighlighted * * #param string $bookIsHighlighted * #return Book */ public function setBookIsHighlighted($bookIsHighlighted) { $this->bookIsHighlighted = $bookIsHighlighted; return $this; } /** * Get bookIsHighlighted * * #return string */ public function getBookIsHighlighted() { return $this->bookIsHighlighted; } /** * Set bookHasNotes * * #param string $bookHasNotes * #return Book */ public function setBookHasNotes($bookHasNotes) { $this->bookHasNotes = $bookHasNotes; return $this; } /** * Get bookHasNotes * * #return string */ public function getBookHasNotes() { return $this->bookHasNotes; } /** * Set bookComment * * #param string $bookComment * #return Book */ public function setBookComment($bookComment) { $this->bookComment = $bookComment; return $this; } /** * Get bookComment * * #return string */ public function getBookComment() { return $this->bookComment; } /** * Set bookContactMethod * * #param string $bookContactMethod * #return Book */ public function setBookContactMethod($bookContactMethod) { $this->bookContactMethod = $bookContactMethod; return $this; } /** * Get bookContactMethod * * #return string */ public function getBookContactMethod() { return $this->bookContactMethod; } /** * Set bookContactHomeNumber * * #param string $bookContactHomeNumber * #return Book */ public function setBookContactHomeNumber($bookContactHomeNumber) { $this->bookContactHomeNumber = $bookContactHomeNumber; return $this; } /** * Get bookContactHomeNumber * * #return string */ public function getBookContactHomeNumber() { return $this->bookContactHomeNumber; } /** * Set bookContactCellNumber * * #param string $bookContactCellNumber * #return Book */ public function setBookContactCellNumber($bookContactCellNumber) { $this->bookContactCellNumber = $bookContactCellNumber; return $this; } /** * Get bookContactCellNumber * * #return string */ public function getBookContactCellNumber() { return $this->bookContactCellNumber; } /** * Set bookContactEmail * * #param string $bookContactEmail * #return Book */ public function setBookContactEmail($bookContactEmail) { $this->bookContactEmail = $bookContactEmail; return $this; } /** * Get bookContactEmail * * #return string */ public function getBookContactEmail() { return $this->bookContactEmail; } /** * Set bookIsAvailablePublic * * #param string $bookIsAvailablePublic * #return Book */ public function setBookIsAvailablePublic($bookIsAvailablePublic) { $this->bookIsAvailablePublic = $bookIsAvailablePublic; return $this; } /** * Get bookIsAvailablePublic * * #return string */ public function getBookIsAvailablePublic() { return $this->bookIsAvailablePublic; } /** * Set bookPaymentMethodCaShOnExchange * * #param string $bookPaymentMethodCaShOnExchange * #return Book */ public function setBookPaymentMethodCaShOnExchange($bookPaymentMethodCaShOnExchange) { $this->bookPaymentMethodCaShOnExchange = $bookPaymentMethodCaShOnExchange; return $this; } /** * Get bookPaymentMethodCaShOnExchange * * #return string */ public function getBookPaymentMethodCaShOnExchange() { return $this->bookPaymentMethodCaShOnExchange; } /** * Set bookPaymentMethodCheck * * #param string $bookPaymentMethodCheck * #return Book */ public function setBookPaymentMethodCheck($bookPaymentMethodCheck) { $this->bookPaymentMethodCheck = $bookPaymentMethodCheck; return $this; } /** * Get bookPaymentMethodCheck * * #return string */ public function getBookPaymentMethodCheck() { return $this->bookPaymentMethodCheck; } /** * Add bookImages * * #param \AppBundle\Entity\BookImage $bookImages * #return Book */ public function addBookImage(\AppBundle\Entity\BookImage $bookImages) { $this->bookImages->add($bookImages); $bookImages->setBook($this); return $this; } /** * Remove bookImages * * #param \AppBundle\Entity\BookImage $bookImages */ public function removeBookImage(\AppBundle\Entity\BookImage $bookImages) { $this->bookImages->removeElement($bookImages); } /** * Get bookImages * * #return \Doctrine\Common\Collections\Collection */ public function getBookImages() { return $this->bookImages; } /** * Set bookPaymentMethodCheque * * #param boolean $bookPaymentMethodCheque * #return Book */ public function setBookPaymentMethodCheque($bookPaymentMethodCheque) { $this->bookPaymentMethodCheque = $bookPaymentMethodCheque; return $this; } /** * Get bookPaymentMethodCheque * * #return boolean */ public function getBookPaymentMethodCheque() { return $this->bookPaymentMethodCheque; } /** * Set bookAvailableDate * * #param \DateTime $bookAvailableDate * #return Book */ public function setBookAvailableDate($bookAvailableDate) { $this->bookAvailableDate = $bookAvailableDate; return $this; } /** * Get bookAvailableDate * * #return \DateTime */ public function getBookAvailableDate() { return $this->bookAvailableDate; } public function __toString() { return strval($this->id); } } BookImage Entity class BookImage { /** * #var integer * */ protected $id; /** * #var string * */ private $imageName; /** * #var string * */ private $imageUrl; /** * #var boolean * */ private $titleImage; private $book; /** * Get id * * #return integer */ public function getId() { return $this->id; } /** * Set imageName * * #param string $imageName * #return BookImage */ public function setImageName($imageName) { $this->imageName = $imageName; return $this; } /** * Get imageName * * #return string */ public function getImageName() { return $this->imageName; } /** * Set imageUrl * * #param string $imageUrl * #return BookImage */ public function setImageUrl($imageUrl) { $this->imageUrl = $imageUrl; return $this; } /** * Get imageUrl * * #return string */ public function getImageUrl() { return $this->imageUrl; } /** * Set titleImage * * #param boolean $titleImage * #return BookImage */ public function setTitleImage($titleImage) { $this->titleImage = $titleImage; return $this; } /** * Get titleImage * * #return boolean */ public function getTitleImage() { return $this->titleImage; } /** * Set book * * #param \AppBundle\Entity\Book $book * #return BookImage */ public function setBook(\AppBundle\Entity\Book $book = null) { $this->book = $book; return $this; } /** * Get book * * #return \AppBundle\Entity\Book */ public function getBook() { return $this->book; } public function __toString() { return strval($this->id); } }
I have been trying to find the answer for almost 7 days now and finally came up with a solution. But don't know if it a bad practice or not. Just have to put the data as an array into submitData. After submitting the value will be added to that particular entity via form. public function addNewSellBookAction(Request $request) { $em = $this->getDoctrine()->getManager(); $serializer = $this->container->get('jms_serializer'); $userId = $this->get('security.token_storage')->getToken()->getUser()->getId(); $content = $request->get('book'); $bookData = json_decode($content, true); $bookData['bookImages']=array(); array_push($bookData['bookImages'],array( 'imageName'=>"Amazon Book Image", 'imageUrl'=>"http://url1.com" )); array_push($bookData['bookImages'],array( 'imageName'=>"Amazon Book Image", 'imageUrl'=>"http://url1.com" )); $bookData['bookSeller']=$userId; $book = new Book(); $bookForm = $this->createForm(new BookType(),$book); var_dump($bookForm->getData()->getBookImages()); $bookForm->submit($bookData); var_dump($book->getBookImages()); if($bookForm->isValid()){ $em->persist($book); $em->flush(); return $this->createJsonResponse('success',array('successTitle'=>"Book Successfully added to sell List")); }else{ $error= $serializer->serialize($bookForm,'json'); return new Response($error,200); } } Hope it will help the others. Bounty Still Open If anyone provides answer with best practice
I'm not sure. As per the documentation by symfony Check Task controller line number 20 and 23 $task->getTags()->add($tag2); The tags collection is accessible naturally via $task->getTags() and can be persisted to the database or used however you need. I think you are missing something here $book->addBookImage($bookImage1); Try this instead $book->getBookImages()->add($bookImage1);
If you don't need to modify images with the request data add new images after you submit the form. $bookForm->submit($bookData); // ... $book->addBookImage($bookImage1);
->find($id) in entity returns an empty proxy object symfony2
I'm doing a search on an entity, but this returns me a proxy object. Thus I am trying to do the search. $em = $this->getDoctrine()->getEntityManager(); $tipou = $em->getRepository('SertecomvendoautosBundle:TipoUsuario')->find(5); In the database, table tipo_usuario I have only two records with ID 4 and 5, but to make the search with ID 4, doctrine returns the object for me and not the proxy object that returns me with ID 5. $em = $this->getDoctrine()->getEntityManager(); $tipou = $em->getRepository('SertecomvendoautosBundle:TipoUsuario')->find(4); This brings the object in the normal way. Really do not understand this behavior that doctrine, I would like to know what happens with this. This is code of entity tipo_usuario. class TipoUsuario { /** * #var string $tipouNombre */ private $tipouNombre; /** * #var string $tipouToken */ private $tipouToken; /** * #var datetime $tipouCreatedAt */ private $tipouCreatedAt; /** * #var datetime $tipouUpdatedAt */ private $tipouUpdatedAt; /** * #var integer $tipouId */ private $tipouId; /** * Set tipouNombre * * #param string $tipouNombre */ public function setTipouNombre($tipouNombre) { $this->tipouNombre = $tipouNombre; } /** * Get tipouNombre * * #return string */ public function getTipouNombre() { return $this->tipouNombre; } /** * Set tipouToken * * #param string $tipouToken */ public function setTipouToken($tipouToken) { $this->tipouToken = $tipouToken; } /** * Get tipouToken * * #return string */ public function getTipouToken() { return $this->tipouToken; } /** * Set tipouCreatedAt * * #param datetime $tipouCreatedAt */ public function setTipouCreatedAt($tipouCreatedAt) { $this->tipouCreatedAt = $tipouCreatedAt; } /** * Get tipouCreatedAt * * #return datetime */ public function getTipouCreatedAt() { return $this->tipouCreatedAt; } /** * Set tipouUpdatedAt * * #param datetime $tipouUpdatedAt */ public function setTipouUpdatedAt($tipouUpdatedAt) { $this->tipouUpdatedAt = $tipouUpdatedAt; } /** * Get tipouUpdatedAt * * #return datetime */ public function getTipouUpdatedAt() { return $this->tipouUpdatedAt; } /** * Get tipouId * * #return integer */ public function getTipouId() { return $this->tipouId; }