php - Auth not working in view
Get the solution ↓↓↓I'm trying to make certain buttons appear only to certain user types, I was adding this code around buttons in my view:
<li><?php
if($this->Auth->user('role_id')==8){
echo $this->Html->link(__('New Consumer Product'), array('action' => 'add'));
}
?>
</li>
But that just gave me the errorError: AuthHelper could not be found.
so I added the following in my AppController:
public $helpers = array('Auth');
However this just gave me the following error:
Helper class AuthHelper could not be found.
Error: An Internal Error Has Occurred.
What's happening here? Shouldn't it have worked when I added the Auth helper into my AppController?
I'd previously been using Auth in my UsersController with no problems at all.
Answer
Solution:
You can't use Auth in the view. That's only for controllers.
There are actually a few options such as setting/passing a variable for it, but this is the correct way as per the manual
if((AuthComponent::user('role_id') == 8) {
...
}
Answer
Solution:
In your AppControllersbeforeRender()
orbeforeFilter()
just set the active user to the view:
public function beforeRender() {
$this->set('userData', $this->Auth->user());
}
And work with that variable in the view. I prefer to not use the static method calls on the component inside a view, it's the wrong place for a component and also static calls aren't something you want to introduce a lot because of tight coupling.
My BzUtils plugin comes with a helper that can deal with this variable or can be configured to read the user data from session and offers some convenience methods.
Answer
Solution:
in cake 3.x I found the only thing that worked is to set the variable in AppController.php as so:
public function beforeRender(\Cake\Event\Event $event) {
$this->set(['userData'=> $this->Auth->user(),
]);
}
the key difference being you have to pass in $event...
Answer
Solution:
Auth is a component not a helper. There is no Auth helper.
You can read the Authenticated user from the following command
$user = $this->Session->read("Auth.User");
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: dompdf image not found or type unknown
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.