Issue
I have a few tables that have fields that should never be changed. Instead, rows should be deleted entirely and added again when changes need to be made.
Is there a neat way of adding validation or a build rule that will prevent any changes?
I couldn't find anything in https://book.cakephp.org/3.0/en/orm/validation.html or https://api.cakephp.org/3.8/class-Cake.Validation.Validation.html
Solution
I ended up creating a custom and reusable rule:
<?php
// in src/Model/Rule/StaticFieldsRule.php
namespace App\Model\Rule;
use Cake\Datasource\EntityInterface;
/** * Rule to specify fields that cannot be changed */ class StaticFieldsRule {
protected $_fields;
/**
* Constructor
*
* @param array $fields
* @param array $options
*/
public function __construct($fields, array $options = [])
{
if (!is_array($fields))
{
$fields = [$fields];
}
$this->_fields = $fields;
}
/**
* Call the actual rule itself
*
* @param EntityInterface $entity
* @param array $options
* @return boolean
*/
public function __invoke(EntityInterface $entity, array $options)
{
// If entity is new it's fine
if ($entity->isNew())
{
return true;
}
// Check if each field is dirty
foreach ($this->_fields as $field)
{
if ($entity->isDirty($field))
{
return false;
}
}
return true;
}
}
Usage than looks like:
<?php
// in src/Model/Table/MyTable.php
namespace App\Model\Table;
//...
use App\Model\Rule\StaticFieldsRule;
class MyTable extends Table
{
// ...
public function buildRules(RulesChecker $rules)
{
$rules->add(new StaticFieldsRule(['user_id']), 'staticFields', [
'errorField' => 'user_id',
'message' => 'User_id cannot be changed'
]);
}
}
Answered By - Roberto
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.