繁体   English   中英

Symfony 3.4 Ajax在Form事件中

[英]Symfony 3.4 Ajax in Form event

在我的项目中,该表单允许用户在SelectBox中选择一个Map。 更改地图选择框时,GroupLayer选择框中的选项也会更改,具体取决于选择的地图。 在以下示例代码中,我可以看到关于我的案例的Symfony文档: 如何使用表单事件动态修改表单 ,示例代码:

$formModifier = function (FormInterface $form, Sport $sport = null) {
        $positions = null === $sport ? array() : $sport->getAvailablePositions();

        $form->add('position', EntityType::class, array(
            'class' => 'App\Entity\Position',
            'placeholder' => '',
            'choices' => $positions,
        ));
    };

我不知道getAvailablePositions()函数应该在哪里,该函数的返回值是什么? 我认为此功能将放置在Sport Entity中。 是正确的,在“ Sport实体”中,我可以使用Doctrine ORM queryBuilder查询Position实体吗?

使用此formModifier,您仅更改表单具有的字段。 我不知道Map和GroupLayer之间的关系在哪里,但是这种关系是您需要搜索的。 例如,如果您在实体之间有一个OneToMany关系,则可以执行以下操作:

$map->getGroupLayers();

这是选择器的选择。

另一方面,您可以使用GroupLayer存储库中的自定义方法(将地图作为参数)或从地图中搜索相关GroupLayers的服务,这取决于您和您的体系结构。

编辑#1

使用您的新信息,我想您的代码看起来像这样:

$formModifier = function (FormInterface $form, Map $map = null) {
    $groupLayers = null === $map ? array() : $map->getGroupLayers();

    $form->add('position', EntityType::class, array(
        'class' => 'App\Entity\GroupLayer',
        'placeholder' => '',
        'choices' => $groupLayers,
    ));
};

$builder->addEventListener(
    FormEvents::PRE_SET_DATA,
    function (FormEvent $event) use ($formModifier) {
        // this would be your entity, i.e. SportMeetup
        $data = $event->getData();

        $formModifier($event->getForm(), $data->getMap());
    }
);

$builder->get('sport')->addEventListener(
    FormEvents::POST_SUBMIT,
    function (FormEvent $event) use ($formModifier) {
        // It's important here to fetch $event->getForm()->getData(), as
        // $event->getData() will get you the client data (that is, the ID)
        $map = $event->getForm()->getData();

        // since we've added the listener to the child, we'll have to pass on
        // the parent to the callback functions!
        $formModifier($event->getForm()->getParent(), $map);
    }
);

希望对您有所帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM