Issue
Having started with CakePHP 3.0 I find docummentation very confusing as by following the code snippets I have genertaed the following code:
if($this->Auth->User('role') != 'Admin' ){
$query = $users->find('all')
->where(['Users.group_id' => $this->Auth->User('group_id')]);
$this->set('users', $this->paginate($query->all()));
}else{
$this->set('users', $this->paginate($this->Users));
}
Which runs perfectly fine if user is an admin, howver if he is not, then the code breaks on this line: $query = $users->find('all')
The following message is being provided:
Call to a member function find() on a non-object
The code is run in users controller
.
Any help or guidance is much appreciated.
Solution
Try this instead:
if($this->Auth->User('role') != 'Admin' ){
$options = [
'conditions' => array(
"Users.group_id" => $this->Auth->User('group_id')
)];
$query = $users->find('all', $options);
$this->set('users', $this->paginate($query));
}else{
$this->set('users', $this->paginate($this->Users));
}
I think your issue is that you are essentially calling 'find' incorrectly.
$query = $users->find('all') ->$options
(not your exact code, but essentially what you have done, to help compare to my solution) should be
$query = $users->find('all', $options)
with $options declared above. This is a much cleaner way (in my opinion at least) of managing find options, an can be reused if needed once they are set to a variable.
Answered By - Ash Betts
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.