I have encountered something weird:
I created three doctrine entities via app/console doctrine:generate:entity
:
I set up the relationships and everything works fine with the fixtures data (app/console doctrine:fixtures:load
).
A post belongs to a single category (category_id), and has one author (user_id).
I used app/console doctrine:generate:crud
to get CRUD operations for all my entities.
When I update a post, I get this strange error:
ContextErrorException: Catchable Fatal Error: Object of class Proxies__CG__...\BlogBundle\Entity\Category could not be converted to string
In order to correctly display the dropdown fields I use in PostType()
:
$builder ....
->add('categoryId','entity', array(
'class' => 'HotelBlogBundle:Category',
'property'=>'name'
))
->add('userId','entity',array(
'class'=>'UserBundle:User',
'property'=>'username'
))
Since I specify the property
option I don't need a __toString()
in my Entity classes.
If I create a __toString()
like this (both in Category & User Entities), the error is gone and works:
public function __toString()
{
return (string) $this->getId();
}
I am not sure if I do it the right way.
Also, since a Category
& User
object is passed to category_id
and user_id
fields, Doctrine (or Symfony) should be able to figure out the id column. What am I missing? Is there another way of doing this?
I just ran into this issue with the mentioned error (and ended up here), I'll post the solution that worked for me - seeing as there are no other answers.
Like the OP, I also created a new table and join using Doctrine.
This error is telling us that the joined object
cannot be converted to a string
. We have to either provide a __toString()
method in the object so it can be converted to a string, or we can specify which field we want to return in our Form Builder using the property
key.
__toString()
method to your object/**
* (Add this method into your class)
*
* @return string String representation of this class
*/
public function __toString()
{
return $this->name;
}
// where `name` equals your field name you want returned
$builder->add('category', null, ['property' => 'name'])
I simply added the __toString()
method to my entity
, I only have the fields id
and name
- so the only string representation is the name
.
In symfony 3, you can't use property.
Here the error message : The option "property" does not exist. ...
It's because the entity field doesn't use the option "property" anymore (documentation).
You should use the option "choice_label" instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With