save() returning false, but with no error in CakePHP

China☆狼群 提交于 2019-11-28 22:27:47

This will probably give you the info you need (assuming it's not saving because of invalid data, of course):

if(!$this->save()){
    debug($this->validationErrors); die();
}

contains validationErrors array

if ($this->save()) {
    return $this->ModelName->id;
}
else {
    debug($this->ModelName->invalidFields());
    return false;
}
neilcrookes

Have you got a beforeValidate() or beforeSave() method in the model or app model? Ifso, are they returning true? Failing that, use a debugger, set a break point in your IDE at the top of cake/libs/models/model.php save() method and step through the code until it returns false. Failing that add die('here'); calls.

Thiago Belem

Try this:

if ($this->save()) {
    return $this->id;
}
else {
    var_dump($this->invalidFields());
    return false;
}
na8ur

Make sure to check your tables:

  • Does ID have auto increment enabled?
  • Is id your primary key?

the auto_increment issues killed me. Easy way to check: if any of your rows have ID = 0, auto_increment is likely disabled.

@cakePHP 3.6 : After you save an entity any validation errors will be stored on the entity itself. It can read by getErrors() method.

\Cake\Log\Log::debug($this->ModelName->getErrors());

If you have included library

use \Cake\Log\Log;

then you can access the errors as below:

Example: log::debug($contactRelationship->getErrors());

Ref: https://book.cakephp.org/3.0/en/orm/entities.html

The other situation where CakePHP fails to report any $this->Model->validationErrors and no other errors is potentially when $this->request->data isn't as Cake expects and is simply ignoring your data, not saving, no validation errors. For example if your data was provided by DataTables you might see this format $this->request->data[0]['Model']['some_field'].

$this->Model->save($this->request->data[0]) will work however.

CakePHP 3.6

$entity = $this->Model->newEntity([
    'account_id' => $id,
    'gallery_id' => $gallery_id
]);

$result = $this->Model->save($entity);

print_r($entity->getErrors());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!