Question

in the sections_controller i use loadmodel to print username in sections/index file but i get error :
Notice (8): Undefined variable: user [APP\views\sections\index.ctp, line 3]

public function index ()
        {

       $this->loadModel('User');
      $user = $this->User->find('all');
       $this->Section->find('threaded', array('order' => array('Section.created ASC')));
       $this->set('data','user');
          }

in the sections/index

<div><?php echo $user['User']['username']; ?></div>
Was it helpful?

Solution

You're not assigning the variable properly, try this instead:

$this->set('user', $user);

$user pointing to your find result and set as user, since that's what you're trying to call in your view. Or alternatively use the compact notation to achieve the same:

$this->set(compact('user'));

What you are doing now is setting a variable called data with the string value user, so when you would do this in your view:

echo $data;

It would return user as a string in your view.

EDIT

Since a find('all') will return an array, make sure you loop over the results in your view as well, like this:

foreach($user as $u) {
    echo $u['User']['username'];
}

Or if you want a specific result, call it's array key, which for the first user would be:

echo $user[0]['User']['username'];

OTHER TIPS

You have a typo, try :

$this->set('data',$user);

and then in your view :

<div><?php echo $data['User']['username']; ?></div>

Hope this helps !

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top