1

これは2.xでの最初のアプリですが、私はCakePHPにまったく慣れていません。ベイクされたコントローラーとビューを使用していますが、編集機能に問題があります。

まず、焼いたものは次のとおりです。

public function edit($id = null) {
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
            }
        } else {
            $this->request->data = $this->User->read(null, $id);
        }
    }

これを放置すると

if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }

ユーザーが存在することを疑いなく知っている場合でも、無効なユーザーがいると言われます。

これを次のように変更すると:

 if (!$this->User->exists($id)) {
                    throw new NotFoundException(__('Invalid user'));
                }

正しい編集フォームが表示され、正しいデータが取り込まれますが、保存時に更新ではなく挿入が試行されます。

これは通常、CakePHP には操作する ID がないためですが、フォームに非表示の ID フィールドがあり、保存の前に次のコードを記述して問題を強制しようとしました。

$this->request->data['User']['id'] = $id;

ここで何が起こっているのですか?

4

2 に答える 2

0

ベークによって生成されたコード、非表示のIDなど、同じ問題が発生しました。その後、データベースのフィールドIDが自動インクリメントに設定されていないことがわかりました。

自動インクリメントに設定しただけで動作します

于 2014-10-01T20:08:49.263 に答える
0
public function edit($id = null) {
        if (!$this->User->exists($id)) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            $user_data = $this->User->findById($id);
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved'), 'flash');
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The user could not be saved. Please, try again.'), 'flash');
            }
        } else {
            $options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
            $this->request->data = $this->User->find('first', $options);
        }
       }
于 2014-08-14T14:06:14.950 に答える