2014-02-11 201 views
1

我试图将一个变量从我的控制器传递到视图中。这只是一个简单的添加操作。将变量从控制器传递到cakephp中的视图

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

问题是第四行代码。如果我传递一个字符串,更新语句就可以工作,并且我最终会在我的表中使用该字符串。不过,我想将当前登录的用户作为字符串传递给数据库。在我的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'); 
?> 

我缺少什么?我如何使用变量进行这项工作?

回答

3

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

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']; 

但不会做出太大的意义了这种情况。

相关问题