我想在Users表中为两个字段设置默认值。
用户表是这样的:
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(); ?>
角色和活动不在这里,因为我想默认设置它们的值。新用户无法选择他的角色以及他是否活跃。
我的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()来做,但它不起作用。
感谢您的建议。
答案 0 :(得分:2)
试试这样:
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.');
}
}
}
答案 1 :(得分:0)
可能你应该这样吗?
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.');
}
}
}