symfony2 ContextErrorException: Catchable Fatal Error: Object of class Proxies\__CG__\...\Entity\... could not be converted to string
doctrine, orm, php, symfony, tostring
Solution
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.
Add a `__toString()` method to your object
/**
* (Add this method into your class)
*
* @return string String representation of this class
*/
public function __toString()
{
return $this->name;
}
OR add the property key to your form builder
// 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`.
Problem
I have encountered something weird: I created three doctrine entities via `app/console doctrine:generate:entity`: - Category - User - Post 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?