2015-07-21 58 views
1

我有一个实体Question和表单编辑问题QuestionType。我可以成功编辑一个问题。现在我创建一个编辑所有问题的链接。以一种形式编辑多个实体

我想编辑一个表格中的所有问题,该如何处理?我尝试使用集合,但我不知道如何映射表单集合中的单个问题,我不确定这是否正确。

QuestionType样子:

public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $categories = $this->entityManager->getRepository('MyAppBundle:QuestionCategory')->findByIsActive(true); 

     $builder->add('category', 'entity', array(
         'class' => 'MyAppBundle:QuestionCategory', 
         'choices' => $categories, 
         'label' => 'category', 
         'translation_domain' => 'messages', 
         'multiple' => false, 
         'empty_value' => 'msg.pleaseSelect', 
         'expanded' => false)) 
       ->add('translations', 'a2lix_translations', array(
          'fields' => array(
           'text' => array(
            'field_type' => 'textarea', 
            'label' => 'hintText', 
            'attr' => array('class' => 'rte') 
           ), 
           'explanation' => array(
            'field_type' => 'textarea', 
            'label' => 'title', 
            'attr' => array('class' => '') 
           ) 
          ) 
       )); 
    } 

    public function setDefaultOptions(OptionsResolverInterface $resolver) 
    { 
     $resolver->setDefaults(array(
      'data_class' => 'My\AppBundle\Entity\Question', 
     )); 
    } 

我用行动来编辑所有问题控制器,看起来像:

$em = $this->getDoctrine()->getManager(); 
$questions = $em->getRepository('MyAppBundle:Question')->findAll(); 

/** 
    * -- Here is my problem , how can i my $questions into form? --- 
**/   
$form = $this->createFormBuilder() 
    ->add('questions', 'collection', array(
      'type' => new QuestionType() , 
      'allow_add' => false, 
      'allow_delete' => false, 
      'label' => false) 
    ) 
    ->add('save', 'submit', array('label' => 'Create')) 
    ->getForm(); 


$form->handleRequest($request); 

if ($form->isValid()) { 
} 

return $this->render('MyAppBundle:Question:editAllQuestions.html.twig', array("form" => $form->createView())); 

有没有人暗示或方法?

回答

0

你在正确的轨道上,你可能需要做的是:

$form->setData(array('questions' => $yourQuestionArray)); 

刚过->getForm()->handleRequest($request)之前。

或者你可以把它作为一个选项,以createFormBuilder()像这样:

$form = $this->createFormBuilder(array('questions' => $yourQuestionArray)) 
    ->add(...) 

他们都做同样的事情。

通常当你创建一个表单类(它看起来像你有QuestionType做什么),您提供的,它定义了形式使用它作为模型data_class配置选项(see documentation)。

你在控制器中做的是创建一种没有关联数据类的“匿名”表单(documentation,这看起来像你在控制器中做的那样)。在这种情况下,它的数据是一个数组(类似的,如果你调用$form->getData(),你会得到一个数组)。

+0

非常感谢您的支持,解决了我的问题 – smartcoderx