symfony3 - 显示'此值无效',用于通过ajax添加选项的选项类型的下拉列表

时间:2016-11-03 11:47:22

标签: symfony

我的情景是, 我需要创建一个具有显示顺序的实体(模块),该模块位于主题实体下,并且关联正确。在表单加载时,主题下拉列表和显示顺序下拉列表将沿模块名称显示为空白。选择主题时,显示顺序将通过ajax / js填充选项。显示顺序为1到一个数字,该数字将是特定主题+ 1下的总模块。将自动选择即将出现的显示顺序。而且这很完美。但我的问题是关于提交后的显示顺序验证。它说'这个价值无效'。我知道这是因为没有在表单类型中给出“选择”作为数组,但是这种情况我不能在表单类型中给出静态。请帮助任何人都知道解决方案。 enter image description here

class ModuleType extends AbstractType {

/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder
            ->add('topic', EntityType::class, [
                'class'         => 'AppBundle:Topic',
                'choice_label'  => 'name',
                'placeholder' => 'Choose a Topic'
            ])
            ->add('name')
            ->add('description', TextareaType::class)
            ->add('displayOrder', ChoiceType::class)
            ->add('save', SubmitType::class, [
                'attr'     => ['class' => 'form-control button btn-sm nomargin']
            ])
    ;

}

/**
 * @param OptionsResolver $resolver
 */
public function configureOptions(OptionsResolver $resolver) {
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\Module'
    ));
}

}

1 个答案:

答案 0 :(得分:-1)

尝试使用事件侦听器。

以你的情况为例:

// TopicType.php
private function addEventListener(FormBuilderInterface $builder)
 {
      // this function permit to valid values of topics
    $annonymFunction = function(FormInterface $form, $diplayOrder) {
        $entities = $this->container->get('doctrine.orm.default_entity_manager')
                    ->getRepository('YourBundle:Topic')
                    ->findAll();
        if ($entities) {
            $topics = array();

            foreach($topics as $topic) {
                $topics[$topic->getName()] = $topic->getName();
            }    
        } 
        else $topics = null;

        $form->add('topic', EntityType::class, array(
            'attr' => array('class'   => 'topic'),
            'choices' => $topics));
    };

    $builder
        ->get('displayOrder')
        ->addEventListener(FormEvents::POST_SUBMIT, function(FormEvent $event) use ($annonymFunction) {
                $annonymFunction($event->getForm()->getParent(), $event->getForm()->getData());
        });
}

希望能提供帮助。