【问题标题】:Select2 and Ajax loading, search but I can't choose result in Yii2 frameworkSelect2 和 Ajax 加载,搜索但我无法在 Yii2 框架中选择结果
【发布时间】:2016-06-04 05:14:52
【问题描述】:

我正在使用:Select2 和 Ajax 从教程加载:http://demos.krajee.com/widget-details/select2#usage-ajax

我有一个问题,脚本有效,但我无法选择值。我可以搜索,但我想从结果中进行选择。我点击一个,没有任何反应,没有输入值。

表格:

<?= $form->field($model, 'top_surname_surname_id')->widget(Select2::classname(), [
    'initValueText' => $cityDesc, // set the initial display text
    'options' => ['placeholder' => 'Wpisz nazwisko'],
    'pluginOptions' => [
        'allowClear' => true,
        'minimumInputLength' => 3,
        'ajax' => [
            'url' => $url,
            'dataType' => 'json',
            'data' => new JsExpression('function(params) { return {q:params.term}; }')
        ],
        'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
        'templateResult' => new JsExpression('function(top_surname_surname_id) { return top_surname_surname_id.text; }'),
        'templateSelection' => new JsExpression('function (top_surname_surname_id) { return top_surname_surname_id.text; }'),
    ],
]);?>

控制器:

public function actionSurnamelist($q = null, $id = null) {
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $out = ['results' => ['id' => '', 'text' => '']];
    if (!is_null($q)) {
        $query = new Query;
        $query->select('surname_id, surname_name AS text')
            ->from('surname')
            ->where(['like', 'surname_name', $q])
            ->limit(20);
        $command = $query->createCommand();
        $data = $command->queryAll();
        $out['results'] = array_values($data);
    }
    elseif ($id > 0) {
        $out['results'] = ['id' => $id, 'text' => Surname::find($id)->surname_name];
    }
    return $out;
}

问题出在这一行:

$query->select('surname_id, surname_name AS text')
    ->from('surname')
    ->where(['like', 'surname_name', $q])
    ->limit(20);

工作,然后我将代码编辑为:

$query->select('surname_id AS id, surname_name AS text')
    ->from('surname')
    ->where(['like', 'surname_name', $q])
    ->limit(20);

【问题讨论】:

    标签: ajax yii2 select2


    【解决方案1】:

    如果我理解正确的话。你的结果应该是这样的

    $out['results'] = [
        'id' => your_id,
        'text' => some text,
    ];
    

    但是如果您看到您的 if 条件,则您选择 surname_idid 不同,因此请使用别名或使用 foreach 循环到您的 $data 例如

    foreach($data as $key=>$value){
        $out['results'] = [
            'id' => $value->surname_id,
            'text' => $value->text,
        ]; 
    }
    

    希望这会对你有所帮助。

    【讨论】:

    • 感谢您的回答。我在我的代码中发现了问题。我用好的代码编辑了我的第一篇文章。谢谢。
    【解决方案2】:

    问题是将选择重定向到字段的 id。

    【讨论】:

      猜你喜欢
      • 2013-04-02
      • 2015-10-15
      • 1970-01-01
      • 2019-07-13
      • 1970-01-01
      • 2016-11-09
      • 1970-01-01
      • 2014-10-09
      • 1970-01-01
      相关资源
      最近更新 更多