Search code examples
phpsymfonydoctrinetwigsonata-admin

Sonata AdminBundle with a Child cannot be rendered


Im trying to configure the Sonata AdminBundle. Its a very interesting bundle with many functionalities however it is not straightforward to use. I have a Post entity so I can tweak the posts, as in the doc manual. I want to implement a child Admin, for the comments of each post (a Many to One relationship). I implemented it as a service and a __toString() method for the variable however I get the following error:

An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class Doctrine\ORM\PersistentCollection could not be converted to string") in SonataDoctrineORMAdminBundle:CRUD:list_orm_many_to_one.html.twig at line 17.

I do not understand why not it could not be converted to a string the content of the ManyToOne variable. Any help is appreciated here.

Here is the Post entity code:

<?php

namespace Blog\BlogBundle\Entity;

class Post

/**
 * @var ArrayCollection
 *
 * @ORM\OneToMany(targetEntity="Comment", mappedBy="post", cascade={"remove"})
 */
private $comments;

/**
* Construct DateTime and Comments Array
*/
public function __construct()
{
    $this->createdAt = new \DateTime();

    $this->comments = new ArrayCollection();
}

/**
 * @return mixed
 */
public function __toString()
{
    return $this->comments;
}

Other private and setters and getters

Solution

  • Remove

    /**
     * @return mixed
     */
    public function __toString()
    {
        return $this->comments;
    }
    

    from your Post entity and add it to your comments entity but change $this->comments to the field used for the body of your comment.