【问题标题】:CakePHP 3 - Validation: unchangeable fieldCakePHP 3 - 验证:不可更改的字段
【发布时间】:2019-12-04 16:47:03
【问题描述】:

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

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

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

【问题讨论】:

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


【解决方案1】:

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

<?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'
        ]);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-24
    • 1970-01-01
    • 2017-12-07
    • 2011-06-27
    • 1970-01-01
    • 2021-11-17
    • 2016-09-07
    • 1970-01-01
    相关资源
    最近更新 更多