簡體   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