5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

CakePHPで、save()はtrueなのに保存できない問題について

Posted at

はじめに

 今回、CakePHP4で色々やっている中で、save()メソッドでtrueが返ってくるのに何故か実際にデータは
保存できていないという事象に至りました。

 あくまで私の環境下での原因ですが、備忘録として記録いたします。
 なお、コードはサンプルなので例外処理等不要な記述は省いています。

前提(今回のコード)

 form内に複数ボタンを設置しなければいけない事象があったため、にvalueを持たせ、条件分岐をしていました。
サンプルとして、以下の感じになります。

index.php

<?= $this->Form->create($entity, ['url' => ['controller' => 'Sample', 'action' => 'index']]) ?>
    // フォームの内容

    <?= $this->Form->button('',['type' => 'submit', 'name' => 'buttonType', 'value' => 'create']) ?>
    <?= $this->Form->button('',['type' => 'submit', 'name' => 'buttonType', 'value' => 'delete']) ?>
<?= $this->Form->end() ?>
SampleController.php
public function index()
{
    /** 初期表示メソッド **/

    if($this->request->is(['post', 'put'])){
        $request = $this->request->getData();
        $buttonType = $request['buttonType'];
         // buttonの名称によってメソッドの切り替え
         switch($buttonType){
             case 'create':
                 return $this->create($request);
             case 'delete':
                 return $this->delete($request);
             default:
                 return $this->redirect([
                     'controller' => 'Error',
                     'action' => 'index'
                 ]);
         }
    }
}

public function create($request)
{
    $entity = $this->Model->newEntity($request);
    
    if($entity->hasData()){
        return $this->redirect($this->referer);
    }

    if($this->Model->save($entity)){
        dd('保存成功');
    }else{
        dd('保存失敗');
    }
}

public function delete($request)
{
    // 削除
    $this->Model->delete($request['id']);
}

事象

冒頭やタイトルでも記述しましたが、何故か「保存成功」と出るのに、DBを見てもデータはない・・・
という状態でした。

解決法

今回の事象については、以下の対処で解消することができました。
Before

index.php
return $this->create($request);

After

index.php
$this->create($request);
break; // switch文の中のため

はい、たったこの1行でした。
保存するメソッドをreturnで呼び出ししていたのがダメだった理由でした。
本質的な原因が突き止められていないので、「なんか動いた」という恐怖な状態です・・・。

原因がわかる方がいらっしゃればご教授願います。
後日私自身で原因が突き止められたら記事に追記させていただきます。

5
2
0

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
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?