【问题标题】:Update a Record in CakePHP在 CakePHP 中更新记录
【发布时间】:2013-03-19 21:10:57
【问题描述】:

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

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

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

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

每次我尝试这样做时,它只是插入一个 new 记录而不是更新现有记录,我认为通过识别我的 PK 并添加 ID 来解决问题已提交,但我一定遗漏了什么。

以下是相关页面的代码:

型号

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

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

?>

控制器

<?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');
        }
    }
}

?>

查看/用户/edit_user.ctp

<div class="row-fluid">

    <div class-"span12"></div>
    <div class="span12"></div>

    <div class="span8 offset2">

        <?php
            echo "Hidden ID Field Value: " . $userData[0]['User']['ID'];
            echo "<hr>";



            echo $this->Form->create('User');
            echo $this->Form->input('username');
                echo "  Current Name: " . 
                    $userData[0]['User']['username'];
            echo $this->Form->input('password');
                echo "  Current password: " . 
                    $userData[0]['User']['password'];

            // Hidden ID field to make save ~ an UDATE
            echo $this->Form->hidden('User', 
                    array('ID' => $userData[0]['User']['ID'],
                            'type' => 'hidden'));

            echo $this->Form->end('Save');

        ?>
    </div>

</div>

有没有人看到我没有做的事情会允许我编辑/更新现有记录而不是插入一个全新的记录? 感谢您的宝贵时间!

【问题讨论】:

  • 不确定它是否会有所作为...但是当我使用 ID 输入字段进行类似这样的操作时,我倾向于使用类似这样的内容:echo $this-&gt;Form-&gt;input('id', array('type' =&gt; 'hidden'));
  • 就是这样!感谢您纠正我的 n00b 错误。 :)

标签: forms cakephp sql-update cakephp-model


【解决方案1】:

问题可能与这里使用的表单元素的类型有关;我建议在您的 /View/Users/edit_user.ctp 文件中尝试这样的操作:

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

有关保存编辑的更多信息,请参阅CakePHP blog tutorial

【讨论】:

    【解决方案2】:

    您不需要在表单中回显值,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-&gt;request-&gt;data 中的内容自动使用值填充表单字段。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多