Yii 2中的不少页面控件,是直接封装了现有的JS控件的,这些JS控件的基础数据类型的属性配置还比较简单,基本上在PHP中转换一下就能够直接设置了,可是对于属性值为函数的,就不能简单的传递一个字符串了,由于到了JS端并无将字符串转换为脚本,所以须要特别处理,下面以给Kartik Select2控件增长自定义查询过滤为例,示范如何进行处理:ide
1.首先,注册自定义查询的JS代码:函数
$customFilter = << < SCRIPT function matchCustom(params, data) { // If there are no search terms, return all of the data if ($.trim(params.term) === '') { return data; } // Do not display the item if there is no 'text' property if (typeof data.text === 'undefined') { return null; } // `params.term` should be the term that is used for searching // `data.text` is the text that is displayed for the data object if (data.text.indexOf(params.term) > -1) { var modifiedData = $.extend({}, data, true); modifiedData.text += ' (matched)'; // You can return modified objects from here // This includes matching the `children` how you want in nested data sets return modifiedData; } // Return `null` if the term should not be displayed return null; } SCRIPT; $this - > registerJs($customFilter, View::_POS_HEAD_);
2.其次设置属性值为函数的属性,注意关键是使用“JsExpression()”实现字符串到JS脚本的转换:this
<?= GridView::widget([ 'export' => false, 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, // 自动生成搜索框 'filterPosition' => GridView::FILTER_POS_HEADER, 'summary' => '', 'columns' => [ //fid, fschoolid, fcourseid, fteacherid, fname, fremark [ 'attribute' => 'schoolname', 'headerOptions' => ['width' => '200', 'class' => 'text-center'], 'filterType' => GridView::FILTER_SELECT2, 'filter' => $shoolList, 'filterWidgetOptions' => [ 'options' => ['placeholder' => ''], 'pluginOptions' => [ 'allowClear' => true, 'matcher' => new JsExpression('matchCustom') ], ], ], ], ]); ?>
注意:code
1.变量$customFilter保存的是JS脚本,registerJs()使用该变量将JS脚本输出到页面;rem
2.在配置select2控件的属性时,要使用JsExpression()将字符串转换为JS脚本输出到页面;字符串