Symfony2 - How to set, and get, options when using a Form Class?

后端 未结 6 1470
暖寄归人
暖寄归人 2021-02-06 08:29

I am using Form Classes to build the various form in my project.

In the Entity Type file, for the buildForm function, there is a secondary parameter of \"array $options\

6条回答
  •  暖寄归人
    2021-02-06 08:54

    Well acording to this Google Groups

    "greg0ire" was right, in fact I have tried it and works perfect!!!. You said "I dont really want to go about "hacking" any of the core structure" but you end up using no the best approach.. in matter of fact, from my point of view, you end up doing what you didn't want to do.

    So at the end you should do this:

    at the formType

    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('slug')
            ->add('reference')
            ->add('description')
            ->add('active_from')
            ->add('active_till')
            ->add('is_active')
            ->add('category', 'entity', array(
                'class' => 'DEMO\DemoBundle\Entity\Product\ProductCategory',
                'query_builder' => function(EntityRepository $er) {
                    return $er->createQueryBuilder('u')
                        ->where('u.section = :id')
                        ->setParameter('id', $options['id'])
                        ->orderBy('u.root', 'ASC')
                        ->addOrderBy('u.lft', 'ASC');
                },
                'empty_value' => 'Choose an option',
                'property' => 'indentedName',
            ));
    }
    
    public function getDefaultOptions()
    {
        return array(
            'data_class' => 'DEMO\DemoBundle\Entity\Product\Product'
            'id' => null
        );
    }
    

    And in the controller

    $form = $this->createForm(new ProductType(), $product, array('id' => $id ));
    

提交回复
热议问题