2014-02-11 2 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.')); 
    } 
} 

문제는 네 번째 코드 줄입니다. 문자열을 전달하면 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'); 
?> 

입니까? 변수로이 작업을 수행하려면 어떻게해야합니까?

답변

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

을 사용하는 것입니다하지만이 경우에 너무 많은 의미가 없다.

관련 문제