微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Symfony如何添加回已在PRE_SUBMIT事件处理程序中删除的表单字段?

如何解决Symfony如何添加回已在PRE_SUBMIT事件处理程序中删除的表单字段?

我有一个表单,但没有包含单个集合的数据类。我添加一个PRE_SUBMIT事件侦听器,该事件侦听器在集合上进行迭代,并删除没有选中复选框且尚未持久保存的集合元素。

在我的测试案例中,表单是由11个元素的数据数组创建的。提交表单后,该表单应减少到集合中的4个元素,而不是11个。

以下是以下形式的代码段:

public function buildForm(FormBuilderInterface $builder,array $options)
    {
        
        $builder
            ->add('phyTypeItemTypeInstances',CollectionType::class,[
                'entry_type' => ConfigurePhysicalTypeItemTypeType::class,'entry_options' => ['label' => false],'allow_add' => true,'allow_delete' => true,'prototype' => false,'label' => false]);


        $builder->addEventListener(FormEvents::PRE_SUBMIT,function (FormEvent $event) 
        {
            $data = $event->getData();
            $form = $event->getForm();

            $collection = $form->get('phyTypeItemTypeInstances');
            
            foreach ($collection as $key => $item) {

            if ((!array_key_exists('selection',$item) 
                 || $item['selection'] !== '1') 
                 && null === $collection->get($key)->getData()->getId()) {

                $form->get('phyTypeItemTypeInstances')->remove($key);
            }

dump($form); //<------- Debug output shows a collection with 4 elements in the form as expected.
        });
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => null,'allow_extra_fields' => true
        ]);
    } 

基于调试输出,似乎在控制器中调用handleRequest之后,表单将还原为集合中包含11个元素。这是控制器摘录:

        $dataArray = $this->getConfigurationArray($joinEntity,$bid);

        $form = $this->createForm(ConfigurationJoinTableType::class,[
                    'phyTypeItemTypeInstances' => $dataArray]);

dump($form); //<-- Output shows a collection of 11 as expected

        $form->handleRequest($request);

dump($form); //<-- Outputs shows a collection of 11 even after the dump from the event listener showed a collection of 4. 

在这里缺少基本的东西吗?我还有其他表单,可以在其中添加删除字段,没有问题。但是,我认为这是我第一次从集合中删除元素。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。