LoginSignup
2
3

More than 5 years have passed since last update.

CakePHP3.2.9へのアップデートでエラーを返すようになったexistsInをどうにかする話

Last updated at Posted at 2016-05-20

追記:この変更は3.2.10でリバートされました


CakePHP3.2.9がリリースされたのでアップデートしたらテストが通らなくなってしましました… :cry:
どうやらexistsInが更新されたことが原因のようです。
(変更箇所:Force ExistsIn rule in new Entiy even with a not dirty field)

今まで以下のような感じの処理をしていました。

src/Controller/ArticlesController.php
public function add()
{
    $article = $this->Articles->newEntity();
    if ($this->request->is('post')) {
        $article = $this->Articles->patchEntity($article, $this->request->data);
        $article->user = $this->Users->get($this->Auth->user('id'));
        if ($this->Articles->save($article)) {
            return $this->redirect(['action' => 'index']);
        } else {
            $this->Flash->error(__('保存できません'));
        }
    }
src/Model/Table/ArticlesTable.php
public function buildRules(RulesChecker $rules)
{
    $rules->add($rules->existsIn(['user_id'], 'Users'));
    return $rules;
}

Controllerでuser_idではなくuserをentityの形で$article->userにセットしているので、$article->user_idはセットされていないため、existsIn()がエラーを返すようになったようです。
今まではuser_idがセットされてなかったらチェックしてなかったけど、新規作成の時はそれは許されなくなったぽい?

というわけで、なんか釈然としないけど、以下を追加しました。

src/Model/Table/ArticlesTable.php
public function beforeRules($event, $entity, $options, $operation)
{
    if (!empty($entity->user)) {
        $entity->user_id = $entity->user->id;
    }
}

エラーは出なくなったけど、これでいいのかどうか…。

2
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3