user3298823
user3298823

Reputation: 302

Passing variable from controller to the view in cakephp

I'm trying to pass a variable from my controller into a view. It's just a simple add action.

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

The issue is the fourth line of code. If I pass a string, the update statement works and I end up with that string in my table. However I want to pass the current logged in user to the database as a string. In my AppController I have the $current_user set up. When I echo out $current_user['username'] I get the correct string back.

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

The view is just a simple form

<?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');
?>

What am I missing? How do I make this work with a variable?

Upvotes: 1

Views: 1105

Answers (1)

cornelb
cornelb

Reputation: 6066

You can just use $this->Auth->user('username') in the add function.

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

Another option would be to add

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

And use

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

but that would not make too much sense for for this case.

Upvotes: 3

Related Questions