weixin_33674976 2018-07-07 09:16 采纳率: 0%
浏览 6

Yii用ajax下拉

So what I want to do is populate a dropdown in Yii framework with ajax using my database values in drop down. I using Kartik widget in it here is my dropdown code,

<?php $primaryfield = [1 => 'Business Development(Sales)', 2 => 'Graphic Design', 3 => 'Social Media Marketing', 4 => 'Web Development']; ?>

<?= $form->field($model, 'primaryfield')->widget(Select2::classname(), ['data' => $primaryfield, 
 'options' => ['placeholder' => 'Enter Your Primary Field', 'multiple' => false], 'pluginOptions' => ['tags' => false, 'tokenSeprators' => [',', ' '], 'maximumInputLength' => 20],])->label(false); ?>

I know everything about Ajax in PHP but don't know how to use it in Yii framework using Kartik widget I have all the primary fields value in my database but unfortunately, I am only able to display them in static basis not dynamic basis using ajax

  • 写回答

1条回答 默认 最新

  • weixin_33724046 2018-07-10 15:37
    关注

    If I get you clear, you want to have a drop-down list in which their items are dynamically generated by your database. This is the way you can achieve with kartik dropdown widget.

    I'll first create active form field which contains predefined categories as follows

    <?php $form = ActiveForm::begin(); 
       //Initialize predefined categories
       $data = [
          '1' => 'Business Development(Sales)',
          '2' => 'Graphic Design',
          '3' => 'Social Media Marketing',
          '4' => 'Web Development',
       ]; 
    ?>
    

    These field will prompt database to retrieve items for particular category via AJAX

    <?= $form->field($model, 'primaryfield')->widget(Select2::classname(), [
            'data' => $data,
            'options' => ['placeholder' => 'Enter your primary field'],
            'pluginOptions' => [
                //'allowClear' => true
            ],
            'pluginEvents' => [
                "change" => "function() { 
                    var id = $(this).val(); //extract the id of selected category   
    
                    $.ajax({
                        method : 'GET',
                        dataType : 'text',
                        url : '../yourcontroller/populate?id=' + id,
                        success : function (response) {
                            var response = JSON.parse(response);
                            var myDropDownList = document.getElementById(\"model-item\");
                            $.each(response, function(index, value) {
                                var option = document.createElement(\"option\");
                                    option.text = value;
                                    option.value = index;
    
                                   try {
                                        myDropDownList.options.add(option);
                                    }
                                    catch (e) {
                                        alert(e);
                                    }
                            });
                        }
                    });
                }",
            ],
        ]); 
    ?>
    <?= $form->field($model,'item')->dropdownList(
            ['prompt'=>'Select Item']
        );
    ?>
    

    Now create action in your controller that will query items from your database based on the category selected and return it to the Item field via ajax.

    <?php 
     public function actionPopulate($id)
     {
       // the id above is the one selected from the category field so you can use
       // that Id now to retrieve items from your item-field with ajax
       /* in you case */
       $results = Category::find()
                     ->select('items')
                     ->where(['id' => $id])
                     ->asArray()
                     ->all();
    
        //these hard-coded values are for the demonstration 
        $results = [
            '1'=>'maziwa', 
            '2'=>'ugali', 
            '3'=>'samaki', 
            '4'=>'kuku', 
            '5'=>'mtetea',
        ];
        return json_encode($results);
    }
    ?>
    

    Hope this helps!

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器