从 cakephp 设置默认值

Set default values form cakephp

我想为我的用户 table 中的两个字段设置默认值。 用户 table 是这样的: Users(id, role, name, username, password, active) 我的 UsersController 中有一个 add() 函数来注册新用户。这是表格:

<?php echo $this->Form->create('User');?>
<?php echo $this->Form->input('name', array('class' => 'form-control')); ?>
<br />
<?php echo $this->Form->input('username', array('class' => 'form-control')); ?>
<br />
<?php echo $this->Form->input('password', array('class' => 'form-control')); ?>
<br />
<?php echo $this->Form->button('Submit', array('class' => 'btn btn-primary')); ?>
<?php echo $this->Form->end(); ?>

Role 和 active 不在这里,因为我想默认设置它们的值。新用户不能选择他的角色以及他是否活跃。 我的 add() 函数:

public function add() {
    if ($this->request->is('post')) {
        //$this->data['User']['role'] = 'customer';
        //$this->data['User']['active'] = 1;
        $this->User->create();
        if ($this->User->save($this->request->data)) {
            $this->Session->setFlash('User registred.');
            return $this->redirect(array('action' => '/'));
        } else {
            $this->Session->setFlash('The user could not be saved. Please, try again.');
        }
    }
}

如何在创建或更新用户之前设置这些值?我试着用 save() 来做,但它不起作用。

感谢您的建议。

也许你应该是这样的?

public function add() {
    if ($this->request->is('post')) {
        $data = $this->request->data;
        $data['User']['role'] = 'customer';
        $data['User']['active'] = 1;
        $this->User->create();
        if ($this->User->save($data)) {
            $this->Session->setFlash('User registred.');
            return $this->redirect(array('action' => '/'));
        } else {
            $this->Session->setFlash('The user could not be saved. Please, try again.');
        }
    }
}

这样试试:

public function add() {
    if ($this->request->is('post')) {
        $this->request->data['User']['role'] = 'customer';
        $this->request->data['User']['active'] = 1;
        $this->User->create();
        if ($this->User->save($this->request->data)) {
           $this->Session->setFlash('User registred.');
           return $this->redirect(array('action' => '/'));
        } else {
           $this->Session->setFlash('The user could not be saved. Please, try again.');
        }
    }
}