stivlo
stivlo

Reputation: 85496

Symfony2 __toString() generation

Does Symfony2 have an automatic __toString() generation based on the entity fields, or an annotation to say that the __toString() should be generated, similar to Java Roo?

Upvotes: 2

Views: 3561

Answers (1)

Nick
Nick

Reputation: 2922

I cannot find such a feature under the annotations reference, and the consensus among the Google Group seems to side with defining __toString() on the object.

If you use an IDE such as Net Beans, a simple CTRL+SPACE hotkey and click will automatically generate the __toString() for you, you'd simply need to fill out the refence to whichever attribute you want to use to represent the object.

Furthermore, you could take that one step further and define an Entity template (which is what I do in Net Beans). Something like this could save you some time, keeping in mind Doctrine2 is my ORM in this example, and I use the annotations method of defining my entities:

<?php

namespace Foo\BarBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
//use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity
 */
class ${name}
{
    /**
     * @ORM\Id @ORM\Column(type="integer")
     * @ORM\GeneratedValue
     */
    protected $id;

    public function __toString()
    {
        //return $this->get();
    }
}

This automatically fills out the class name and has ArrayCollection commented out (so I can easily add that in if the entity requires it). This would leave you with simply needing to fill in the rest of whatever method you'd like to use for __toString();

${name} is a template variable in NetBeans.

Upvotes: 1

Related Questions