问题
I am developing a website using Kohana 3.3 and i want to selectively display HTML UI elements depending on the role of the user. e:- If user is an admin then show the 'edit' hyperlink, and when the admin clicks the edit button change the textbox's from 'readonly' to 'normal'.
If user is an registered normal user than enable the button to 'ask a question'.
If user is a visitor then he have no priviliges.
Right now i am using a single view file and changing the visbility after checking the status of php variables. Somehow, i feel that i am not doing it correctly, what is the suggested method to handle such scenarios( any plugins?) ?
回答1:
Ok, so you want to distinguish three different cases
- visitor
- admin
- user
The place to handle this, is your controller. In this you have access to Auth::instance()->get_user().
$user = Auth::instance()->get_user();
if ($user === null) {
//visitor
} else {
if ($user->has('roles', ORM::factory('Role', array('name' => 'admin')))) {
//admin
} else {
//user
}
}
Now that you know how to handle the cases, you somehow need to tell your view. To do that, you can create a new variable in which you load either one of three views - one for each case.
$specificViewName = "";
$user = Auth::instance()->get_user();
if ($user === null) {
$specificViewName = "visitor";
} else {
if ($user->has('roles', ORM::factory('Role', array('name' => 'admin')))) {
$specificViewName = "admin";
} else {
$specificViewName = "user";
}
}
$specificView = View::factory("index/".$specificViewName);
If you are in a Controller_Template
, you can now use $this->template->set("specificView", $specificView);
.
In this case you'd have a index template like this
<html><!--etc.-->
<h1>Welcome to my website</h1>
<!--stuff all sites share like navigation-->
<?php print $specificView; ?>
<!--more-->
</html>
And index/visitor
<span class="sadtext">Nothing special for you here</span>
index/user
<form>
<button>ask a question!
</form>
index/admin
<a href="edit">hyperlink</a>
来源:https://stackoverflow.com/questions/23323414/how-to-hide-part-of-html-form-depending-on-user-role