Symfony Form render with Self Referenced Entity

Posted by benarth on Stack Overflow See other posts from Stack Overflow or by benarth
Published on 2014-06-12T14:46:50Z Indexed on 2014/06/12 15:24 UTC
Read the original article Hit count: 237

Filed under:
|
|

I have an Entity containing Self-Referenced mapping.

class Category
{

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=100)
     */
    private $name;

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

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

}

In my CategoryType I have this :

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $plan = $this->plan;

    $builder->add('name');

    $builder->add('parent', 'entity', array(
        'class' => 'xxxBundle:Category',
        'property' => 'name',
        'empty_value' => 'Choose a parent category',
        'required' => false,
        'query_builder' => function(EntityRepository $er) use ($plan) {
            return $er->createQueryBuilder('u')
                ->where('u.plan = :plan')
                ->setParameter('plan', $plan)
                ->orderBy('u.id', 'ASC');
        },
    ));
}

Actually, when I render the form field Category this is something like

  • Cat1
  • Cat2
  • Cat3
  • Subcat1
  • Subcat2
  • Cat4

I would like to know if it's possible and how to display something more like, a kind of a simple tree representation :

  • Cat1
  • Cat2
  • Cat3
  • -- Subcat1
  • -- Subcat2
  • Cat4

Regards.

© Stack Overflow or respective owner

Related posts about forms

Related posts about symfony2