Passing data to buildForm() in Symfony 2.8, 3.0 and above

后端 未结 4 1346
暗喜
暗喜 2020-11-27 11:36

My application currently passes data to my form type using the constructor, as recommended in this answer. However the Symfony 2.8 upgrade guide advises that passing a type

4条回答
  •  心在旅途
    2020-11-27 12:37

    Here's how to pass the data to an embedded form for anyone using Symfony 3. First do exactly what @sekl outlined above and then do the following:

    In your primary FormType

    Pass the var to the embedded form using 'entry_options'

    ->add('your_embedded_field', CollectionType::class, array(
              'entry_type' => YourEntityType::class,
              'entry_options' => array(
                'var' => $this->var
              )))
    

    In your Embedded FormType

    Add the option to the optionsResolver

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Yourbundle\Entity\YourEntity',
            'var' => null
        ));
    }
    

    Access the variable in your buildForm function. Remember to set this variable before the builder function. In my case I needed to filter options based on a specific ID.

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $this->var = $options['var'];
    
        $builder
            ->add('your_field', EntityType::class, array(
              'class' => 'YourBundle:YourClass',
              'query_builder' => function ($er) {
                  return $er->createQueryBuilder('u')
                    ->join('u.entity', 'up')
                    ->where('up.id = :var')
                    ->setParameter("var", $this->var);
               }))
         ;
    }
    

提交回复
热议问题