目录
3、选择用户,下拉多选(穿梭框)/ ActiveForm自定义下拉框
7、Bootstrap Select(select扩展及美化),ActiveForm一般用于form表单
9、ActiveForm Grid 添加操作按钮 (Grid自定义编辑和新增的layer框大小)
13、ActiveForm 美化radio组件 + 颜色选择
16、Grid 添加操作按钮2,需要confirm确认后执行
19、Grid 数据列表小部件,基于data-tables组件,水平滚动条,右侧内容超出隐藏,可滚动
22、echarts图表及API配置 + daterangepicker 小部件
use backend\widgets\switcher\SwitcherWidget;
- <?= $form->field($model, 'status',[
- "template" => "{label}\n<div class='col-md-6'>{input}</div>\n{hint}\n{error}"
- ])->widget(SwitcherWidget::className(), [
- "options" => [
- "data-color" => "#3aa99e", // 颜色
- "data-size" =>"large" ,// 大小,large / small
- "data-on" => $model::STATUS_ACTIVE, //原本默认应该是1,这里是10
- "data-off" => $model::STATUS_INACTIVE, //原本默认应该是0,这里是9
- ]
- ]) ?>
紫色(默认) #526069灰色 #3aa99e绿色 #f2a654橙色 #f96868红色 #926dde深紫色
GridView 使用开关按钮:
- <?= GridView::widget([
- 'id' => 'article-grid',
- 'dataProvider' => $dataProvider,
- 'filterModel' => $searchModel,
- 'columns' => [
- ['class' => 'yii\grid\SerialColumn'],
- 'id',
- [
- 'class' => 'backend\widgets\grid\SwitcherColumn',
- 'attribute' => 'is_top'
- ],
- [
- 'class' => 'backend\widgets\grid\SwitcherColumn',
- 'attribute' => 'status'
- ],
- ...
也可以自定义启用的value和未启用的value,默认是1和0
- [
- 'class' => 'backend\widgets\grid\SwitcherColumn',
- 'attribute' => 'status',
- 'options' => [
- "data-color" => "#3aa99e", // 颜色
- "data-on" => User::STATUS_ACTIVE, //原本默认应该是1,这里是10
- "data-off" => User::STATUS_INACTIVE, //原本默认应该是0,这里是9
- ]
- ],
如果是GridView使用开关按钮,需要在控制器中:
- public function actions()
- {
- return [
- 'switcher' => [
- 'class' => 'backend\widgets\grid\SwitcherAction'
- ]
- ];
- }
同时将findModel的属性改为public
ActiveForm使用按钮
- <?= $form->field($model, 'is_top')->switcher() ?>
- <?= $form->field($model, 'is_top')->switcher([
- "options" => [
- "data-color" => "#3aa99e",
- "data-size" => "small"
- ]
- ]) ?>
单独使用:
- <?= SwitcherWidget::widget([
- "name" => "org_if_current_inspection",
- "value" => $vv->org_if_current_inspection,
- "options" => [
- "class" => "js-switch org-list-switch",
- "data-color" => "#3aa99e", // 颜色
- "data-size" => "small",
- "data-url" => Url::to(["switcher"]),
- "data-params" => [
- "id" => $vv->id,
- "attribute" => "org_if_current_inspection"
- ]
- ]
- ]) ?>
加change事件:
- $('.js-switch').on('change', function () {
- var url = $(this).data("url");
- var reload = false; //修改后是否刷新页面,否
- var on = 1;
- var off = 0;
- var checked = $(this).is(':checked') ? on : off;
- var data = $(this).data("params");
- data.value = checked;
- console.log(data);
- $.post(url, data, function (response) {
- if (response.code != 200) {
- $.modal.error(response.message);
- return;
- }
- $.modal.alert(response.message);
- // 刷新组织信息即可
- $.pjax.reload({container: orgContainerName, timeout: 0});
- });
- });
如果有未来元素,把on change事件改为:
- $(document).on('change','.js-switch',function(){
- <?= $form->field($moduleModel, 'avatar')->widget(\common\modules\attachment\widgets\SingleWidget::className(), [
- 'onlyUrl' => true
- ]) ?>
onlyUrl 表示仅需要url链接
- <?= $form->field($model, 'title', [
- 'template' => '{label}<div class="col-md-10">{input}</div>',
- 'labelOptions' => ['class' => 'col-md-2 col-form-label text-right'],
- ])->widget(\backend\widgets\multiselect\MultiSelectWidget::className(), [
- 'data' => [
- "选项1",
- "选项2",
- "选项3",
- "选项4",
- "选项5",
- "选项6",
- "选项7",
- "选项8",
- ]
- ]) ?>
use backend\widgets\multiselect\MultiSelectWidget;
- <?php echo $form->field($model, 'userids')->widget(MultiSelectWidget::className(), [
- 'data' => User::getListDropDownList(),
- 'options' => [
- 'name' => 'abccc',
- 'value' => explode(",", $model->userids)
- ]
- ]) ?>
- <?php
- echo \backend\widgets\multiselect\MultiSelectWidget::widget([
- 'name' => 'choose-user',
- 'value' => [0, 1],
- 'data' => [
- "选项1",
- "选项2",
- "选项3",
- "选项4",
- "选项5",
- "选项6",
- "选项7",
- "选项8",
- ],
- ])
- ?>
如果是model下,那么这个字段的规则,只能是safe,否在提交的时候,无法捕捉到值
可以使用behavior:
- public function behaviors()
- {
- return [
- [
- 'class' => ChooseUserBehavior::className(), // 这里处理beforeSave时转为string
- 'chooseAttribute' => 'userids', //默认字段为username,重复可忽略
- ],
- ...
- ];
- }
也可以自己使用钩子函数写:
- public function beforeSave($insert)
- {
- parent::beforeSave($insert);
- if(is_array($this->fields)){
- $newItems = array_filter($this->fields, function ($item) {
- return !emptyempty($item);
- });
- $this->fields = implode(",",$newItems);
- }
- return true;
- }
自定义ActiveForm下拉选择框插件,在一行显示
- <?= $form->field($model, 'type')->dropDownListForPlugin($model::getTypeEnum(),['prompt' => '请选择11']) ?>
也可以使用
- <?=Html::customDropDownList($model,"project_id",\common\modules\project\models\Project::getDropDownList())?>
- <?= $form->field($model, 'avatar')->widget(\common\modules\attachment\widgets\SingleAndChooseWidget::className(), [
- 'chooseUrl' => '/attachment/default/choose-sing-pic', // 可以自主添加图片的跳转控制器,默认就是这个,可以自主加别的控制器来控制条件
- 'chooseArea' => ["80%","80%"],// 选择框的大小
- 'onlyUrl' => true
- ]) ?>
单独使用
- <?=SingleAndChooseWidget::widget([
- 'model' => $model,
- 'attribute' => 'qrcode',
- ])?>
多图上传:
model:
- use common\modules\attachment\behaviors\UploadBehavior;
- use common\traits\EntityTrait;
- class xxx extends \yii\db\ActiveRecord
- {
- use EntityTrait;
- public function rules()
- {
- return [
- [['files'],'safe'],
- ];
- }
- public function attributeLabels()
- {
- return [
- ...
- 'files' => '项目附件'
- ];
- }
- public function behaviors()
- {
- return [
- TimestampBehavior::className(),
- [
- 'class' => UploadBehavior::className(),
- 'attribute' => 'files',// 字段名,喜欢什么写什么,不要中文就行,
- 'multiple' => true, // 是否多图,true为是,去掉这条为false,默认为false,单图上传
- 'entity' => __CLASS__
- ],
- ];
- }
使用:
- <?= $form->field($model, 'files', [
- 'template' => '{label}<div class="col-md-10">{input}</div>',
- 'labelOptions' => ['class' => 'col-md-2 col-form-label text-right'],
- ])->widget(\common\modules\attachment\widgets\MultipleAndChooseWidget::className(), [
- 'onlyImage' => false, // 是否只允许上传图片,默认true,为false表示支持上传文件
- ]) ?>
默认upload上传引擎从配置项获取,也可指定上传到本地
- <?= $form->field($model, 'files', [
- 'template' => '{label}<div class="col-md-10">{input}</div>',
- 'labelOptions' => ['class' => 'col-md-2 col-form-label text-right'],
- ])->widget(\common\modules\attachment\widgets\MultipleAndChooseWidget::className(), [
- 'onlyImage' => false, // 是否只允许上传图片,默认true,为false表示支持上传文件
- "url" => ["/upload/file-upload-local"] // local上传到本地,可以看一下配置文件有哪些参数
- ]) ?>
视图文件采用GridView的写法:
- [
- "label" => "排序",
- "value" => function ($model) {
- return Html::sort($model->sort,[
- "data" => [
- "id"=>$model->classid,//需要改变的主键ID
- "name" => "sort", // 需要改变的字段名,默认就是sort
- "url" => Url::to(["change-sort"]) //ajax动态改变值的url
- ],
- ]);
- },
- "format" => "raw",
- 'headerOptions' => ['style' => 'width:80px'],
- ],
2020.8.16支持callback,callback支持js方法名,也支持string,直接执行
- return Html::sort($model->sort, [
- "data" => [
- "id" => $model->id,//需要改变的主键ID
- "name" => "sort", // 需要改变的字段名,默认就是sort
- "url" => Url::to(["/organization-member/change-sort"]), //ajax动态改变值的url
- "callback" => "pjaxRefresh()"
- ],
- ]);
控制器添加:
- public function actions()
- {
- return [
- 'change-sort' => [
- 'class' => 'backend\\actions\\AjaxUpdateFieldAction',
- ], // change-sort与上面的url一致
- ];
- }
控制器最后一个方法findModel给public
用到的视图页面需要改:
- <div class="page-main">
- <?php Pjax::begin(['id' => 'container-organization']) ?>
- </div>
- <?php Pjax::end() ?>
- </div>
- <?php $this->beginBlock('js') ?>
- <script>
- var containerName = "#container-organization";
- // pjax刷新
- function pjaxRefresh() {
- $.modal.close(); //关闭弹窗
- $.pjax.reload({container: containerName, timeout: 0});
- }
- </script>
- <?php $this->endBlock() ?>
- <?= $form->field($model, 'created_at')->widget(\backend\widgets\timepicker\TimePickerWidget::className(), [
- 'options' => [
- "data-min-time" => "上午9:00",
- "data-max-time" => "下午2:30",
- "data-show-duration" => "true"
- ]
- ]) ?>
7、Bootstrap Select(select扩展及美化),一般用于form表单
- <?= $form->field($model, 'group_id')->dropDownList($model::getGroupEnum(),['encode' => false, 'prompt' => '请选择','data-plugin'=>'selectpicker', 'data-style' => 'btn-select']) ?>
加一个属性:"data-live-search"=>"true"
- <?= $form->field($model, 'leader')->dropDownList(common\modules\user\models\User::getListDropDownList(), ['encode' => false, 'prompt' => '请选择', 'data-plugin' => 'selectpicker',‘data-live-search’=>‘true’]) ?>
加一个属性:"multiple"=>true
- <?= $form->field($model, 'role')->dropDownList($roleList, ['encode' => false, 'prompt' => '请选择', 'data-plugin' => 'selectpicker', 'data-live-search' => 'true','multiple'=>true]) ?>
可以通过 data-style 属性改变其样式
btn-outline btn-primary
btn-outline btn-info
btn-outline btn-success
btn-outline btn-warning
btn-outline btn-danger
- <?= $form->field($model, 'role')->dropDownList($roleList, ['encode' => false, 'prompt' => '请选择', 'data-plugin' => 'selectpicker', 'data-live-search' => 'true','multiple'=>true,'data-style'=>'btn-outline btn-primary']) ?>
- <?= $form->field($model, 'role')->dropDownList($roleList, ['encode' => false, 'prompt' => '请选择', 'data-plugin' => 'selectpicker', 'data-live-search' => 'true','multiple'=>true,'data-style'=>'btn-outline btn-info']) ?>
- <?= $form->field($model, 'role')->dropDownList($roleList, ['encode' => false, 'prompt' => '请选择', 'data-plugin' => 'selectpicker', 'data-live-search' => 'true','multiple'=>true,'data-style'=>'btn-outline btn-success']) ?>
- <?= $form->field($model, 'role')->dropDownList($roleList, ['encode' => false, 'prompt' => '请选择', 'data-plugin' => 'selectpicker', 'data-live-search' => 'true','multiple'=>true,'data-style'=>'btn-outline btn-warning']) ?>
- <?= $form->field($model, 'role')->dropDownList($roleList, ['encode' => false, 'prompt' => '请选择', 'data-plugin' => 'selectpicker', 'data-live-search' => 'true','multiple'=>true,'data-style'=>'btn-outline btn-danger']) ?>
没有选中任何项,这里不做placeholder,用作title,如:
- <?= $form->field($model, 'role')->dropDownList($roleList, [
- 'encode' => false,
- 'prompt' => '请选择',
- 'data-plugin' => 'selectpicker',
- 'multiple'=>true,
- 'title' => '请选择角色',
- ]) ?>
可以通过 data-selected-text-format 属性指定选中项如何显示
- <?= $form->field($model, 'role')->dropDownList($roleList, [
- 'encode' => false,
- 'prompt' => '请选择',
- 'data-plugin' => 'selectpicker',
- 'multiple'=>true,
- 'data-selected-text-format'=>'count'
- ]) ?>
- <?= $form->field($model, 'role')->dropDownList($roleList, [
- 'encode' => false,
- 'prompt' => '请选择',
- 'data-plugin' => 'selectpicker',
- 'multiple'=>true,
- 'data-selected-text-format'=>'count>2'
- ]) ?>
8、select2组件,搜索比下拉更智能,支持过滤过隐藏不必要的选项:
- <?= $form->field($model, 'org_id')->widget(\backend\widgets\select2\Select2Widget::className(), [
- "options" => [],
- "data" => [
- "选项1",
- "选项2",
- "选项3",
- "选项4",
- "选项5",
- "选项6",
- "选项7",
- "选项8"
- ]
- ]) ?>
options => 常规选项
data => 下拉选择项
pluginOptions => select2插件选项,用于初始化select2时填充参数
pluginOptions["allowClear"] = true 支持插件删除当前选择项
select2单选,添加placeholder:
- <?= $form->field($model, 'classurl')->widget(Select2Widget::className(), [
- "data" => $selectRoutes,
- 'options' => [
- 'placeholder' => '请选择'
- ],
- ]) ?>
分组显示:
- <?= $form->field($model, 'org_id')->widget(\backend\widgets\select2\Select2Widget::className(), [
- "options" => [],
- "data" => [
- '一级菜单的名称' => [
- 1 => "我是1",
- 2 => "这是2",
- ],
- '二级菜单的名称' => [
- 1 => "这是3",
- 2 => "这是5",
- ],
- ]
- ]) ?>
分组显示 + 多选
- <?= $form->field($model, 'org_id')->widget(\backend\widgets\select2\Select2Widget::className(), [
- "options" => [
- "multiple" => true
- ],
- "data" => [
- '一级菜单的名称' => [
- 1 => "我是1",
- 2 => "这是2",
- ],
- '二级菜单的名称' => [
- 1 => "这是3",
- 2 => "这是5",
- ],
- ]
- ]) ?>
在外层添加一层class,改变tag颜色,支持
.select2-primary
.select2-success
.select2-info
.select2-waring
.select2-danger 来改变其颜色
- <?= $form->field($model, 'org_id',[
- "options"=>[
- "class"=>"form-group row select2-primary"
- ]
- ])->widget(\backend\widgets\select2\Select2Widget::className(), [
- "options" => [
- "multiple" => true,
- ],
- "data" => [
- '一级菜单的名称' => [
- 1 => "我是1",
- 2 => "这是2",
- ],
- '二级菜单的名称' => [
- 1 => "这是3",
- 2 => "这是5",
- ],
- ]
- ]) ?>
select2支持多选以及自定义输入,可以参考一下common/modules/document/backend/views/document/_form.php
- <!-- 'pluginOptions' => ['tags'=>true] 表示 如果没有当前TAG,则输入的文字为TAG值 -->
- <?= $form->field($model, TagBehavior::$formName, [
- "options" => [
- "class" => "form-group row select2-primary"
- ]
- ])->label(TagBehavior::$formLable)->widget(TagsInput::className(), [
- "pluginOptions" => [
- 'tags' => true,
- 'placeholder' => '标签 ...',
- 'maximumInputLength' => 10
- ],
- "options" => [
- 'multiple' => true,
- ]
- ]) ?>
自定义select2组件的input name,value,或其它属性等,ID轻易不要自定义,以防如果当前页面有多个同样的组件时,ID重复:
- <?php
- echo \backend\widgets\select2\Select2Widget::widget([
- 'id' => 'abc',
- 'name' => $provinceName,
- 'value' => $provinceDefault,
- 'options' => [
- 'class' => 'province'
- ]
- ])
- ?>
- [
- 'class' => 'backend\widgets\grid\ActionColumnLayer',
- 'template' => '{create} {view} {update} {delete}',
- 'buttons' => [
- 'create' => function ($url, $model, $key) {
- return Html::createLayer(['create', 'id' => $model->id], '<span class="icon wb-plus"></span>', ['class' => 'btn btn-sm btn-flat', 'data-toggle' => 'tooltip', 'title' => '添加子分类']);
- }
- ]
- ],
同时修改layer的宽和高
- [
- 'class' => 'backend\widgets\grid\ActionColumnLayer',
- 'template' => '{create} {view} {update} {delete}',
- 'buttons' => [
- 'create' => function ($url, $model, $key) {
- return Html::createLayer(['create', 'parent_id' => $model->schedule_id], '添加', ['data' => ['width' => '80%', 'height' => '80%'],'class'=>'btn btn-info btn-xs']);
- },
- 'update' => function ($url, $model, $key) {
- return Html::createLayer($url, '<span class="icon wb-edit"></span>', ['data' => ['width' => '80%', 'height' => '80%']]);
- }
- ]
- ],
- use backend\widgets\ActiveForm;
- <?= $form->field($model, 'module')->suffix(Html::a('管理内容模型', ['/document/document-module/index'], ['class' => 'btn btn-primary', 'target' => '_blank']), 'btn')->dropDownList(DocumentModule::getTypeEnum(), ['prompt' => '请选择']) ?>
- <?= $form->field($moduleModel, 'money')->append('<span class="input-group-text">元</span>') ?>
点击弹出layer框的按钮,data-width控制layer的宽度(默认为800px),data-height控制layer的高度(默认为520px)
- <?= Html::a('<i class="icon fa-plus" aria-hidden="true"></i> 添加项目', ['create'], ['class' => 'btn btn-inverse btn-round', 'data-ajax' => '1', 'data-target' => '_blank', 'data-title' => '新增','data-width'=>'80%','data-height'=>'90%']) ?>
在Grid的列表中,点击编辑的时候同样需要将layer框放大
- [
- 'class' => 'backend\widgets\grid\ActionColumnLayer',
- 'template' => '{update} {delete}',
- 'buttons' => [
- 'update' => function ($url, $model, $key) {
- return Html::createLayer(['create', 'id' => $model->id], '<span class="icon wb-edit"></span>', ['data'=>['width'=>'80%','height'=>'500px']]);
- }
- ]
- ],
- use backend\widgets\ActiveForm;
- <?= $form->boxField($model, 'meta', [
- "collapsed" => true, // true展开,false收起
- "template" => "<div class='panel'>{header}\n{body}\n{footer}</div>" //如果ActiveForm没有设置template的话,可忽略
- ])->widget(MetaForm::className())->header("SEO"); ?>
model中添加行为和获取
- public function behaviors()
- {
- return [
- TimestampBehavior::className(),
- [
- 'class' => MetaBehavior::className(),
- ],
- ];
- }
- /**
- * 获取分类的关键词、描述
- * @return array
- */
- public function getMetaData()
- {
- $model = $this->getMetaModel();
- $title = $model->title ? : $this->title;
- $keywords = $model->keywords;
- $description =$model->description ? : $this->description;
- return [$title, $keywords, $description];
- }
- use backend\widgets\ActiveForm;
- <?= $form->field($model, 'allow_publish')->inline()->radioList($model::getAllowPublishEnum())->label("发布") ?>
- <?= $form->field($model, 'allow_publish')->customInlineRadioList($model::getAllowPublishEnum())->label("发布") ?>
重写activeRadioList
- <?= Html::customInlineRadioList($model,'gender', [0=>"男",1=>"女"]) ?>
如果是自定义name和value,支持:
- <?= Html::customInlineRadioListNoActive("gender", 1, [0=>"男",1=>"女"]) ?>
- <?= $form->field($model, 'color')->customInlineColorList([
- "#3e8ef7"=>"primary",
- "#997b71" => "brown",
- "#0bb2d4" => "cyan",
- "#11c26d" => "green",
- "#757575" => "grey",
- "#667afa" => "indigo",
- "#eb6709" => "orange",
- "#f74584" => "pink",
- "#9463f7" => "purple",
- "#ff4c52" => "red",
- "#17b3a3" => "teal",
- "#ffcd17" => "yellow",
- ]) ?>
- <?= $form->field($model, 'executive')->customCheckboxList([1 => "开启"]) ?>
- <?= Html::customCheckboxList($model,'executive', [1 => "开启"]) ?>
上面同样适用于多个复选框,如果仅单个,可使用:
- <?= $form->field($model, 'executive')->customCheckbox() ?>
- <?= $form->field($model, 'amount')->append('<span class="input-group-text">万元</span>')->label("项目金额") ?>
16、Grid 添加操作按钮2,需要confirm确认后执行:
- [
- 'class' => '\backend\widgets\grid\ActionColumn',
- 'template' => '{update} {delete} {refresh}',
- 'buttons' => [
- 'delete' => function ($url, $model, $key) {
- return Html::createAjaxBtn($url, "<i class='icon wb-close'></i>", [
- "data-confirm" => "确定要删除吗?删除后可在回收站恢复",
- "data-method" => "post",
- 'data-toggle' => 'tooltip',
- 'data-original-title' => '删除'
- ]);
- },
- 'refresh' => function ($url, $model, $key) {
- return Html::createAjaxBtn($url,"刷新",['class' => 'btn btn-primary btn-xs']);
- },
- ]
- ],
- [
- 'class' => '\backend\widgets\grid\ActionColumn',
- 'template' => '{reduction} {delete}',
- 'buttons' => [
- 'reduction' => function ($url, $model) {
- return Html::createAjaxBtn(['reduction'], '还原', [
- "class" => "btn btn-success btn-xs",
- "data-method" => "post",
- "data-confirm" => "是否确认还原?",
- 'data-params' => ['id' => $model->id],
- ]);
- },
- 'delete' => function ($url, $model, $key) {
- return Html::createAjaxBtn(['hard-delete'], "清除", ['class' => 'btn btn-danger btn-xs',"data-confirm" => "确定要彻底删除吗?不可恢复!"]);
- }
- ]
- ],
- [
- 'class' => '\backend\widgets\grid\ActionColumn',
- 'template' => '{view} {update} {delete} {deleteAll}',
- 'buttons' => [
- 'view' => function ($url, $model) {
- return Html::tag("span", "查看", ["class" => "btn btn-primary btn-sm createTab", "title" => "查看" . $model->profile->true_name . "资料", "target" => "_blank", "data-url" => Url::to(["/organization-member/view", "user_id" => $model->user_id, "org_id" => $model->org_id])]);
- },
- 'update' => function ($url, $model, $key)use($rightOrg) {
- return Html::createLayer(["/organization-member/update", "user_id" => $model->user_id, "org_id" => Yii::$app->request->get("org_id"), 'parent_tree_init' => 1], "<span class='btn btn-info btn-sm'>编辑</span>", ["data-title" => "编辑【".$rightOrg->title."】成员【".$model->profile->true_name."】资料" ]);
- },
- 'delete' => function ($url, $model, $key) use ($org_id) {
- return Html::createAjaxBtn(["/organization-member/delete", "id" => $model->id], "<span class='btn btn-warning btn-sm'>删</span>", [
- "data-confirm" => "确定要删除吗?该操作仅删除此用户在当前组织的信息,基础资料与其他组织的关联关系不受影响",
- "data-method" => "post",
- 'data-toggle' => 'tooltip',
- 'data-original-title' => '删除当前关联关系',
- 'data-refresh-pjax-container' => 'container-organization'
- ]);
- },
- 'deleteAll' => function ($url, $model, $key) use ($org_id) {
- return Html::createAjaxBtn(["delete-member", "user_id" => $model->user_id, "org_id" => $org_id], "<i class='icon wb-close text-danger'></i>", [
- "data-confirm" => "确定要删除吗?该操作将会删除此用户全部资料,包括所在组织与基础资料,且不可恢复",
- "data-method" => "post",
- 'data-toggle' => 'tooltip',
- 'data-original-title' => '删除',
- 'data-refresh-pjax-container' => 'container-organization'
- ]);
- },
- ]
- ],
文档模块中,扩展model支持添加:
- public function behaviors()
- {
- return [
- [
- 'class' => UploadBehavior::className(),
- 'attribute' => 'attachment',
- 'entity' => __CLASS__
- ],
- [
- 'class' => DynamicFormBehavior::className(),
- 'formAttributes' => [
- 'attachment' => [
- 'type' => 'fileAndChoose',
- 'options' => ['widgetOptions' => ['onlyUrl' => false]]
- ],
- 'content' => [
- 'type' => 'multipleInput',
- 'items' => [
- "title" => "标题",
- "value" => "值",
- ],
- 'options' => [
- "max" => 20
- ]
- ],
- 'lng' => 'text',
- 'lat' => 'text',
- ]
- ]
- ];
- }
在options中添加额外的属性
- public function behaviors()
- {
- return [
- [
- 'class' => DynamicFormBehavior::className(),
- 'formAttributes' => [
- 'start_at' => [
- 'type' => 'datetime',
- 'options' => [
- 'style' => 'width:20px;',
- // 'widgetOptions' => [
- // 'style' => 'width:20px;'
- // ]
- ]
- ],
- //'start_at' => 'datetime',
- 'end_at' => 'datetime',
- 'city' => 'text',
- 'address' => 'text'
- ]
- ]
- ];
- }
- <?= $form->field($model, 'routers')->widget(\unclead\multipleinput\MultipleInput::className(),[
- 'max' => 4,
- 'iconSource' => 'fa',
- 'cloneButton' => true,
- 'allowEmptyList' => true,
- 'columns' => [
- [
- 'name' => 'user_id',
- 'type' => 'dropDownList',
- 'title' => 'User',
- 'defaultValue' => 1,
- 'items' => [
- 1 => 'User 1',
- 2 => 'User 2'
- ]
- ],
- [
- 'name' => 'day',
- 'type' => \kartik\date\DatePicker::class,
- 'title' => 'Day',
- 'value' => function($data) {
- return $data['day'];
- },
- 'items' => [
- '0' => 'Saturday',
- '1' => 'Monday'
- ],
- 'options' => [
- 'pluginOptions' => [
- 'format' => 'dd.mm.yyyy',
- 'todayHighlight' => true
- ]
- ]
- ],
- [
- 'name' => 'priority',
- 'title' => 'Priority',
- 'enableError' => true,
- 'options' => [
- 'class' => 'input-priority'
- ]
- ]
- ],
- ]) ?>
- <?php echo \backend\widgets\jstree\JstreeWidget::widget([
- "name" => "departmentJstree",
- "nodes" => \common\models\Organization::treeList(),
- "options" => [
- "id" => "departmentJstree"
- ]
- ]) ?>
格式固定,id,pid,title,options是选项
如果需要展开,需要加data-jstree = {opened:true}
如果需要选中,需要加data-jstree = {selected:true}
- /**
- * 返回组织机构的全部树结构
- * @return array
- */
- static function treeList(){
- $list = self::find()->select(['id', 'parent_id as pid', 'title'])->orderBy('sort asc,id asc')->asArray()->all();
- $list = self::find()->select(['id', 'parent_id as pid', 'title'])->orderBy('sort asc,id asc')->asArray()->all();
- $list = array_map(function ($item) use ($selected) {
- $item["options"] = [
- "data-jstree" => [
- 'icon' => 'fa-building-o',
- 'id' => $item["id"],
- 'parent_id' => $item["pid"]
- ]
- ];
- if ($item["parent_id"] == 0) {
- // 第一层展开
- $item["options"]["data-jstree"]["opened"] = true;
- }
- // 指定id高亮显示
- if ($item["id"] == $selected) {
- $item["options"]["data-jstree"]["selected"] = true;
- }
- return $item;
- }, $list);
- p(Json::encode($list));
- return Tree::build($list,"id","pid","children",0);
- }
- [
- {
- "id": "1",
- "pid": "0",
- "title": "南京xxx公司",
- "options": {
- "data-jstree": {
- "opened": true
- }
- }
- },
- {
- "id": "2",
- "pid": "1",
- "title": "技术部",
- "options": {
- "data-jstree": {
- "selected": true
- }
- }
- },
- {
- "id": "3",
- "pid": "1",
- "title": "财务部",
- "options": {
- "data-jstree": {
- "opened": true
- }
- }
- },
- {
- "id": "4",
- "pid": "1",
- "title": "业务部",
- "options": {
- "data-jstree": {
- "opened": true
- }
- }
- },
- {
- "id": "5",
- "pid": "1",
- "title": "总经办",
- "options": {
- "data-jstree": {
- "opened": true
- }
- }
- },
- {
- "id": "6",
- "pid": "1",
- "title": "营销中心",
- "options": {
- "data-jstree": {
- "opened": true
- }
- }
- },
- {
- "id": "7",
- "pid": "6",
- "title": "市场部",
- "options": {
- "data-jstree": {
- "opened": true
- }
- }
- },
- {
- "id": "8",
- "pid": "6",
- "title": "公关部",
- "options": {
- "data-jstree": {
- "opened": true
- }
- }
- },
- {
- "id": "9",
- "pid": "6",
- "title": "技术支持部",
- "options": {
- "data-jstree": {
- "opened": true
- }
- }
- }
- ]
需要添加自定义图标,则:
- {
- "id": "9",
- "pid": "6",
- "title": "技术支持部",
- "options": {
- "data-jstree": {
- "opened": true,
- "icon": "fa-building-o"
- }
- }
- }
添加点击事件:
- <?php $this->beginBlock('js') ?>
- <script>
- $('#departmentJstree').on("changed.jstree", function (e, data) {
- // if(data.selected.length) {
- console.log(data.instance.get_node(data.selected[0]).data.jstree);
- // console.log(data.instance.get_node(data.selected[0]).id);
- // alert('The selected node is: ' + data.instance.get_node(data.selected[0]).text);
- // }
- });
- </script>
- <?php $this->endBlock() ?>
添加右键菜单,plugin = "contextmenu"
- <?php echo \backend\widgets\jstree\JstreeContextmenuWidget::widget([
- "id" => "departmentJstree", //div的id命名,唯一值
- "dataUrl" => Url::to(["get-tree", "org_id" => $org_id]),// 源数据的ajax请求地址
- "create" => [
- "url" => Url::to(["create"]),// 创建的请求地址
- "label" => "添加组织机构",
- "area" => ["800px","520px"], // 新增的layer宽、高
- ],
- "update" => [
- "url" => Url::to(["update"]),
- "label" => "修改组织机构",
- "area" => ["800px","520px"], // 编辑的layer宽、高
- ],
- "delete" => [
- "url" => Url::to(["delete"]),
- "label" => "删除组织机构"
- ],
- "clickCallback" => "clickDepartmentHandle"
- ]) ?>
- v>
- <?php $this->beginBlock('js') ?>
- <script>
- var containerName = "#container-organization"; // 成员列表容器
- var orgId = 0;
- // 点击左侧菜单
- function clickDepartmentHandle(e,data) {
- if (data.selected.length) {
- //当前选中节点的Id--多选时只能得到第一个被选中的值
- var domId = data.instance.get_node(data.selected[0]).id;
- //当前选中节点的文本值-和上面方法一样只能的得到第一个被选中的值
- var value = data.instance.get_node(data.selected[0]).text;
- // console.log(domId,value);
- var url = "<?=Url::to(["index"])?>?org_id=" + domId;
- $.pjax.reload({url: url, container: containerName, timeout: 0});
- }
- }
- </script>
- <?php $this->endBlock() ?>
支持搜索框:
这里的id一定要是tree组件的id 加 _q,否则js无效
- <input type="text" class="form-control" id="departmentJstree_q" name="" placeholder="搜索部门">
- <?php echo \backend\widgets\jstree\JstreeContextmenuWidget::widget([
- "id" => "departmentJstree", //div的id命名,唯一值
- "dataUrl" => Url::to(["get-tree", "org_id" => $org_id]),// 源数据的ajax请求地址
- "create" => [
- "url" => Url::to(["create"]),// 创建的请求地址
- "label" => "添加部门",
- "area" => ["800px","520px"], // 新增的layer宽、高
- ],
- "update" => [
- "url" => Url::to(["update"]),
- "label" => "修改部门",
- "area" => ["800px","520px"], // 编辑的layer宽、高
- ],
- "delete" => [
- "url" => Url::to(["delete"]),
- "label" => "删除部门"
- ],
- "clickCallback" => "clickDepartmentHandle",
- "plugin" => ["contextmenu","search"], // 重点在这里,多添加一个search
- ]) ?>
19、基于data-tables组件,水平滚动条,右侧内容超出隐藏,可滚动
- use backend\widgets\grid\GridViewX;
- <?= GridViewX::widget([
- 'dataProvider' => $dataProvider,
- //'filterModel' => $searchModel,
- // 'id' => 'article-grid',
- // 'tableOptions' => [
- // 'class' => 'table table-hover dataTable table-striped w-full text-nowrap',
- // 'data-plugin' => 'dataTable',
- // 'data-scroll-x' => 'true',
- // 'data-responsive' => 'false',
- // 'style'=>'width:800px'
- // ],
- 'columns' => [
- ['class' => 'yii\grid\SerialColumn'],
- 'id',
- [
- 'attribute' => 'title',
- 'value' => function ($model) {
- return Html::a($model->title, Yii::$app->config->get('SITE_URL') . '/' . $model->id . '.html', ['target' => '_blank', 'no-iframe' => '1']);
- },
- 'format' => 'raw',
- 'enableSorting' => false
- ],
- 'category.title:text:分类',
- [
- 'label' => '标签',
- 'value' => function ($model) {
- $html = '';
- foreach ($model->tags as $tag) {
- $html .= ' <span class="badge badge-' . $tag->level . '">' . $tag->name . '</span>';
- }
- return $html;
- },
- 'format' => 'raw'
- ],
- 'trueView',
- [
- 'class' => 'backend\widgets\grid\SwitcherColumn',
- 'attribute' => 'is_top'
- ],
- [
- 'class' => 'backend\widgets\grid\SwitcherColumn',
- 'attribute' => 'status'
- ],
- 'profile.nickname:text:作者',
- [
- 'class' => '\backend\widgets\grid\ActionColumn',
- 'template' => '{update} {delete} {comment} {refresh}',
- 'buttons' => [
- 'update' => function ($url, $model, $key) {
- return Html::a("<i class='icon wb-edit'></i>",$url,["target"=>"_blank","data-title"=>"编辑"]);
- },
- 'delete' => function ($url, $model, $key) {
- return Html::createAjaxBtn($url, "<i class='icon wb-close'></i>", [
- "data-confirm" => "确定要删除吗?删除后可在回收站恢复",
- "data-method" => "post",
- // 'data-toggle' => 'tooltip',
- // 'data-original-title' => '删除'
- ]);
- },
- 'comment' => function ($url, $model, $key) {
- return Html::a("去评论", ["/comment/default/list", "module" => "document", "id" => $model->id], ['class' => 'btn btn-info btn-xs', 'target' => '_blank', 'data-title' => '评论']);
- },
- 'refresh' => function ($url, $model, $key) {
- return Html::createAjaxBtn($url, "刷新", ['class' => 'btn btn-primary btn-xs']);
- },
- ]
- ],
- ],
- ]); ?>
编辑和删除,在数量只有一两条的时候不能加tooltip,由于滚动条的缘故,会有闪现的现象,测试了一下,数量超过10条就正常了,可以加tooltip,也不会发生闪现的现象
- <?= $form->field($moduleModel, 'birthday')->widget(DatePicker::className(), [
- 'options' => [
- 'placeholder' => '输入出生年月',
- 'autocomplete' => 'off',
- ],
- 'pluginOptions' => [
- 'autoclose' => true,
- 'format' => 'yyyy-mm-dd',
- 'todayHighlight' => true
- ]
- ]) ?>
自定义name与value
- <?= \kartik\date\DatePicker::widget([
- "name" => "inspection_time",
- "value" => $vv->inspection_time,
- 'options' => [
- 'placeholder' => '输入年检日期',
- 'autocomplete' => 'off',
- 'class' => 'update-inspection-time',
- 'data-url' => Url::to(["update-inspection-time", "id" => $vv->id]),
- ],
- 'pluginOptions' => [
- 'autoclose' => true,
- 'format' => 'yyyy-mm-dd',
- 'todayHighlight' => true
- ]
- ]) ?>
可选的日期格式:
yyyy-mm-dd
yyyy-mm-dd hh:ii
yyyy-mm-dd hh:ii:ss
pluginOptions支持:
'startDate' =>date('Y-m-d'), //设置今天之前的日期不能选择
'startView'=>2, //其实范围(0:日 1:天 2:年)
'maxViewMode'=>2, //最大选择范围(年)
'minViewMode'=>2, //最小选择范围(年)
'todayHighlight' => true, // 今日高亮
'autoclose' => true, // 选择后自动关闭
'todayBtn' => true, // 今日按钮显示
可以添加callback回调:
- pluginEvents = [
- "show" => "function(e) { # `e` here contains the extra attributes }",
- "hide" => "function(e) { # `e` here contains the extra attributes }",
- "clearDate" => "function(e) { # `e` here contains the extra attributes }",
- "changeDate" => "function(e) { # `e` here contains the extra attributes }",
- "changeYear" => "function(e) { # `e` here contains the extra attributes }",
- "changeMonth" => "function(e) { # `e` here contains the extra attributes }",
- ];
例:
- "changeDate" => "function(e) { updateInspectionTime(e,this) }"
- <script>
- function updateInspectionTime(e,obj){
- var date = Date.parse(e.date); //毫秒级时间戳
- date = YYformatDate(date,"Y-m-d");
- var dom = e.target.getElementsByTagName("input")[0]; //第一个input,即输入框
- var url = dom.getAttribute("data-url"); //获取属性的data-url
- // console.log(date);
- // console.log(url);
- }
- </script>
- <?= $form->field($model, 'collectionTime')->widget(\kartik\datetime\DateTimePicker::class, [
- 'options' => [
- 'placeholder' => ''
- ],
- 'pluginOptions' => [
- 'autoclose' => true,
- 'todayHighlight' => true,
- 'format' => 'yyyy-mm-dd HH:ii:ss'
- ]
- ]) ?>
- <?= $form->field($model, 'content', ['template' => "{label}
- ss='col-md-6'>{input}</div>"])->widget(\backend\widgets\multitextarea\MultiTextareaWidget::class, [
- 'columns' => [
- [
- 'name' => 'field',
- 'options' => [
- 'class' => 'title'
- ]
- ],
- [
- 'name' => 'value',
- 'options' => [
- 'class' => 'form-control'
- ]
- ],
- ]
- ])->label("") ?>
单独使用:
- <?= \backend\widgets\multitextarea\MultiTextareaWidget::widget([
- "name" => "content",
- "columns" => [
- [
- "name" => "field"
- ],
- [
- "name" => "value"
- ]
- ],
- "value" => [
- [
- "field" => "待办任务",
- "value" => "标题12"
- ],
- [
- "field" => "需协调的任务",
- "value" => "任务xxx"
- ]
- ],
- ]) ?>
- <?= \common\widgets\echarts\Echarts::widget([
- 'config' => [
- 'server' => Url::to(['echarts']),
- 'height' => '315px'
- ]
- ]) ?>
路由返回的数据为:
code: "201"
data: {
fieldsName: ["test"]
seriesData: [{field: "price", name: "test", type: "line",…}]
xAxisData: ["00:00", "01:00", "02:00", "03:00", "04:00", "05:00", "06:00", "07:00", "08:00", "09:00", "10:00",…]
}
message: "ok"
- <?= \backend\widgets\daterangepicker\DateRangePickerWidget::widget([
- 'name' => 'queryDate-' . $boxId,
- 'value' => '',
- 'startAttribute' => 'start_time',
- 'endAttribute' => 'end_time',
- 'options' => [
- 'class' => 'form-control choose-picker-input',
- 'placeholder' => '开始时间 - 结束时间'
- ],
- 'pluginOptions' => [
- 'locale' => ['format' => 'YYYY-MM-DD'],
- // 'timePicker' => true, //显示时间
- // 'timePicker24Hour' => true, //时间制
- // 'timePickerSeconds' => true, //时间显示到秒
- ],
- 'pluginEvents' => [
- "apply.daterangepicker" => "function(ev, picker) {
- var startDate = picker.startDate.format('YYYY-MM-DD');
- var endDate = picker.endDate.format('YYYY-MM-DD');
- // 更新当前input的日期显示
- $(this).val(startDate +' - '+endDate);
- }",
- ],
- 'callback' => '
- var boxID = "'.$boxId.'";
- // 触发点击
- console.log("触发点击")
- let startDate = start.format(\'YYYY-MM-DD\');
- let endDate = end.format(\'YYYY-MM-DD\');
- $(\'#freedom-\' + boxID).attr(\'data-start\', startDate);// 更新按钮开始日期
- $(\'#freedom-\' + boxID).attr(\'data-end\', endDate);// 更新按钮结束日期
- // 触发点击
- $(\'#freedom-\' + boxID).trigger(\'click\');
- '
- ]) ?>
行政区划划代码:http://www.mca.gov.cn/article/sj/xzqh/1980/
- <?= backend\widgets\choose\ChooseRegionWidget::widget(
- [
- 'province' => [
- "name" => Html::getInputName($moduleModel, "province"),
- "value" => $moduleModel->province
- ],
- 'city' => [
- "name" => Html::getInputName($moduleModel, "city"),
- "value" => $moduleModel->city
- ],
- 'district' => [
- "name" => Html::getInputName($moduleModel, "district"),
- "value" => $moduleModel->district
- ],
- 'field' => 'area_name'
- ]
- ) ?>
参数说明:
province 省份
--name 生成的select的name名称,为了实现form表单的增改
--value 生成的select的默认选择项,实现默认选择项
city 城市
--name
--value
district 区/县
--name
--value
field 表单存储的值,如:
--id 地区唯一一ID,但是如果该项被删除,会影响较多数据(不建议)
--area_name 地区名称,数据比较清晰
--area_code 地区编号
小部件默认存储【地区名称】
label 默认是“选择地区”,支持自定义
showLable 默认是true,是否显示左侧的label,可以不显示