【问题标题】:Set default values form cakephp设置默认值表单 cakephp
【发布时间】:2015-11-13 08:29:15
【问题描述】:

我想为我的用户表中的两个字段设置一个默认值。 用户表是这样的: 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() 来做,但它不起作用。

感谢您的建议。

【问题讨论】:

  • 你应该使用$this-&gt;request-&gt;data。试试看。

标签: php cakephp cakephp-2.0


【解决方案1】:

试试这样:

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.');
        }
    }
}

【讨论】:

  • 非常感谢!它与$this-&gt;request-&gt;data 合作
【解决方案2】:

也许你的应该是这样的?

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.');
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    相关资源
    最近更新 更多