如何根据从Symfony2中的另一个列表中选择的值从一个选择列表中获取值?

时间:2015-04-23 21:51:09

标签: php jquery symfony twig

当我从会员列表中选择一个会员时,我需要从另一个选择部门列表中获取他的默认部门“添加新会员”'形式,并在必要时更改该成员的部门隶属关系。

我有两个实体,会员和部门部门也是会员实体的财产。两个下拉列表都从数据库中填充。

在FormType.php文件中,我有:

class CommMemberType extends AbstractType

    /**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('member','entity', array(
                'label' => 'Member Name',
                'empty_value' => ' ',
                'class' => 'CommitteesBundle:Member',
                'query_builder' => function(EntityRepository $er) {
                    return $er->createQueryBuilder('m')
                        ->orderBy('m.fname', 'ASC');
                },
            )
        )

        ->add('dept', 'entity', array(
            'label' => 'Department',
            'empty_value' => '---Select Department---',
            'required' => true,
            'class' => 'CommitteesBundle:Lookup\Dept',
            'property' => 'meaning',
            'query_builder' => function(EntityRepository $er) {
                return $er->createQueryBuilder('dept')
                    ->orderBy('dept.meaning', 'ASC');
            },
        ));

不幸的是,我无法找到使用jQuery解决此问题的任何解决方案。非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

不幸的是,它需要一些样板。

首先,您需要向表单FormEvents::PRE_SET_DATAFormEvents::PRE_SUBMIT添加两个事件,以便在提交表单或设置实体时使用相关选项填充相关下拉列表。

在下面的示例中,出发日期取决于所选择的行程。

class ExampleType extends AbstractType
{
   public function buildForm(FormBuilderInterface $builder, array $options)
   {
        $builder->add('tripsFk', 'entity', array(
            'class'         => 'ExampleBundle:Trips',
            'query_builder' => function(EntityRepository $er) {
                    return $er->createQueryBuilder('t')
                        ->orderBy('t.id', 'DESC');
            },
            'label'       => 'Trip',
            'attr' => array(
                'class' => 'booking_trip'
            )
        ));

        $builder->addEventListener(FormEvents::PRE_SET_DATA, array($this, 'onPreSetData'));
        $builder->addEventListener(FormEvents::PRE_SUBMIT, array($this, 'onPreSubmit'));

    }

    function onPreSubmit(FormEvent $event)
    {
        $form = $event->getForm();
        $data = $event->getData();

        $trip = $data['tripsFk'];
        $this->populateChoices($form, $trip);
    }

    function onPreSetData(FormEvent $event)
    {
        $entity = $event->getData();
        $form = $event->getForm();


        $tripId = $entity->getTripsFk() ? $entity->getTripsFk() : null;

        $this->populateChoices($form, $tripId);
    }

    public function populateChoices($form, $tripId)
    {
        $form->add('departIdFk', 'entity', array(
            'label'         => 'Departure Code',
            'class'         => 'ExampleBundle:Departures',
            'query_builder' => function(EntityRepository $er) use ($tripId) {
                    return $er->createQueryBuilder('t')
                        ->andWhere('t.trip_id', ':trip_id')
                        ->setParameter('trip_id', $tripId);
            },
            'attr' => array(
                'class' => 'booking_date'
            )
        ));
    }
}

接下来你要做的就是编写一个javascript,它会改变.booking_date淹没旅程中的选项。在.booking_trip更改事件下方的js代码段中,我们删除了现有的离职选项,并加载了新的选项:

var bookingTripChange = (function () {
        var $trip = $('.booking_trip');
        var $dates = $('.booking_date');


        init = function () {
            $trip.on('change', function () {

                $dates.attr('disabled', 'disabled');

                $.ajax({
                    url: Routing.generate('load_departures', {tripId: $trip.val()}),
                    type: 'GET',
                    dataType: 'json',
                    success: function (response) {
                        $dates.find('option').remove();

                        $("<option/>", {value: '', text: 'Specify Departure Code'}).appendTo($dates);

                        $.each(response.tripdates, function (index, entity) {
                            $("<option/>", {value: entity.id, text: entity.label}).appendTo($dates);
                        });

                        $dates.removeAttr('disabled');

                    }
                });
            });
        };
        return {
            init: init
        };
    })();

bookingTripChange.init();

最后一件事是为load_departures路线写一个动作。它可以是一个简单的选择,给定$tripId并且水合到array

public function loadChoicesAction(Request $request, $tripId)
{
        $tripdates = $this->getDoctrine()
            ->getRepository('ExampleBundle:Departures')
            ->getTripsDatesOptions($tripId);



        $content = json_encode(array(
            'tripdates' => $tripdates
        ));

        $reponse = new Response($content, 200);

        return $reponse;
}

P.S。

  1. 使js路由工作需要安装:FOSJsRoutingBundle