如何在Symfony中的表单生成器中获取字段值

时间:2017-04-05 08:02:03

标签: php forms symfony symfony-forms builder

如何在Symfony中的表单构建器中获取字段值。 我在表格中有2个下拉列表 我想在页面打开时基于Dropdown1的Dropdown2中的相关选项。

这是我的表格

use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\Event\DataEvent;
use C2Educate\ToolsBundle\Entity\Students;
public function buildForm(FormBuilder $builder, array $options) {

第1场:

$builder->add('leadSource', 'entity', array( 
        'label' => 'How did you hear about C2?   Source ',

        'class' => 'C2EducateToolsBundle:LeadSources',
        'query_builder' => function($repo)  {
            return $repo->createQueryBuilder('p')->orderBy('p.sort_order', 'ASC');
        },
        'property' => 'name',
        'empty_value' => 'Select'

    ));
$leadSource = 1;

$leadSource = 1; - 当我静态分配值时它会起作用,但我想获取“leadSource”的值并将其分配给$leadSource

我想获取leadSource并将其传递给leadSourceSub查询

第2场:

$builder->addEventListener(FormEvents::PRE_SET_DATA, function (DataEvent $event) { 
    $form = $event->getForm();
    $entity = $event->getData();
    $leadSource = $entity->getLeadSourceID();
    $form->add('leadSourceSub', 'C2Educate\ToolsBundle\Entity\Students', array(
            'label' => ' Source Detail ',
            'required' => true,
            'class' => 'C2EducateToolsBundle:LeadSourceSubs',
            'query_builder' => function($repo) use ($leadSource) {
                return $repo->createQueryBuilder('p')
                        ->where('p.lead_source_id =:leadSource')
                        ->setParameter('leadSource', $leadSource)
                        ->orderBy('p.sort_order', 'ASC');
            },
            'property' => 'name',
            'empty_value' => 'Select'
        ));
    });

1 个答案:

答案 0 :(得分:3)

您无法从$builder获取表单数据,因为...它是表单构建器,而不是表单。它还不包含任何数据。

要完成这项工作,您需要使用FormEvents。在这种情况下,您可能需要FormEvents::PRE_SET_DATA事件监听器。

    $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) { 
        $form = $event->getForm();
        // in your case it's C2EducateToolsBundle:LeadSourceSubs
        $entity = $event->getData();
        $leadSource = $entity->getLeadSource();

        // adding this field again will override it.
        $form->add('leadSourceSub', 'entity', array(
                'label' => ' Source Detail ',
                'required' => true,
                'class' => 'C2EducateToolsBundle:LeadSourceSubs',
                'query_builder' => function($repo) use ($leadSource) {
                    return $repo->createQueryBuilder('p')
                            ->where('p.lead_source_id =:leadSource')
                            ->setParameter('leadSource', $leadSource)
                            ->orderBy('p.sort_order', 'ASC');
                },
                'property' => 'name',
                'empty_value' => 'Select'
            ));
        }
    });

请注意,此代码未经过测试,可能需要进行一些验证,以确定$entity是否符合您的预期。