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

后端 未结 6 1467
暖寄归人
暖寄归人 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:53

    Pass the options through the forms class __construct method, like so:

    use Doctrine\ORM\EntityRepository;
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilder;
    
    class ProductType extends AbstractType
    {
    
        private $options = array();
        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', $this->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'
            );
        }
    
        public function getName()
        {
            return 'demo_demobundle_product_type';
        }
    
        public function __construct(array $options)
        {
            $this->options = $options;
        }
    }
    

    And then you can do:

    new ProductType(array('id'=>1));
    

提交回复
热议问题