首页 文章

表格事件中的Symfony 3.4 Ajax

提问于
浏览
0

在我的项目中,表单允许用户在SelectBox中选择一个Map . 当Map Selectbox更改时,GroupLayer Selectbox中的选项也会根据选择的Map进行更改 . 我在我的案例中看到了完整的Symfony文档:How to Dynamically Modify Forms Using Form Events Howerver,在示例代码中:

$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 实体吗?

1 回答

  • 0

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

    $map->getGroupLayers();
    

    这是选择器的选择 .

    另一方面,您可以使用GroupLayer存储库中的自定义方法,将map作为参数或从 Map 中搜索相关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);
        }
    );
    

    我希望这可以帮到你

相关问题