CakePHP 3-验证:不可更改的字段

时间:2019-07-26 10:41:33

标签: validation cakephp cakephp-3.0 cakephp-3.x

我有一些表,其中的字段永远都不应更改。相反,应将行完全删除,并在需要进行更改时再次添加。

是否有一种简洁的方法来添加验证或构建规则以防止任何更改?

我在https://book.cakephp.org/3.0/en/orm/validation.htmlhttps://api.cakephp.org/3.8/class-Cake.Validation.Validation.html中找不到任何内容

1 个答案:

答案 0 :(得分:0)

我最终创建了一个自定义和可重复使用的规则:

<?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'
        ]);
    }
}
相关问题