How can I get ID of entity in form type?

Tags: , ,



I have form type for build form of category:

class CategoryType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
                ->add('published', 'checkbox', array(
                    'required' => FALSE,
                ))
                ->add('parent', 'entity', array(
                    'class' => 'BWBlogBundle:Category',
                    'property' => 'name',
                    'query_builder' => function(EntityRepository $er) {
                        return $er->createQueryBuilder('c')
                                ->where('c.id != :id')
                                ->setParameter('id', ... /* I need to get category ID here */)
                            ;
                    },
                    'required' => FALSE,
                    'empty_value' => 'Корневая категория',
                ))
            // other my code

How can I get category ID of entity in query_builder closure in buildForm action?

Answer

answer for your question into this two questions symfony-2-how-to-pass-data-to-formbuilder and passing-data-from-controller-to-type-symfony2

1) create category variable and __construct() method into CategoryType class:

private category;
public function __construct(yourBundleCategory $category){

   $this->category = $category ;

}

2) use category variable in buildForm() method into CategoryType class :

public function buildForm(FormBuilderInterface $builder, array $options)
{

    $category = $this->category;

    $builder
            ->add('published', 'checkbox', array(
                'required' => FALSE,
            ))
            ->add('parent', 'entity', array(
                'class' => 'BWBlogBundle:Category',
                'property' => 'name',
                'query_builder' => function(EntityRepository $er) use ($category){
                    return $er->createQueryBuilder('c')
                            ->where('c.id != :id')
                            ->setParameter('id', $category->getId())
                        ;
                },
                'required' => FALSE,
                'empty_value' => 'Корневая категория',
            ))

    }

finally when you create form in your controller :

$category = new Category();

$form = $this->createForm(new CategoryType($category),$category);


Source: stackoverflow