Yii2 显示/隐藏 kartik 树视图节点 [英] Yii2 Show/Hide kartik treeview nodes
问题描述
我正在使用
我想做什么
现在我只想显示指定的节点及其子节点,并向该用户隐藏其他节点
控制器
目前,我正在渲染树结构的视图有两种,但将来会有更多
我的首页
公共函数 actionIndex(){if(Yii::$app->user->isGuest){$this->redirect(Yii::$app->urlManager->createUrl('site/login'));}返回 $this->render('index');}
本身的树管理器节点控制器
/*** 通过 ajax 查看、创建或更新树节点** @return 混合 json 编码响应*/公共函数 actionManage(){静态::checkValidRequest();$data = static::getPostData();$nodeTitles = TreeSecurity::getNodeTitles($data);$callback = function () use ($data, $nodeTitles) {$id = ArrayHelper::getValue($data, 'id', null);$parentKey = ArrayHelper::getValue($data, 'parentKey', '');$parsedData = TreeSecurity::parseManageData($data);$out = $parsedData['out'];$oldHash = $parsedData['oldHash'];$newHash = $parsedData['newHash'];/*** @var 模块 $module* @var 树 $treeClass* @var 树 $node*/$treeClass = $out['treeClass'];if (!isset($id) || empty($id)) {$node = 新 $treeClass;$node->initDefaults();} 别的 {$node = $treeClass::findOne($id);}$module = TreeView::module();$params = $module->treeStructure + $module->dataStructure + ['节点' =>$节点,'父密钥' =>$parentKey,'treeManageHash' =>$newHash,'treeRemoveHash' =>ArrayHelper::getValue($data, 'treeRemoveHash', ''),'treeMoveHash' =>ArrayHelper::getValue($data, 'treeMoveHash', ''),] + $出;if (!empty($data['nodeViewParams'])) {$params = ArrayHelper::merge($params, unserialize($data['nodeViewParams']));}if (!empty($module->unsetAjaxBundles)) {$cb = 函数($e)使用($module){foreach ($module->unsetAjaxBundles 作为 $bundle) {unset($e->sender->assetBundles[$bundle]);}};Event::on(View::class, View::EVENT_AFTER_RENDER, $cb);}TreeSecurity::checkSignature('manage', $oldHash, $newHash);return $this->renderAjax($out['nodeView'], ['params' => $params]);};返回 self::process($回调,Yii::t('kvtree', '查看 {node} 时出错.请稍后再试.', $nodeTitles),空值);}
我怎样才能实现它?任何帮助将不胜感激.
实现隐藏/显示某些节点的一种方式可能如下:
在视图中你应该有你的数据库表名.
查找您感兴趣的表名.
在表名的文件夹内应该有如下文件名:_form.php、_script.php 和 index.php
index.php 文件应该有一些用处,其中应该有:...
使用kartik\tree\TreeView;
使用kartik\tree\Module;
...
在这些 use 语句之后,您可以添加以下代码:
/** @var integer $uid */
//获取当前登录的用户 ID.//这用于控制显示树的内容,和//控制表单域.if (isset(Yii::$app->user)) {$uid = Yii::$app->user->getId();}
所以现在登录的用户ID保存在变量$uid
在同一个 index.php 文件中,您应该有呈现树视图的代码.开头是:echo TreeView::widget
在这个 TreeView::widget([.. 你可以添加一个查询,它只呈现当前登录的用户内容,像这样:
'查询' =>YourTableName::find()->where(['user_id' => $uid])->addOrderBy('root, lft'),
...其他设置...
如果您希望管理员查看或更改内容,您可以添加一个控制器,例如名为 AdminController,然后在这个 index.php TreeView::widget 中您可以添加更多这样的选项:
echo TreeView::widget(['查询' =>YourTableName::find()->where(['user_id' => $uid])->addOrderBy('root, lft'),'headingOptions' =>['标签' =>'你的标签名'],//'rootOptions' =>['标签' =>'<span class="text-success">Root</span>'],'fontAwesome' =>错误的,'isAdmin' =>真的,'showInactive' =>AdminController::isAdmin(),'显示值' =>0,'showIDAttribute' =>真的,'emptyNodeMsg' =>'在这里输入一些信息......','showCheckbox' =>错误的,'多个' =>错误的,'选项' =>['id' =>'树ID'],'allowNewRoots' =>错误的,'工具栏' =>['创建' =>['始终禁用' =>真的],//'删除' =>['始终禁用' =>!(AdminController::isAdmin())],//'上移' =>['始终禁用' =>!(AdminController::isAdmin())],//'下移' =>['始终禁用' =>!(AdminController::isAdmin())],//'向左移动' =>['始终禁用' =>!(AdminController::isAdmin())],//'向右移动' =>['始终禁用' =>!(AdminController::isAdmin())],//'删除' =>错误的,],'cascadeSelectChildren' =>错误的,//'softDelete' =>错误的,'iconEditSettings'=>['显示' =>'列表','列表数据' =>[//'文件夹' =>'文件夹','文件' =>'文件','星' =>'星星','铃' =>'钟',//'电话' =>'电话',]],'缓存设置' =>['启用缓存' =>真的],'nodeAddlViews' =>[模块::VIEW_PART_1 =>'@app/views/mappings/_form',],]);
这只是一个小小的开始,但您可以更进一步.例如,假设用户未登录或假设您想以任何方式显示某些节点.在这些情况下,您可以使用 switch case 语句并检查例如 $uid 是否未定义(未设置,因为用户未登录)在这种情况下,您可以要求用户登录或呈现或显示不同的树视图:
开关($SomeVariable){案例case_to_check":echo TreeView::widget([...'查询' =>TableName::find()->where(['user_id' => $uid])->addOrderBy('root, lft'),...休息;
案例another_case":echo TreeView::widget([...休息;默认:echo TreeView::widget([...
== 你也可以在 index.php 的顶部添加 html select,像这样:
然后使用java脚本过滤和捕获选定的值,然后您可以在switch case中使用此值来显示某些节点.您可以将 java 脚本代码放在 <?php 块中,并在 switch case 或 echo TreeView::widget([ .java 脚本代码可能如下所示:
$this->registerJs(";$('select[name=".The_name_you_give_in_select"."]').change(function(){var 值 = $(this).val();开关(值){情况1':window.location.href = \你的页面名称?what=mynodes\";;休息;情况2":window.location.href = \你的页面名称?what=othernodes\";;休息;默认:window.location.href = \你的页面名称?what=allnodes\";;}});", 视图::POS_READY);
=== 然后检查 switch case 中 what 的值并使用它来过滤要显示的树节点.类似于上面的java脚本代码下面的代码:
/** @var integer $The_name_you_give_in_select *///从选择菜单中获取值.//这用于过滤和显示所需的树.如果 (isset($_GET['what'])) {$The_name_you_give_in_select = $_GET['what'];} 别的 {$The_name_you_give_in_select = "defaultcase";}//然后在切换案例中:开关($The_name_you_give_in_select){案例mynodes":echo TreeView::widget([...休息;案例其他节点":echo TreeView::widget([...休息;默认:echo TreeView::widget([...
=============== 您可能还想对 views/your_table_name/_form.php 进行一些更改
在 _form.php 中,您还可以控制要显示的字段、将哪些字段设为可编辑或只读等,如下所示:== _form.php:
.../** @var 整数 $userid */
//在 var $userid 中保存当前节点用户 ID//用于控制表单域$userid = $node->user_id;...if(isset($userid)){$username = Yii::$app->user->identity;}...<div class="your-form">...<?= $form->field($node, 'annotation')->textarea(['rows' => 6, 'readonly' => !(Yii::$app->user->identity->id == $userid or AdminController::isAdmin())]) ?><?= $form->field($node, 'comments')->textarea(['rows' => 6, 'readonly' => !(Yii::$app->user->identity->id == $userid or AdminController::isAdmin())]) ?><!-- <?/*= $form->field($username, 'username')->textInput(['maxlength' => true, 'readonly'=>true])->label('由用户创建') */?>--><?= $form->field($node, 'user_id')->textInput(['readonly'=>true]) ?><?= $form->field($node, 'date_ added')->textInput(['placeholder' => '添加日期', 'readonly'=>true]) ?>
============= AdminContoler.php 可能看起来像这样:
用户 ->admins 并添加您希望成为管理员访问和管理用户的用户名* - (2) THEN 在view views/layouts/main.php 中,按照第62 行中相同的逻辑添加用户名.** @return 布尔值*/公共静态函数 isAdmin(){如果 (Yii::$app->user->identity->username == '在此输入用户名'或者Yii::$app->user->identity->username == '在此输入用户名'//例如,通过取消注释以下行并输入您想成为管理员的用户名,在此处添加更多内容//或者//Yii::$app->user->identity->username == '在此输入用户名'//或者//Yii::$app->user->identity->username == '在此输入用户名'//或者//Yii::$app->user->identity->username == '在此输入用户名'){返回真;} 别的 {返回假;}}}
I am using Kartik Tree Manager. I am able to add, remove, update nodes. There is more requirement, that is to show/hide nodes on the basis of user access. i.e. when a user is given a specific node(s) then only that particular node(s) with all the child (if any) should be shown.
What I have done so far?
I have created a table user-node
in which I am assigning a node id to a user as shown below
What I want to do
Now I want to show only the specified node with its child node only and hide other nodes to that user
Controller
For now, there are two views in which I am rendering the tree structure but in the future, there shall be more
My front page
public function actionIndex() { if(Yii::$app->user->isGuest){ $this->redirect(Yii::$app->urlManager->createUrl('site/login')); } return $this->render('index'); }
Itself tree-manager node controller
/** * View, create, or update a tree node via ajax * * @return mixed json encoded response */ public function actionManage() { static::checkValidRequest(); $data = static::getPostData(); $nodeTitles = TreeSecurity::getNodeTitles($data); $callback = function () use ($data, $nodeTitles) { $id = ArrayHelper::getValue($data, 'id', null); $parentKey = ArrayHelper::getValue($data, 'parentKey', ''); $parsedData = TreeSecurity::parseManageData($data); $out = $parsedData['out']; $oldHash = $parsedData['oldHash']; $newHash = $parsedData['newHash']; /** * @var Module $module * @var Tree $treeClass * @var Tree $node */ $treeClass = $out['treeClass']; if (!isset($id) || empty($id)) { $node = new $treeClass; $node->initDefaults(); } else { $node = $treeClass::findOne($id); } $module = TreeView::module(); $params = $module->treeStructure + $module->dataStructure + [ 'node' => $node, 'parentKey' => $parentKey, 'treeManageHash' => $newHash, 'treeRemoveHash' => ArrayHelper::getValue($data, 'treeRemoveHash', ''), 'treeMoveHash' => ArrayHelper::getValue($data, 'treeMoveHash', ''), ] + $out; if (!empty($data['nodeViewParams'])) { $params = ArrayHelper::merge($params, unserialize($data['nodeViewParams'])); } if (!empty($module->unsetAjaxBundles)) { $cb = function ($e) use ($module) { foreach ($module->unsetAjaxBundles as $bundle) { unset($e->sender->assetBundles[$bundle]); } }; Event::on(View::class, View::EVENT_AFTER_RENDER, $cb); } TreeSecurity::checkSignature('manage', $oldHash, $newHash); return $this->renderAjax($out['nodeView'], ['params' => $params]); }; return self::process( $callback, Yii::t('kvtree', 'Error while viewing the {node}. Please try again later.', $nodeTitles), null ); }
How can I achieve it? Any help would be highly appreciated.
One way to achieve hide/show some nodes may be as follows:
In views you should have your db table names.
Look for the table name you are interested in.
Inside the folder of the table name there should be files names something like: _form.php, _script.php and index.php
The index.php file should have some use among of which there should be: ...
use kartik\tree\TreeView;
use kartik\tree\Module;
...
After these use statements, you can add this code:
/** @var integer $uid */
// get current logged in user id. // this is used to control showing tree content, and // to control form fields. if (isset(Yii::$app->user)) { $uid = Yii::$app->user->getId(); }
So now the logged in user id is saved in variable $uid
In the same index.php file you should have code that renders the tree view. Something starts with: echo TreeView::widget
Inside this TreeView::widget([.. you can add a query that renders only current logged in user content, like this:
'query' => YourTableName::find()->where(['user_id' => $uid])->addOrderBy('root, lft'),
... Other settings ...
If you want the admin(s) to see or change the content, you can add a Controller for example named AdminController, then in this index.php TreeView::widget you can add more options like this:
echo TreeView::widget([
'query' => YourTableName::find()->where(['user_id' => $uid])->addOrderBy('root, lft'),
'headingOptions' => ['label' => 'YourLableName'],
//'rootOptions' => ['label' => '<span class="text-success">Root</span>'],
'fontAwesome' => false,
'isAdmin' => true,
'showInactive' => AdminController::isAdmin(),
'displayValue' => 0,
'showIDAttribute' => true,
'emptyNodeMsg' => ' type some msg here ... .',
'showCheckbox' => false,
'multiple' => false,
'options' => ['id' => 'treeID'],
'allowNewRoots' => false,
'toolbar' => [
'create' => ['alwaysDisabled' => true],
//'remove' => ['alwaysDisabled' => !(AdminController::isAdmin())],
// 'move-up' => ['alwaysDisabled' => !(AdminController::isAdmin())],
// 'move-down' => ['alwaysDisabled' => !(AdminController::isAdmin())],
// 'move-left' => ['alwaysDisabled' => !(AdminController::isAdmin())],
// 'move-right' => ['alwaysDisabled' => !(AdminController::isAdmin())],
//'remove' => false,
],
'cascadeSelectChildren' => false,
//'softDelete' => false,
'iconEditSettings'=> [
'show' => 'list',
'listData' => [
// 'folder' => 'Folder',
'file' => 'File',
'star' => 'Star',
'bell' => 'Bell',
// 'phone' => 'Phone',
]
],
'cacheSettings' => ['enableCache' => true],
'nodeAddlViews' => [
Module::VIEW_PART_1 => '@app/views/mappings/_form',
],
]);
This is just a small start, but you can take it further. For example suppose the user is not logged in or suppose you want to show some nodes any way. In these cases you can use switch case statement and check for example if $uid is not defined (it is not set because the user is not logged in) in this case, you can ask the user to log in or render or show a different tree view:
switch ($SomeVariable) { case "case_to_check": echo TreeView::widget([ ... 'query' => TableName::find()->where(['user_id' => $uid])->addOrderBy('root, lft'), ... break;
case "another_case": echo TreeView::widget([ ... break; default: echo TreeView::widget([ ...
== You can also add html select at the top of index.php, something like this:
<select name="Give_any_name_you_like" size=1 class="btn btn-primary" style="margin-bottom: 0.5em; margin-left: 0.5em; ">
<option value="0">Select Node</option>
<option value="1">mynodes</option>
<option value="2">othernodes</option>
<option value="3">allnodes</option>
</select>
then use java script to filter and capture the selected value, then you can use this vale in switch case to show certain nodes. You can place the java script code inside <?php block and before switch case or echo TreeView::widget([ . java script code may look something like this:
$this->registerJs("
$('select[name=" . "The_name_you_give_in_select" . "]').change(function(){
var value = $(this).val();
switch(value) {
case '1':
window.location.href = \"your-page-name?what=mynodes\" ;
break;
case '2':
window.location.href = \"your-page-name?what=othernodes\" ;
break;
default:
window.location.href = \"your-page-name?what=allnodes\" ;
}
});", View::POS_READY);
=== Then you check for the value of what in switch cases and use it to filter which tree node to show. Something like this code just below above java script code:
/** @var integer $The_name_you_give_in_select */
// get value from selection menu.
// this is used to filter and show desired tree.
if (isset($_GET['what'])) {
$The_name_you_give_in_select = $_GET['what'];
} else {
$The_name_you_give_in_select = "defaultcase";
}
// Then in switch case:
switch ($The_name_you_give_in_select) {
case "mynodes":
echo TreeView::widget([
...
break;
Case "othernodes":
echo TreeView::widget([
...
break;
default:
echo TreeView::widget([
...
============= === Also you may want to do some changes in views/your_table_name/_form.php
In _form.php you can also control what fields to show, what fields to make editable or read only, etc. something like this: == _form.php:
... /** @var integer $userid */
// save current node user id in var $userid // to be used to control form fields $userid = $node->user_id; ... if(isset($userid)){ $username = Yii::$app->user->identity; } ... <div class="your-form"> ... <?= $form->field($node, 'annotation')->textarea(['rows' => 6, 'readonly' => !(Yii::$app->user->identity->id == $userid or AdminController::isAdmin())]) ?> <?= $form->field($node, 'comments')->textarea(['rows' => 6, 'readonly' => !(Yii::$app->user->identity->id == $userid or AdminController::isAdmin())]) ?> <!-- <?/*= $form->field($username, 'username')->textInput(['maxlength' => true, 'readonly'=>true])->label('Created by User') */?>--> <?= $form->field($node, 'user_id')->textInput(['readonly'=>true]) ?> <?= $form->field($node, 'date_added')->textInput(['placeholder' => 'Date Added', 'readonly'=>true]) ?> </div>
========= === The AdminContoler.php may look something like this:
<?php
namespace app\controllers;
use Yii;
...
class AdminController extends Controller
{
/**
*
* manage admins.
* add admins here
* this will allow admins more control on all tables, but not accessing and managing users
* controlling, accessing and managing users is configured through:
* - config/web.php and views/layouts/main.php
* - (1) in config/web.php go to modules -> user -> admins and add username(s)that you want to be admin accessing and managing users
* - (2) THEN in view views/layouts/main.php, follow the same logic in line 62 and add username(s).
*
* @return bool
*/
public static function isAdmin()
{
if (
Yii::$app->user->identity->username == 'type user name here'
or
Yii::$app->user->identity->username == 'type user name here'
// add more here for example by uncommenting the following lines and typing username that you want to be admin
// or
// Yii::$app->user->identity->username == 'type user name here'
// or
// Yii::$app->user->identity->username == 'type user name here'
// or
// Yii::$app->user->identity->username == 'type user name here'
) {
return true;
} else {
return false;
}
}
}
这篇关于Yii2 显示/隐藏 kartik 树视图节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!