HTML   发布时间:2022-04-14  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Symfony2表单事件 – 下拉列表大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
在Symfony2网站上,我试图制作一个包含2(或3)个下拉列表的表单,其中包含依赖状态,如Country>区域>市.那个城市是我正在用表格编辑的元素的一个领域.我们的想法是根据选择填写列表.

我在这里按照教程和表格事件:http://aulatic.16mb.com/wordpress/2011/08/symfony2-dynamic-forms-an-event-driven-approach/
(基于webb-on-the-web .com /?p = 5)

我遇到的问题:一切正常但是当我使用表单编辑元素时,城市被正确选择(来自数据库),但国家和地区下拉列表被预先填写并留在“选择一个值”.我不知道它是否应该与教程一起工作.

问题是:如何选择这些列表?我正在尝试添加pOST_SET_DATA事件,但我找不到在表单字段中选择值的方法.

这是表单类:http://pastebin.com/PpWkHxC3(请注意,而不是城市:字段>主题和主题是表单编辑的课程的字段).

解决方法

我几乎拥有它.如果其他任何人需要这里需要添加的内容,以便在编辑现有项目时使此解决方案完美运行:
class ItemDetailForm extends AbstractType
{
   ...
        $builder->addEventListener(FormEvents::POST_SET_DATA,function (DataEvent $event) use ($refreshTopiC) {
            $data = $event->getData();
            $form = $event->getForm();
            if (null === $data) {
                return;
            }

            $form->get('region')->setData($data->getCity()->getRegion());
        });
}

编辑:自symfony 2.1以来,在将子项添加到表单之前调用POST_SET_DATA事件,导致所有get(‘region’)引发异常.
解决方案是在POST_SET_DATA中而不是在buildForm()中创建此字段:

/** @var FormFactory $factory */
        $form->add($factory->createnamed('region','entity',null,array(
            'class'=>'AcmeBundle:region','property_path'=>false,'empty_value'=>'Choose a value','required'=>true,'label'=>'Region'
        )));

请注意,您需要将$factory添加到处理事件的闭包的’use’:

$builder->addEventListener(FormEvents::POST_SET_DATA,function (DataEvent $event) use ($refreshTopic,$factory) {

这是整个表单类:

<?php
namespace AAA\CoreBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormFactory;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\Form;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\ORM\EntityRepository;
use AAA\CoreBundle\Entity\ClassYear;
use AAA\CoreBundle\Entity\Field;
use AAA\CoreBundle\Entity\Lesson;
use AAA\CoreBundle\Form\LessonContentForm;

class LessonDetailForm extends AbstractType
{
    public $country;
    function __construct($country=null) {
        // Get country for classyear dropdown list
        $this->country = $country;
    }
    public function buildForm(FormBuilderInterface $builder,array $options)
    {
        $factory = $builder->getFormFactory();

        $builder->add('name',array('label'=>'Titre de la leçon'));
        $builder->add('description','textarea',array('label'=>'Description (définition conceptuellE) Qu\'est-ce que c\'est ? Et à quoi ça sert ? (importance,utilité)'));
        $builder->add('text',array('label'=>'Leçon','required'=>falsE)); // Can't set 'required' on textareas used by TinymCE
        $builder->add('reperes',array('label'=>'Repères (détectionel) - Quels sont les éléments qui me permettent de repérer que je dois penser à ce concept ?','required'=>falsE));
        $builder->add('other_topic',array(
            'required'  =>  false,'mapped'     =>  false
        ));

        $refreshField = function ($form,$classyear) use ($factory) {
            /** @var FormFactory $factory */
            /** @var Form $form */
            $form->add($factory->createnamed('field',array(
                'class'         => 'AAA\CoreBundle\Entity\Field','mapped'        => false,'label'         => 'Matière','empty_value'   => 'Sélectionne une valeur','empty_data'    => null,'required'      => false,'query_builder' => function (EntityRepository $repository) use ($classyear) {
                    $qb = $repository->createQueryBuilder('field')
                        ->innerJoin('field.classyear','classyear');

                    if($classyear instanceof ClassYear) {
                        $qb = $qb->where('field.classyear = :classyear')
                            ->setParameter('classyear',$classyear);
                    } elseif(is_numeric($classyear)) {
                        $qb = $qb->where('classyear.id = :classyear_id')
                            ->setParameter('classyear_id',$classyear);
                    } else {
                        $qb = $qb->where('0 = 1');
                    }

                    return $qb;
                }
            )));
        };
        $refreshTopic = function ($form,$field) use ($factory) {
            /** @var FormFactory $factory */
            /** @var Form $form */
            $form->add($factory->createnamed('topic',array(
                'class'         => 'AAA\CoreBundle\Entity\Topic','property'      => 'name','label'         => 'Sujet','query_builder' => function (EntityRepository $repository) use ($field) {
                    $qb = $repository->createQueryBuilder('topic')
                        ->innerJoin('topic.field','field');

                    if($field instanceof Field) {
                        $qb = $qb->where('topic.field = :field')
                            ->setParameter('field',$field);
                    } elseif(is_numeric($field)) {
                        $qb = $qb->where('field.id = :field_id')
                            ->setParameter('field_id',$field);
                    } else {
                        $qb = $qb->where('0 = 1');
                    }

                    return $qb;
                }
            )));
        };

        // Populate ddl to show form
        $country = $this->country;
        $builder->addEventListener(FormEvents::PRE_SET_DATA,function (FormEvent $event) use ($refreshTopic,$refreshField,$factory,$country) {
            /** @var Lesson $data */
            $data = $event->getData();
            $form = $event->getForm();

            // Test if null because this event is called 2 times,only the second time with the actual Lesson object (which has null values in the creation casE)
            if($data != null)
                // In case of creation
                if($data->getId()==null) {
                    // Creates empty fields
                    $refreshTopic($form,null);
                    $refreshField($form,null);
                }
                // In case of edition
                else {
                    if ($data->getTopic() != null) {
                        $refreshTopic($form,$data->getTopic()->getField());
                        if ($data->getTopic()->getField() != null) {
                            $refreshField($form,$data->getTopic()->getField()->getClassYear());
                        }
                    }
                    else {
                        $refreshField($form,null);
                        $refreshTopic($form,null);
                    }
                }

            /** @var FormFactory $factory */
            $form->add($factory->createnamed('classyear',array(
                'class'         => 'AAACoreBundle:ClassYear','property'      => 'name'.$country,'label'         => 'Année','query_builder' => function (EntityRepository $repository) {
                    return $repository->createQueryBuilder('classyear')
                        ->orderBy('classyear.sort');
                }
            )));
        });
        // Populate ddl when form was posted
        $builder->addEventListener(FormEvents::PRE_BIND,$refreshField) {
            $form = $event->getForm();
            $data = $event->getData();

            if(array_key_exists('classyear',$data)) {
                $refreshField($form,$data['classyear']);
            }
            if(array_key_exists('field',$data)) {
                $refreshTopic($form,$data['field']);
            }
        });

        // SELEct value in ddl when ediTing
        $builder->addEventListener(FormEvents::POST_SET_DATA,function (FormEvent $event) use ($refreshTopiC) {
            /** @var Lesson $data */
            $data = $event->getData();
            $form = $event->getForm();
            if (null === $data || null === $data->getId() ) {
                return;
            }

            if ($data->getTopic() != null) {
                $form->get('field')->setData($data->getTopic()->getField());
                if ($data->getTopic()->getField() != null) {
                    $form->get('classyear')->setData($data->getTopic()->getField()->getClassYear());
                }
            }
        });
    }
    public function getName()
    {
        return 'LessonDetailForm';
    }
    /** @param OptionsResolverInterface $resolver */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AAA\CoreBundle\Entity\Lesson'
        ));
    }
}

?>

大佬总结

以上是大佬教程为你收集整理的Symfony2表单事件 – 下拉列表全部内容,希望文章能够帮你解决Symfony2表单事件 – 下拉列表所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。