/** * @inheritDoc */ public function beforeSave($insert) { //新增有上级单位名称没有上级编码 if ($insert && $this->parent_name && !$this->parent) { $query = self::findOne(['name' => $this->parent_name]); if ($query) { $this->parent = $query->id; } else { return false; } } return parent::beforeSave($insert); }
/** * Searching menu * @param array $params * @return \yii\data\ActiveDataProvider */ public function search($params) { $query = MenuModel::find()->from(MenuModel::tableName() . ' t')->joinWith(['menuParent' => function ($q) { $q->from(MenuModel::tableName() . ' parent'); }]); $dataProvider = new ActiveDataProvider(['query' => $query]); $sort = $dataProvider->getSort(); $sort->attributes['menuParent.name'] = ['asc' => ['parent.name' => SORT_ASC], 'desc' => ['parent.name' => SORT_DESC], 'label' => 'parent']; $sort->attributes['order'] = ['asc' => ['parent.order' => SORT_ASC, 't.order' => SORT_ASC], 'desc' => ['parent.order' => SORT_DESC, 't.order' => SORT_DESC], 'label' => 'order']; $sort->defaultOrder = ['menuParent.name' => SORT_ASC]; if (!($this->load($params) && $this->validate())) { return $dataProvider; } $query->andFilterWhere(['id' => $this->id, 'parent' => $this->parent]); $query->andFilterWhere(['like', 'name', $this->name])->andFilterWhere(['like', 'route', $this->route])->andFilterWhere(['like', 'parent.name', $this->parent_name]); return $dataProvider; }
/** * Get menu children * @return \yii\db\ActiveQuery */ public function getMenus() { return $this->hasMany(Menu::className(), ['parent' => 'id']); }
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; use mdm\admin\models\Menu; use yii\helpers\Json; use mdm\admin\AutocompleteAsset; /* @var $this yii\web\View */ /* @var $model mdm\admin\models\Menu */ /* @var $form yii\widgets\ActiveForm */ AutocompleteAsset::register($this); $opts = Json::htmlEncode(['menus' => Menu::getMenuSource(), 'routes' => Menu::getSavedRoutes()]); $this->registerJs("var _opts = {$opts};"); $this->registerJs($this->render('_script.js')); ?> <div class="menu-form"> <?php $form = ActiveForm::begin(); ?> <?php echo Html::activeHiddenInput($model, 'parent', ['id' => 'parent_id']); ?> <div class="row"> <div class="col-sm-6"> <?php echo $form->field($model, 'name')->textInput(['maxlength' => 128]); ?> <?php echo $form->field($model, 'parent_name')->textInput(['id' => 'parent_name']);
/** * Use to get assigned menu of user. * @param mixed $userId * @param integer $root * @param \Closure $callback use to reformat output. * callback should have format like * * ~~~ * function ($menu) { * return [ * 'label' => $menu['name'], * 'url' => [$menu['route']], * 'options' => $data, * 'items' => $menu['children'] * ] * ] * } * ~~~ * @param boolean $refresh * @return array */ public static function getAssignedMenu($userId, $root = null, $callback = null, $refresh = false) { /* @var $manager \yii\rbac\BaseManager */ $manager = Yii::$app->getAuthManager(); $menus = Menu::find()->asArray()->indexBy('id')->all(); $key = [__METHOD__, $userId, $manager->defaultRoles]; $cache = Configs::cache(); if ($refresh || $cache === null || ($assigned = $cache->get($key)) === false) { $routes = $filter1 = $filter2 = []; if ($userId !== null) { foreach ($manager->getPermissionsByUser($userId) as $name => $value) { if ($name[0] === '/') { if (substr($name, -2) === '/*') { $name = substr($name, 0, -1); } $routes[] = $name; } } } foreach ($manager->defaultRoles as $role) { foreach ($manager->getPermissionsByRole($role) as $name => $value) { if ($name[0] === '/') { if (substr($name, -2) === '/*') { $name = substr($name, 0, -1); } $routes[] = $name; } } } $routes = array_unique($routes); sort($routes); $prefix = '\\'; foreach ($routes as $route) { if (strpos($route, $prefix) !== 0) { if (substr($route, -1) === '/') { $prefix = $route; $filter1[] = $route . '%'; } else { $filter2[] = $route; } } } $assigned = []; $query = Menu::find()->select(['id'])->asArray(); if (count($filter2)) { $assigned = $query->where(['route' => $filter2])->column(); } if (count($filter1)) { $query->where('route like :filter'); foreach ($filter1 as $filter) { $assigned = array_merge($assigned, $query->params([':filter' => $filter])->column()); } } $assigned = static::requiredParent($assigned, $menus); if ($cache !== null) { $cache->set($key, $assigned, 0, new TagDependency(['tags' => self::CACHE_TAG])); } } $key = [__METHOD__, $assigned, $root]; if ($refresh || $callback !== null || $cache === null || ($result = $cache->get($key)) === false) { $result = static::normalizeMenu($assigned, $menus, $callback, $root); if ($cache !== null && $callback === null) { $cache->set($key, $result, 0, new TagDependency(['tags' => self::CACHE_TAG])); } } return $result; }
<div class="menu-form"> <?php $form = ActiveForm::begin(['id' => 'menu-form', 'options' => ['enctype' => 'multipart/form-data', 'class' => 'form-horizontal'], 'enableClientValidation' => true, 'fieldConfig' => ['template' => "{label}\n<div class=\"col-lg-9\">{input}</div>\n<div class=\"col-lg-offset-3 col-lg-9\">{error}</div>", 'labelOptions' => ['class' => 'col-lg-3 control-label']]]); ?> <?php echo $form->field($model, 'name')->textInput(['maxlength' => 128]); ?> <?php echo $form->field($model, 'parent_name')->widget('yii\\jui\\AutoComplete', ['options' => ['class' => 'form-control'], 'clientOptions' => ['source' => Menu::find()->select(['name'])->column()]]); ?> <?php echo $form->field($model, 'route')->widget('yii\\jui\\AutoComplete', ['options' => ['class' => 'form-control'], 'clientOptions' => ['source' => Menu::getSavedRoutes()]]); ?> <?php echo $form->field($model, 'order')->input('number'); ?> <?php echo $form->field($model, 'data')->widget(\common\widgets\Iconpicker::className(), ['rows' => 6, 'columns' => 8, 'iconset' => 'fontawesome'])->label('请选择一个图标..'); ?> <div class="form-group"> <div class="col-lg-offset-3"> <?php echo Html::submitButton($model->isNewRecord ? Yii::t('rbac-admin', 'Create') : Yii::t('rbac-admin', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']); ?>
?> <?php echo $form->field($model, 'route')->textInput(['id' => 'route']); ?> <?php echo $form->field($model, 'order')->input('number'); ?> <?php echo $form->field($model, 'data')->textarea(['rows' => 4]); ?> <div class="form-group"> <?php echo Html::submitButton($model->isNewRecord ? Yii::t('rbac-admin', 'Create') : Yii::t('rbac-admin', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']); ?> </div> <?php ActiveForm::end(); ?> </div> <?php AutocompleteAsset::register($this); $options1 = Json::htmlEncode(['source' => Menu::find()->select(['name'])->column()]); $this->registerJs("\$('#parent_name').autocomplete({$options1});"); $options2 = Json::htmlEncode(['source' => Menu::getSavedRoutes()]); $this->registerJs("\$('#route').autocomplete({$options2});");
</div> <div class="col-md-6"> <?php echo $form->field($model, 'description')->textarea(['rows' => 4]); ?> <?php echo $form->field($model, 'link')->textInput(['maxlength' => true]); ?> <?php echo $form->field($model, 'icon')->textInput(['maxlength' => true]); ?> <?php echo $form->field($model, 'menu_group_id')->dropDownList(yii\helpers\ArrayHelper::map(\mdm\admin\models\Menu::find()->where("parent is null")->all(), 'id', 'name')); ?> </div> </div> <div class="row"> <div class="col-md-12"> <div class="form-group"> <?php echo Html::submitButton($model->isNewRecord ? Yii::t('backend', 'Create') : Yii::t('backend', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']); ?> </div> </div> </div> <?php ActiveForm::end();
<?php use yii\helpers\Html; use mdm\admin\models\Menu; /* @var $content string */ $menus = Menu::find()->where(['parent' => 8])->orderBy('order')->all(); $activeMenu = Yii::$app->controller->id; $this->beginContent('@backend/views/layouts/main.php'); ?> <div class="row"> <div class="col-md-3 col-sm-4"> <div class="list-group"> <?php foreach ($menus as $id => $menu) { $label1 = Yii::t('igolf', $menu->name); $label = '<i class="glyphicon glyphicon-chevron-right"></i>' . Html::encode($label1); echo Html::a($label1, Yii::$app->homeUrl . ltrim($menu->route, '/'), ['class' => strpos($menu->route, $activeMenu) > 0 ? 'list-group-item active' : 'list-group-item']); } ?> </div> </div> <div class="col-md-9 col-sm-8"> <?php echo $content; ?> </div> </div> <?php $this->endContent();
/** * Finds the Menu model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param integer $id * @return Menu the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Menu::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } }