简体   繁体   中英

Yii2 - validate field from model in main.php file

I have a table called user, and inside it a field called estatuto.

Only users with estatuto == admin can see Admin hyperlink in my NavBar widget located in main.php file.

My problem is to check in:

'label' => 'Admin', 'visible' => !Yii::$app->user->isGuest,

if a user is logged with estatuto == admin, and only in that condition show the admin hyperlink.

I can only check if a user is Guest or not Guest.

I need something like:

'label' => 'Admin', 'visible' => !Yii::$app->user->isGuest && User::estatuto = 'admin',

I searched a lot and the only thing i saw and couldn't understand was through:

$this->view->params['customParam'] = 'customValue';

But maybe there's another aproach.

Anyone can help me solve this problem?

Your task is not about validating model field, it is classical permission management task. So you should use Yii2 RBAC feature. in that case you can check permission like that:

\Yii::$app->user->can('viewAdminMenu')

Store the value of estatuto in session when the user logs in.

Then at any point just call that value from session.

Also don't set the visible tag for access. You need to not show the entire link if not admin. Also hiding just links is not enough, you need to check for access within the controller as well.

A better way to do this is use Role Based Access Control or RBAC.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM