0

为 UsersController 编写 add() 函数时出现问题。

    public function add(){
        if ($this->request->is('post')) {
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash('The new user has been saved.');
                $this->redirect(array('action' => 'test'));
            }
        }
        $this->set('title_for_layout', 'Register');
    }

这是添加视图 ctp。

    <?php
    echo $this->Form->create('User');
    echo $this->Form->input('username');
    echo $this->Form->input('password');
    echo $this->Form->end('Save User');
    ?>

当我尝试访问用户/添加时总是出现内部错误。有谁知道如何处理这个问题?谢谢。

4

1 回答 1

1

您是否尝试过测试$this->data而不是$this->request->is('post')?这可能无关紧要,但这通常是它的完成方式。

此外,为了保存,您很可能(除非您手动设置用户 ID)执行以下操作:

$this->User->create();
$this->User->save($this->data);

所以你的 add 函数应该是这样的:

public function add(){
        if ($this->data) {
            $this->User->create();
            if ($this->User->save($this->data)) {
                $this->Session->setFlash('The new user has been saved.');
                $this->redirect(array('action' => 'test'));
            }
        }
        $this->set('title_for_layout', 'Register');
    }

您可能希望您的视图类似于:

<?php echo $form->create('User', array('action' => 'add')); ?>
<?php echo $form->input("username", array('label' => 'Username'))   ?>
<?php echo $form->input("password",array("type"=>"password", 'label' => 'password')) ?>
<?php echo $form->submit('Submit'); ?>
于 2011-12-09T18:39:58.143 回答