0

I thought this would be a relatively common thing to do, but I can't find examples anywhere, and the Cookbook's section on find() was not clear in the slightest on the subject. Maybe it's just something that's so simple Cake assumes you can just do it on your own.

All I'm looking to do here is retrieve a User's name (not the currently logged-in user…a different one) in Cake based on their ID passed to my by an array in the view.

Here's what I've got in the controller:

public function user_lookup($userID){
  $this->User->flatten = false;
  $this->User->recursive = 1;
  $user = $this->User->find('first', array('conditions' => $userID));
  //what now?
}

At this point, I don't even know if I'm on the right track…I assume this will return an array with the User's data, but how do I handle those results? How do I know what the array's gonna look like? Do I just return($cakeArray['first'].' '.$cakeArray['last'])? I dunno…

Help?

tereško
  • 58,060
  • 25
  • 98
  • 150
joshdcomp
  • 1,618
  • 3
  • 19
  • 26

1 Answers1

2

You need to use set to take the returned data, and make it accessible as a variable in your views. set is the main way you send data from your controller to your view.

public function user_lookup($userID){
  $this->User->flatten = false;
  $this->User->recursive = 1;

  // added - minor improvement
  if(!$this->User->exists($userID)) {
      $this->redirect(array('action'=>'some_place')); 
      // the requested user doesn't exist; redirect or throw a 404 etc.
  }

  // we use $this->set() to store the data returned. 
  // It will be accessible in your view in a variable called `user` 
  // (or what ever you pass as the first parameter)
  $this->set('user', $this->User->find('first', array('conditions' => $userID)));

}


// user_lookup.ctp - output the `user`
<?php echo $user['User']['username']; // eg ?>
<?php debug($user); // see what's acutally been returned ?>

more in the manual (this is fundamental cake stuff so might be worth having a good read)

Ross
  • 18,117
  • 7
  • 44
  • 64
  • 1
    Upvoted because it's the correct answer, but you might want to not query the database twice for such a simple operation. A cleaner way is to do a `$user = $this->User->find(...)` and then redirect if `empty($user)`, otherwise set for view. Also, your link points to 1.3 version of the manual, while the question is tagged with 2.0. – dr Hannibal Lecter Jun 12 '12 at 13:16