在CakePHP中更新记录

时间:2013-03-19 21:10:57

标签: forms cakephp sql-update cakephp-appmodel

所以我正在学习CakePHP,我正在尝试构建一堆基本的应用程序,我可以在PHP中构建,以了解CakePHP的工作原理。现在我正在开发一个基本的订单管理系统 - 用户可以拥有多个订单和订单属于用户。

我已经设置了数据库并正确配置了CakePHP(起始页面显示了每个主题的所有绿色,例如默认时区和数据库连接,但我没有安装的DebugKit除外)。我还有一个“用户列表”页面:

enter image description here

我正在尝试在/ users / edit_user上编辑现有用户时遇到的问题,正如您在上面的屏幕截图中看到的那样:

enter image description here

我正在尝试保存用户的编辑,我(1)使用$this->Form->hidden(...)作为ID,(2)将主键设置为模型中表的主键{{1} }

每次我尝试这样做时,它只是插入一个 new 记录而不是更新现有记录,我认为通过识别我的PK并添加ID来修复问题提交,但我必须遗漏一些东西。

以下是相关网页的代码:

模型

public $primaryKey = 'ID';

控制器

<?php
/**
 * app/Model/User.php
 *
 */
class User extends AppModel
{
    public $name = 'User';
    public $primaryKey = 'ID';

    // <hasMany>
    public $hasMany = array(
                            'Order' => array('dependent' => true)
                        );
}

?>

查看/用户/ edit_user.ctp

<?php
/**
 * app/Controller/UsersController.php
 *
 */
class UsersController extends AppController
{
    //public $scaffold;

    /* Validation */
    public $validate = array(
            'username' => array(
                    'required' => true,
                    'allowEmpty' => false,
                    'loginRule1' => array(
                        'rule' => 'alphaNumeric',
                        'message' => "Usernames must be alphanumeric!"
                                        ),
                    'loginRule2' => array(
                        'rule' => array('minLength', 4),
                        'message' => 'Usernames must be at least 4 characters.'
                                        ),
                                ),
            'password' => array(
                    'required' => true,
                    'allowEmpty' => false,
                    'passwordRule1' => array(
                        'rule' => array('minLength', 4),
                        'message' => 'Passwords must be between 4 and 8 characters.'
                                            ),
                    'passwordRule2' => array(
                        'rule' => array('maxLength', 8),
                        'message' => 'Passwords must be between 4 and 8 characters.'
                                            )
                                )
            );


    /* Actions */

    public function index()
    {
        // Grab all users
        $users = $this->User->find('all');

        // Set/Send users to View
        $this->set('users', $users);
    }

    public function new_user()
    {
        /* Has any Form data been POST'd? */
        if ($this->request->is('post'))
        {
            // Save User data to the DB
            $this->User->save($this->request->data);

            $this->redirect('/users');
        }
    }

    /*
        Accessing Args:
            (1) Direct URL Routing Method
                --> ...
            (2) Named Params Method
                --> CakeRequest['named']['[name]']
    */
    public function edit_user($id = null)
    {
        $id = $this->request['named']['currentID'];

        // Display the current data of the user
        if (!empty($id))
        {
            $userInfo = $this->User->find('all', 
                    array('conditions' => array('User.ID' => $id)));

            $this->set('userData', $userInfo);
        }
        else
            $this->set('error', '$id is empty!');

        /* Has any Form data been POST'd? */
        if ($this->request->is('post'))
        {
            // Save User data to the DB
            $this->User->save($this->request->data);

            $this->redirect('/users');
        }
    }
}

?>

有没有人看到我没做的事情会让我编辑 /更新现有记录而不是INSERT一个全新的记录? 谢谢你的时间!

2 个答案:

答案 0 :(得分:4)

问题可能与此处使用的Form元素的类型有关;我建议你在/View/Users/edit_user.ctp文件中尝试这样的事情:

// Hidden ID field to make save an UPDATE
echo $this->Form->input('id', array('type' => 'hidden'));

有关保存修改的详细信息,请参阅CakePHP blog tutorial

答案 1 :(得分:4)

你不需要回显表单中的值,CakePHP比那更聪明。这样做:

<?php
class UsersController {

    public function edit($id) {
        if ($this->request->is('post')) {
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash('User successfully saved.');
                $this->redirect(array('action' => 'index'));
            }
        }
        else {
            $this->request->data = $this->User->findById($id);
        }
    }
}

然后在视图中创建一个表单:

<?php
    echo $this->Form->create('User');
    echo $this->Form->input('User.name');
    // and any other fields
    echo $this->Form->input('User.id', array('type' => 'hidden'));
    echo $this->Form->end('Save user');
?>

CakePHP将根据$this->request->data中的内容自动填充表单字段。

CakePHP食谱上的Blog Tutorial是掌握框架及其概念的良好起点。