PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, January 5, 2022

[FIXED] CakePHP 3 - Validation: unchangeable field

 January 05, 2022     cakephp, cakephp-3.0, cakephp-3.x, validation     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing