将变量从控制器传递到cakephp中的视图

时间:2014-02-11 20:12:57

标签: php cakephp cakephp-2.0

我正在尝试将控制器中的变量传递给视图。这只是一个简单的添加操作。

public function add() {
    if($this->request->is('post')) {
        $this->Post->create();
        $this->request->data['Post']['username']= $current_user['username'];
        if($this->Post->save($this->request->data)) {
            $this->Session->setFlash(__('Your post has been saved.'));
            return $this->redirect(array('action'=>'index'));
        }
        $this->Session->setFlash(__('Unable to add your post.'));
    }
}

问题是第四行代码。如果我传递一个字符串,则update语句可以工作,我最终会在表格中找到该字符串。但是,我想将当前登录的用户作为字符串传递给数据库。在我的AppController我设置了$current_user。当我回显$current_user['username']时,我得到了正确的字符串。

public function beforeFilter() {
    $this->Auth->allow('index', 'view');
    $this->set('logged_in', $this->Auth->loggedIn());
    $this->set('current_user', $this->Auth->user());
}

视图只是一个简单的表单

<?php
echo $current_user['username'];
echo $this->Form->create('Post');
echo $this->Form->input('title');
echo $this->Form->input('body',array('rows'=>'3'));
echo $this->Form->input('username',array('type'=>'hidden'));
echo $this->Form->end('Save Post');
?>

我错过了什么?如何使用变量进行此操作?

1 个答案:

答案 0 :(得分:3)

您可以在$this->Auth->user('username')功能中使用add

public function add() {
    if ($this->request->is('post')) {
        $this->Post->create();
        $this->request->data['Post']['username'] = $this->Auth->user('username');
        if ($this->Post->save($this->request->data)) {
            $this->Session->setFlash(__('Your post has been saved.'));
            return $this->redirect(array('action'=>'index'));
        }
        $this->Session->setFlash(__('Unable to add your post.'));
    }
}

另一种选择是添加

$this->current_user = $this->Auth->user();
$this->set('current_user', $this->Auth->user());

并使用

$this->request->data['Post']['username'] = $this->current_user['username'];

但对于这种情况来说这没有多大意义。

相关问题