【问题标题】:How to populate a select field based on a previous selected value in Doctrine?如何根据 Doctrine 中先前选择的值填充选择字段?
【发布时间】:2017-03-15 09:44:05
【问题描述】:

我正在开发一个为表单实现 Doctrine ORM 的 Symfony2 CRM。 CRM 上的一种表格用于创建客户地址,具有所有标准文本字段,例如街道、城市、邮政编码等,还有国家和县的下拉列表。问题是,如果我从数据库中检索所有县,则列表很大,不仅需要很长时间才能加载,而且我的客户很难找到县,因为它适用于世界上的每个国家。

我希望他们先选择国家,然后根据所选国家自动填充县域。但是,我不确定如何在 Doctrine 中执行此操作。

这是我在表单类型中的buildForm 函数(注意这里,Zone 表示县):

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('company' , 'text', array('required' => false ));
    $builder->add('firstname' , 'text', array('required' => true, 'label' => 'First name' ));
    $builder->add('lastname' , 'text', array('required' => true, 'label' => 'Last name' ));
    $builder->add('address1' , 'text');
    $builder->add('address2' , 'text', array('required' => false ));
    $builder->add('city' , 'text');
    $builder->add('country' , 'entity',
        array(
            'class' => 'AppBundle:Oc49Country',
            'property' => 'name',
            'empty_value' => 'Choose an option',
        ));
    $builder->add('zone' , 'entity',
        array(
            'class' => 'AppBundle:Oc49Zone',
            'query_builder' => function (EntityRepository $er) {
                return $er->createQueryBuilder('z')
                    ->orderBy('z.name', 'ASC');
            },
            'empty_value' => '-- Please select --',
            'required' => true,
            'label' => 'County/State'
        ));
    $builder->add('postcode' , 'text');
    $builder->add('save', 'submit', array(
        'attr' => array(
            'class' => 'btn btn-primary'
        ),
    ));
}

有没有一种方法可以在查询构建器中添加一个额外的参数,以便即时过滤县列表?

【问题讨论】:

    标签: symfony doctrine


    【解决方案1】:

    因为你想在页面已经被 symfony 渲染之后改变县选择列表,你必须以某种方式使用 ajax 来更新那个县选择列表。

    我会使用 jquery/ajax 调用来根据所选国家/地区填充县选择列表。从您的 twig 模板中,按照以下几行添加一些 jquery 函数:

    $('#country_select).on('change', function() {
        url: '/path/to/controller/to/get/countyList',
        method: 'GET'
    }).done(function() {
        // update options
    });
    

    This question 将提供详细信息。显然我的代码很粗糙,但希望这会有所帮助。

    【讨论】:

    • 我知道如何做到这一点,我之前已经实现过这种事情 - 但我正在尝试使用 Doctrine 方法找到一种方法。我想知道是否有某种方法可以添加侦听器来检查所选国家/地区,但我真的不知道该怎么做...
    • 实际上,想想看,我想我会实现这个但禁用选择框,直到它被重新填充。谢谢
    • 我看到的最接近的东西是:symfony.com/doc/current/form/dynamic_form_modification.html。请参阅选项 3。我不认为这正是您想要的。我自己没有尝试过,所以也许我错了。
    • 在这一天,这篇文章应该很有用:stackoverflow.com/questions/71264515/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-04
    相关资源
    最近更新 更多