Catchable Fatal Error: Object of class could not be converted to string

14,923

Here what I think :

You are trying to save a Category object as parent, but in the following code :

/**
 *
 * @ORM\Column(type="integer", nullable=true)
 */
protected $parent;

You said that a parent is an integer, so the framework try to save the parent category as an integer but to feet it it's probably converting the object as a string before, and so it crashes...

I'm not totally sure, but you should rethink your property "$parent".

It should be a self referencing relation.

Example :

/**
 * @OneToMany(targetEntity="Category", mappedBy="parent")
 */
private $children;

/**
 * @ManyToOne(targetEntity="Category", inversedBy="children")
 * @JoinColumn(name="parent_id", referencedColumnName="id")
 */
protected $parent;

public function __construct() {
    $this->children = new \Doctrine\Common\Collections\ArrayCollection();
}

Don't forget to refactor your getter / setter :

    /**
     * Set parent
     *
     * @param \CategoryBundle\Entity\Category $parent
     */
    public function setParent(\CategoryBundle\Entity\Category $parent = null)
    {
        $this->parent = $parent;
    }

    /**
     * Get parent
     *
     * @return \CategoryBundle\Entity\Category 
     */
    public function getParent()
    {
        return $this->parent;
    }

Hope this is the solution !

Share:
14,923

Related videos on Youtube

Reynier
Author by

Reynier

Updated on June 04, 2022

Comments

  • Reynier
    Reynier almost 2 years

    I have this Entity defined:

    namespace CategoryBundle\Entity;
    
    use Doctrine\ORM\Mapping as ORM;
    use Gedmo\Mapping\Annotation as Gedmo;
    
    /**
     * @ORM\Entity
     * @ORM\Table(name="category")
     */
    class Category {
    
        /**
         * @ORM\Id
         * @ORM\Column(type="integer")
         * @ORM\GeneratedValue(strategy="AUTO")
         * 
         */
        protected $id;
    
        /**
         *
         * @ORM\Column(type="string", length=255, nullable=false)
         */
        protected $name;
    
        /**
         *
         * @ORM\Column(type="integer", nullable=true)
         */
        protected $parent;
    
        /**
         *
         * @ORM\Column(type="string", length=255, nullable=true)
         */
        protected $description;
    
        /**
         *
         * @ORM\Column(type="integer")
         */
        protected $age_limit;
    
        /**
         * @Gedmo\Timestampable(on="create")
         * @ORM\Column(name="created", type="datetime")
         */
        protected $created;
    
        /**
         * @Gedmo\Timestampable(on="update")
         * @ORM\Column(name="modified", type="datetime")
         */
        protected $modified;
    
        public function getId() {
            return $this->id;
        }
    
        public function setParent(Category $parent = null) {
            $this->parent = $parent;
        }
    
        public function getParent() {
            return $this->parent;
        }
    
        public function setName($name) {
            $this->name = $name;
        }
    
        public function getName() {
            return $this->name;
        }
    
        public function setDescription($description) {
            $this->description = $description;
        }
    
        public function getDescription() {
            return $this->description;
        }
    
        public function setAgeLimit($age_limit) {
            $this->age_limit = $age_limit;
        }
    
        public function getAgeLimit() {
            return $this->age_limit;
        }
    
        public function setCreated($created) {
            $this->created = $created;
        }
    
        public function getCreated() {
            return $this->created;
        }
    
        public function setModified($modified) {
            $this->modified = $modified;
        }
    
        public function getModified() {
            return $this->modified;
        }
    }
    

    Then I have this method in my controller for handle form submission:

    /**
     * Handle category creation
     *
     * @Route("/category/create", name="category_create")
     * @Method("POST")
     * @Template("CategoryBundle:Default:new.html.twig")
     */
    public function createAction(Request $request) {
        $entity = new Category();
        $form = $this->createForm(new CategoryType(), $entity);
        $form->handleRequest($request);
    
        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
    
            return $this->redirect($this->generateUrl('category_list'));
        }
    
        return $this->render('CategoryBundle:Default:new.html.twig', array(
                    'entity' => $entity,
                    'form' => $form->createView(),
        ));
    }
    

    And finally this is my CategoryType.php:

    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
                ->add('parent', 'entity', array('class' => 'CategoryBundle:Category', 'property' => 'name', 'required' => false))
                ->add('name')
                ->add('description')
                ->add('age_limit');
    }
    

    When I try to save data I get this error:

    An exception occurred while executing 'INSERT INTO category (name, parent, description, age_limit, created, modified) VALUES (?, ?, ?, ?, ?, ?)' with params ["Cat2", {}, null, 2, "2013-08-06 09:58:03", "2013-08-06 09:58:03"]:

    Catchable Fatal Error: Object of class CategoryBundle\Entity\Category could not be converted to string in /var/www/html/vendor/doctrine/dbal/lib/Doctrine/DBAL/Statement.php line 138

    What I'm doing wrong? How do I access to the property in my method so I can save the value?

    UPDATE

    Based on suggestions made by @sybio, I rewrite my Entity so now I have this:

    /**
     * @ManyToOne(targetEntity="Category")
     * @JoinColumn(name="parent", referencedColumnName="id")
     */
    protected $parent;
    

    Is that right?

  • Reynier
    Reynier over 10 years
    you're totally right, $parent is a you said "a self relationship". Since this are my first steps with Symfony2 I'll need a bit of help from you, can you take a look at my edition?
  • Sybio
    Sybio over 10 years
    Your property is good now (you choose a One to Many self-referencing unidirectionnal relation), and the field will be named "parent" in the database. Check my edit I pasted what you should have as getter and setter ;). Enjoy !
  • Sybio
    Sybio over 10 years
    Meant a "Many To One self-referencing unidirectionnal" relation (not "One To Many") *