We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Dynamically adjust whitelist on beforeUpdate event

We are trying to dynamically adjust the model whitelist from within the beforeUpdate.

use case

we want to make certain columns imutable int the systme if certain realtionships exist.

if relationship exist, then we only allow certain columns to be "updateable".

we were thinking we could provide a whitelist of mutable columns if the relationship exists then we could be sure only those columns would be updated. we are currently checking the relationship in the beforeUpdate using the addBehavior method on the model.

take a look at this snapshots

the rest you can do by applying the logic you need in the behavior

edited Aug '18

Someone correct me if I'm missing soemthing, but I could not find a way to update the whitelist fields in the behaviour methods. Docs link: https://docs.phalcon.io/ja/3.3/api/Phalcon_Mvc_Model

Here is a working solution tho, may not be the prettiest, but sure does the job :)

// Controller
$data = [
    'company_id' => mt_rand(1, 1900),
    'user_id' => mt_rand(1, 1900),
    'title' => 'New title - ' . mt_rand(1, 1900),
];
$object = \Models\Reports::findFirst(2); 
$object->save($data, $object->getWhitelist());

// Model
public function getWhitelist()
{
    $isCarSold = true; // Allow update of limited fiedls
    // $isCarSold = false; // Allow updating all fields
    return $isCarSold ? ['title'] : ['title', 'company_id', 'user_id'];
}

You can modify the getWhitelist() method and add the neccessary conditions to check if car is being sold :)

UPDATE: Another option would be to use setters/getters and apply business logic which fields to be updated when, but the above solution looks shorter to me :)

overwrite save method is the best and safest method!