My question is pretty straightforward: How should form data look like (e.i. what should the name keys look like) to patch multiple entities using patchEntities()?
I have read Cookbook > Database Access & ORM > Saving Data > Converting Multiple Records, but it does not explicitly mention how to use it.
This structure works for newEntities():
$data = [
'0' => ['field1' => '...', /* ... */],
'1' => ['field1' => '...', /* ... */],
'2' => ['field1' => '...', /* ... */]
];
With a form like:
<?= $this->Form->input('0.field1', /* ... */) ?>
<?= $this->Form->input('1.field1', /* ... */) ?>
...
However, the same structure but with 'id.field1' does not make any changes to entities in patchEntities().
The form data should look the same, with the exception that it should include the records primary keys, so that the marshaller can map the data on the respective records. The leading number there in your form inputs isn't a primary key (id), but just the resulting array index.
The docs could use a little update there to include patchEntities() too, right now there's only a short section hidden in the "Patching HasMany and BelongsToMany" section.
Cookbook > Database Access & ORM > Saving Data > Patching HasMany and BelongsToMany
So the form should look something like:
<?= $this->Form->input('0.id', /* ... */) ?>
<?= $this->Form->input('0.field1', /* ... */) ?>
<?= $this->Form->input('1.id', /* ... */) ?>
<?= $this->Form->input('1.field1', /* ... */) ?>
<!-- ... -->
resulting in a dataset like:
$data = [
'0' => ['id' => '...', 'field1' => '...', /* ... */],
'1' => ['id' => '...', 'field1' => '...', /* ... */],
// ...
];
which can then be patched on the given entities:
$original = $this->Table->find()->toArray();
$patched = $this->Table->patchEntities($original, $data);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With