Yii2页面PHP控件中输出JS代码

Yii 2中的很多页面控件,是直接封装了现有的JS控件的,这些JS控件的基础数据类型的属性配置还比较简单,基本上在PHP中转换一下就可以直接设置了,但是对于属性值为函数的,就不能简单的传递一个字符串了,因为到了JS端并没有将字符串转换为脚本,因此需要特别处理,下面以给Kartik Select2控件增加自定义查询过滤为例,示范如何进行处理:
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脚本的转换:

<?=
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')
                ],
            ],
        ],
    ],
]);
?>

注意:

1.变量$customFilter保存的是JS脚本,registerJs()使用该变量将JS脚本输出到页面;

2.在配置select2控件的属性时,要使用JsExpression()将字符串转换为JS脚本输出到页面;

转载于:https://www.cnblogs.com/tywali/p/7766287.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值