CakePHP 3 - 验证:不可更改的字段
CakePHP 3 - Validation: unchangeable field
我有几个表,其中包含永远不应更改的字段。相反,应完全删除行并在需要进行更改时重新添加行。
是否有一种巧妙的方法来添加验证或构建规则来防止任何更改?
我在 https://book.cakephp.org/3.0/en/orm/validation.html or https://api.cakephp.org/3.8/class-Cake.Validation.Validation.html
中找不到任何内容
我最终创建了一个自定义且可重复使用的规则:
<?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;
}
}
用法比看起来像:
<?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'
]);
}
}
我有几个表,其中包含永远不应更改的字段。相反,应完全删除行并在需要进行更改时重新添加行。
是否有一种巧妙的方法来添加验证或构建规则来防止任何更改?
我在 https://book.cakephp.org/3.0/en/orm/validation.html or https://api.cakephp.org/3.8/class-Cake.Validation.Validation.html
中找不到任何内容我最终创建了一个自定义且可重复使用的规则:
<?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;
}
}
用法比看起来像:
<?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'
]);
}
}