Cakephp模型不会保存表单输入

时间:2014-02-21 13:26:14

标签: php forms cakephp model

我有一个非常简单的模型用户,它与关联的表用户有字段'id','username','password','role','created','modified'。

视图add.ctp包含:

<div class="users form">
    <?= $this->Form->create('user'); ?>

    <fieldset>
        <legend><?= __('Add user');?></legend>
        <?= $this->Form->input('user.username'); ?>

        <?= $this->Form->input('password'); ?>

        <?= $this->Form->input('role', array('options' => array('admin' => 'Admin', 'customer' => 'Customer'))); ?>

    </fieldset>
    <?= $this->Form->end(__('Submit')); ?>
</div>

根据http://book.cakephp.org/2.0/en/tutorials-and-examples/blog-auth-example/auth.html

设置模型
class User extends AppModel {
    public $validate = array( 
        'username'  => array(
            'required'  => array(
                'rule'      => array('notEmpty'),
                'message'   => 'You must specify a username'
            )
        ),
        'password'  => array(
            'required'  => array(
                'rule'      => array('notEmpty'),
                'message'   => 'You must specify a password'
            )
        ),
        'role'      => array(
            'valid'     => array(
                'rule'      => array('inList', array('admin','customer')),
                'message'   => 'You must specify a valid role',
                'allowEmpty'=> false
            )
        )
    );
}

最后,控制器只是:

public function add() {
    if($this->request->is('post')) {
        $this->User->create();
        if ($this->User->save($this->request->data)) {
            $this->set('stuff', $this->User->data);
            $this->Session->setFlash(__('The user has been saved.'));
            //return $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The user could not be saved. Please try again.'));
        }
    }
}

我已经注释掉成功的重定向,以便能够在提交时显示INSERT查询(如果我允许重定向,则显示的唯一查询是SELECT)

所以,非常简单,问题是,当提交表单时,它会生成此查询:

INSERT INTO `mytable`.`users` (`modified`, `created`) VALUES ('2014-02-21 13:03:11', '2014-02-21 13:03:11')

如何确定不插入提交字段的原因?我该怎么做呢?

1 个答案:

答案 0 :(得分:1)

使用此<?= $this->Form->create('User'); ?>代替<?= $this->Form->create('user'); ?>

并使用此<?= $this->Form->input('User.username'); ?>代替<?= $this->Form->input('user.username'); ?>

CakePHP区分大小写的模型名称必须在CamalCase中