How to update many records?

I have list of items eg:

Item 1 - input[“price”]
Item 2 - input[“price”]
Item 3 - input[“price”]
Item 4 - input[“price”]

and button submit

How do I update the database of these records in one save?
Do I have to put some hidden ID field somewhere?

Please give me an example.

Thank you

Inputs formats:

<?= $this->Form->input('0.id', /* ... */) ?>
<?= $this->Form->input('0.field1', /* ... */) ?>
<?= $this->Form->input('1.id', /* ... */) ?>
<?= $this->Form->input('1.field1', /* ... */) ?>
<!-- ... -->

resulting in a dataset:

$data = [
    '0' => ['id' => '...', 'field1' => '...', /* ... */],
    '1' => ['id' => '...', 'field1' => '...', /* ... */],
    // ...
];

Patch entities:

$original = $this->Table->find()->toList();
$patched = $this->Table->patchEntities($original, $data);

I would need to save the current time in the date column after updating these records. The TimeStamp behavior always saves the date after the update. Is it possible for the behavior to work only if I call a specific controller? Because if I save to the model where the behavior is, my date will always be overwritten…

Please help

You can add a behavior to a table at any time. It’s normally done in the table’s initialize function, but it doesn’t have to be. Feel free to add it to the table just in this one function.

1 Like

You can also remove a behavior any time you want

1 Like

And how can this be added only in a specific function?

In controller initialization function its good?:

    $this->getTableLocator()->get('UsersDocuments')->addBehavior('Timestamp', [
        'events' => [
            'Model.beforeSave' => [
                'date' => 'existing'
            ]
        ]
    ]);

That should work, sure.

1 Like