2014-02-11 5 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

Вы можете использовать $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']; 

, но это не сделало бы слишком много смысла для для этого случая.

Смежные вопросы