我有一个表单,但没有包含单个集合的数据类。我添加了一个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.
我在这里缺少基本的东西吗?我还有其他表单,可以在其中添加和删除字段,没有问题。但是,我认为这是我第一次从集合中删除元素。