[英]Passing variable from controller to the view in 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.'));
}
}
问题是第四行代码。 如果我传递一个字符串,则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');
?>
我错过了什么? 如何使用变量进行此操作?
你可以在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'];
但对于这种情况来说,这不会太有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.