Welcome Guest, Not a member yet? Register   Sign In
A check if model has anything to update
#1

After one of CodeIgniter updates I started getting CodeIgniter\Database\Exceptions\DataException ("There is no data to update."). That is caused by the commit b5b6ddfa3fb8 ("Add additional empty checks after field protection.").

My problem is that \CodeIgniter\Entity::hasChanged() doesn't take into account model's $allowedFields. It means that if:
  • $allowedFields doesn't include one of fields used in Entity
  • [or] Entity has some extra properties set

then hasChanged() will return true BUT BaseModel will throw "There is no data to update."

Could we have some way of checking if BaseModel:Confusedave() / BaseModel::update() is safe to call (won't throw an exception)?

Example:
Code:
<?php
namespace App\Entities;

class Foo extends \CodeIgniter\Entity
{
    protected $casts = [
        'id' => 'integer',
        'name' => 'string',
    ];
}
Code:
<?php
namespace App\Models;

class FooModel extends \CodeIgniter\Model
{
    protected $table = 'foo';
    protected $primaryKey = 'id';
    protected $returnType = '\App\Entities\Foo';
    protected $allowedFields = [ 'name' ];
}
Code:
$fooModel = new \App\Models\FooModel();

$foo = $fooModel->find(1);

var_dump($foo->toArray());

/* Emulate POST data */
$post = [
    'name' => 'John',  /* <input type="text" name="name" /> */
    'agree' => '1',    /* <input type="checkbox" name="agree" value="1" required /> */
    'submit' => 'Save', /* <input type="submit" name="submit" value="Save" /> */
];
$foo->fill($post);

var_dump($foo->toArray());

if (!$foo->hasChanged()) {
    die('Nothing to change');
}

if (!$fooModel->save($foo)) {
    die('Failed to save');
}

die('Success');

Current result:
Code:
array(2) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(4) "John"
}
array(4) {
  ["id"]=>
  int(1)
  ["name"]=>
  string(4) "John"
  ["agree"]=>
  string(1) "1"
  ["submit"]=>
  string(4) "Save"
}
Code:
CodeIgniter\Database\Exceptions\DataException
There is no data to update.
Reply


Messages In This Thread
A check if model has anything to update - by rmilecki - 04-17-2022, 02:20 PM



Theme © iAndrew 2016 - Forum software by © MyBB