Symfony 2 - how to pass data to formBuilder?

前端 未结 6 610
独厮守ぢ
独厮守ぢ 2020-11-30 03:50

I\'m using entity choice list in my form. I want to use only specific entities (in example: only groups that user belongs to) So, in controller, I\'m getting these groups, a

6条回答
  •  借酒劲吻你
    2020-11-30 04:15

    //In controller pass the value which you want to use in builder form in array like
    
    $object = new Question();
    $form->create(new QuestionType() , $object , array('sqtname'=>2,'question_type'=>2));
    
    
    //In Form type class
    public function buildForm(FormBuilderInterface $builder , array $options)
        {  
         //for setting data field dynamically 
      if (array_key_exists('question_type', $options) && $options['question_type'] != '') {
        $data = $em->getReference("RecrutOnlineStandardBundle:StdQuestionType",$options['question_type']->getId());
      } else {
        $data = "";
      }
    
    
      $builder->add('StdQuestionType', 'entity', array(
            'class' => 'TestStandardBundle:StdQuestionType',
            'property' => 'name',
            'empty_value' => 'Sélectionner un question type',
            'required' => true,
            'data' => $data,
            'query_builder' => function(EntityRepository $er ) use ( $options ) {
                if (isset($options['sqtname']) && $options['sqtname'] != '') {
                    return $er->createQueryBuilder('sqt')
                                    ->where("sqt.name!= ".$options['sqtname']);
                } else{
                   return $er->createQueryBuilder('sqt');
                }
            }
        ));
     }
    
     public function setDefaultOptions(OptionsResolverInterface $resolver)
         {
           $resolver->setDefaults(array(
             'data_class' => 'Test\QuestionBundle\Entity\Question',
             'required' => false,
             'sqtname' => '',
             'question_type' =>'' 
           ));
         }
    

提交回复
热议问题