[英]Set default values form cakephp
I'd like to set a default value for two fields in my Users table. 我想为“用户”表中的两个字段设置默认值。 Users table is like that :
Users(id, role, name, username, password, active)
I have a add()
function in my UsersController to register new user. Users表是这样的:
Users(id, role, name, username, password, active)
我在UsersController中有一个add()
函数来注册新用户。 Here is the form : 表格如下:
<?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 and active aren't here because I want to set their values by default. 角色和主动不在这里,因为我想默认设置它们的值。 A new user can't choose his role and if he's active or not.
新用户无法选择他的角色,也不能选择他是否处于活动状态。 My
add()
function : 我的
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.');
}
}
}
How can I set these values before create a user, or update it? 在创建用户或更新用户之前,如何设置这些值? I tried to do it with save() but it doesn't work.
我试图用save()做到这一点,但是它不起作用。
Thanks for your advices. 感谢您的建议。
Try it like this: 像这样尝试:
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.');
}
}
}
May be your should be like this? 可能是您应该这样吗?
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.');
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.