10000 [Form] Fix `keep_as_list` when data is not an array · symfony/symfony@4433af8 · GitHub
[go: up one dir, main page]

Skip to content

Commit 4433af8

Browse files
committed
[Form] Fix keep_as_list when data is not an array
1 parent f960d64 commit 4433af8

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

src/Symfony/Component/Form/Extension/Core/EventListener/ResizeFormListener.php

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,13 @@ public function onSubmit(FormEvent $event): void
199199
}
200200

201201
if ($this->keepAsList) {
202-
$formReindex = [];
202+
$formReindex = $dataKeys = [];
203+
foreach ($data as $key => $value) {
204+
$dataKeys[] = $key;
205+
}
206+
foreach ($dataKeys as $key) {
207+
unset($data[$key]);
208+
}
203209
foreach ($form as $name => $child) {
204210
$formReindex[] = $child;
205211
$form->remove($name);
@@ -208,8 +214,8 @@ public function onSubmit(FormEvent $event): void
208214
$form->add($index, $this->type, array_replace([
209215
'property_path' => '['.$index.']',
210216
], $this->options));
217+
$data[] = $child->getData();
211218
}
212-
$data = array_values($data);
213219
}
214220

215221
$event->setData($data);

src/Symfony/Component/Form/Tests/Extension/Core/EventListener/ResizeFormListenerTest.php

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -310,7 +310,7 @@ public function testOnSubmitDealsWithObjectBackedIteratorAggregate()
310310
$this->assertArrayNotHasKey(2, $event->getData());
311311
}
312312

313-
public function testOnSubmitDealsWithArrayBackedIteratorAggregate()
313+
public function testOnSubmitDealsWithDoctrineCollection()
314314
{
315315
$this->builder->add($this->getBuilder('1'));
316316

@@ -323,6 +323,19 @@ public function testOnSubmitDealsWithArrayBackedIteratorAggregate()
323323
$this->assertArrayNotHasKey(2, $event->getData());
324324
}
325325

326+
public function testKeepAsListWorksWithTraversableArrayAccess()
327+
{
328+
$this->builder->add($this->getBuilder('1'));
329+
330+
$data = new \ArrayIterator([0 => 'first', 1 => 'second', 2 => 'third']);
331+
$event = new FormEvent($this->builder->getForm(), $data);
332+
$listener = new ResizeFormListener(TextType::class, keepAsList: true);
333+
$listener->onSubmit($event);
334+
335+
$this->assertArrayNotHasKey(1, $event->getData());
336+
$this->assertArrayNotHasKey(2, $event->getData());
337+
}
338+
326339
public function testOnSubmitDeleteEmptyNotCompoundEntriesIfAllowDelete()
327340
{
328341
$this->builder->setData(['0' => 'first', '1' => 'second']);

0 commit comments

Comments
 (0)
0