21

我有三个实体:国家、州和城市,具有以下关系:

图片

创建城市时,我需要两个选择器,一个用于国家,一个用于城市所属的州。这两个选择器需要链接,因此更改国家将“过滤”另一个选择器中显示的状态。

我找到了一个教程,展示了如何使用表单事件来做到这一点,但他们的例子并不是我的情况。我的实体 City 它与 Country 实体没有直接关系(它们通过 State 间接相关)所以,当在 City 表单中设置 country 字段时(在 CityType 类中),我被迫声明该字段,'property_path'=>false如您所见在下面的代码中:

class CityType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('country', 'entity', array(
            'class'=>'TestBundle:Country', 
            'property'=>'name', 
            'property_path'=>false //Country is not directly related to City
        ));
        $builder->add('name');

        $factory = $builder->getFormFactory();

        $refreshStates = function ($form, $country) use ($factory) 
        {
            $form->add($factory->createNamed('entity', 'state', null, array(
                'class'         => 'Test\TestBundle\Entity\State',
                'property'      => 'name',
                'query_builder' => function (EntityRepository $repository) use ($country)
                                   {
                                       $qb = $repository->createQueryBuilder('state')
                                                        ->innerJoin('state.country', 'country');

                                        if($country instanceof Country) {
                                            $qb->where('state.country = :country')
                                               ->setParameter('country', $country);
                                        } elseif(is_numeric($country)) {
                                            $qb->where('country.id = :country')
                                               ->setParameter('country', $country);
                                        } else {
                                            $qb->where('country.name = :country')
                                               ->setParameter('country', "Venezuela");;
                                        }        
                                        return $qb;
                                    }
            )));
        };

        $builder->addEventListener(FormEvents::PRE_SET_DATA, function (DataEvent $event) use ($refreshStates)
        {
            $form = $event->getForm();
            $data = $event->getData();

            if($data == null)
                return;               

            if($data instanceof City){
                if($data->getId()) { //An existing City
                    $refreshStates($form, $data->getState()->getCountry());
                }else{               //A new City
                    $refreshStates($form, null);
                }
            }
        });

        $builder->addEventListener(FormEvents::PRE_BIND, function (DataEvent $event) use ($refreshStates)
        {
            $form = $event->getForm();
            $data = $event->getData();

            if(array_key_exists('country', $data)) {
                $refreshStates($form, $data['country']);
            }
        });
    }

    public function getName()
    {
        return 'city';
    }

    public function getDefaultOptions(array $options)
    {
        return array('data_class' => 'Test\TestBundle\Entity\City');
    }
}

问题是当我尝试编辑现有城市时,默认情况下不会在表单中选择相关的国家。如果我删除该行'property_path'=>false,我会(毫不奇怪)收到错误消息:

“Test\TestBundle\Entity\City”类中不存在属性“country”、方法“getCountry()”和方法“isCountry()”

有任何想法吗?

4

3 回答 3

25

好的,我终于想出了如何正确地做到这一点:

namespace Test\TestBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\Event\DataEvent;

use Test\TestBundle\Entity\Country;
use Test\TestBundle\Entity\State;
use Test\TestBundle\Entity\City;


class CityType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('name');

        $factory = $builder->getFormFactory();

        $refreshStates = function ($form, $country) use ($factory) {
            $form->add($factory->createNamed('entity','state', null, array(
                'class'         => 'Test\TestBundle\Entity\State',
                'property'      => 'name',
                'empty_value'   => '-- Select a state --',
                'query_builder' => function (EntityRepository $repository) use ($country) {
                    $qb = $repository->createQueryBuilder('state')
                        ->innerJoin('state.country', 'country');

                    if ($country instanceof Country) {
                        $qb->where('state.country = :country')
                            ->setParameter('country', $country);
                    } elseif (is_numeric($country)) {
                        $qb->where('country.id = :country')
                            ->setParameter('country', $country);
                    } else {
                        $qb->where('country.name = :country')
                            ->setParameter('country', null);
                    }

                    return $qb;
               })
           ));
        };

        $setCountry = function ($form, $country) use ($factory) {
            $form->add($factory->createNamed('entity', 'country', null, array(
                'class'         => 'TestBundle:Country', 
                'property'      => 'name', 
                'property_path' => false,
                'empty_value'   => '-- Select a country --',
                'data'          => $country,
            )));
        };

        $builder->addEventListener(FormEvents::PRE_SET_DATA, function (DataEvent $event) use ($refreshStates, $setCountry) {
            $form = $event->getForm();
            $data = $event->getData();

            if ($data == null) {
                return;
            }

            if ($data instanceof City) {
                $country = ($data->getId()) ? $data->getState()->getCountry() : null ;
                $refreshStates($form, $country);
                $setCountry($form, $country);
            }
        });

        $builder->addEventListener(FormEvents::PRE_BIND, function (DataEvent $event) use ($refreshStates) {
            $form = $event->getForm();
            $data = $event->getData();

            if(array_key_exists('country', $data)) {
                $refreshStates($form, $data['country']);
            }
        });
    }

    public function getName()
    {
        return 'city';
    }

    public function getDefaultOptions(array $options)
    {
        return array('data_class' => 'Test\TestBundle\Entity\City');
    }
}

jQuery AJAX 选择器

$(document).ready(function () {
    $('#city_country').change(function(){
        $('#city_state option:gt(0)').remove();
        if($(this).val()){
            $.ajax({
                type: "GET",
                data: "country_id=" + $(this).val(),
                url: Routing.generate('state_list'),
                success: function(data){
                    $('#city_state').append(data);
                }
            });
        }
    });
});

我希望这对面临同样情况的其他人有所帮助。

于 2012-06-15T23:56:35.447 回答
7

由于您与此方法的链接已关闭,因此我决定补充您的出色答案,以便任何人都可以使用它:

为了执行以下 javascript 命令:

url: Routing.generate('state_list'),

您需要安装 FOSJsRoutingBundle,可以在此处找到。

注意:在捆绑包的自述部分中有安装说明,但缺少一些东西。如果您将 deps 与此一起使用:

[FOSJsRoutingBundle]
git=git://github.com/FriendsOfSymfony/FOSJsRoutingBundle.git
target=/bundles/FOS/JsRoutingBundle

您必须php bin/vendors update在接下来的步骤之前运行。

我仍在尝试找出在 routing.yml 中需要什么路由才能使该解决方案起作用。一旦我发现我会编辑这个答案。

于 2012-08-21T10:06:38.003 回答
0

链式选择框需要一个专用的 FieldType。还有一个 xhr 控制器,可以根据传递的参数返回子选项。当然,property_path 应该设置为 false。

于 2012-04-18T03:24:31.220 回答