Yii2頁面PHP控件中輸出JS代碼

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腳本輸出到頁面;字符串

相關文章
相關標籤/搜索