依赖下拉yii2。怎么做?

时间:2014-05-30 09:43:54

标签: yii2

我可以在yii2中创建一个依赖的下拉列表吗?

我有两张桌子:

'id','name_country"
'id','name_city','country_id'

在我的模型中有两种方法:

public function getCountryList()
{
$models = NetCountry::find()->asArray()->all();
return ArrayHelper::map($models, 'id', 'country_name');
} 

public function getCityList($parent_id) { 
$models = \common\models\City::find()->where(['parent_id' => $country_id])->asArray()->all();
return ArrayHelper::map($models, 'id', 'name_city','country_id');
}

我有第一个字段:

 <?= $form->field($model, 'country')->dropDownList($model->countryList),['id'=>'parent_id'];

和第二个

<?= $form->field($model, 'city')->dropDownList($model->cityList);

我需要'传递'parent_id到控制器并通过AJAX(使用JSON)返回city_list

我该怎么做?我看到了an example in Yii1,但Yii2呢?

4 个答案:

答案 0 :(得分:5)

使用krajee扩展名进行依赖下拉

详情请见Krejee dependent dropdown for yii2

或按照以下说明操作:

通过composer安装扩展程序:

 $ php composer.phar require kartik-v/dependent-dropdown "dev-master"

在您看来:

  use kartik\widgets\DepDrop;

// Normal parent select
echo $form->field($model, 'cat')->dropDownList($catList, ['id' => 'cat-id']);

// Dependent Dropdown
echo $form->field($model, 'subcat')->widget(DepDrop::classname(), [
    'options' => ['id' => 'subcat-id'],
    'pluginOptions' => [
        'depends' => ['cat-id'],
        'placeholder' => 'Select...',
        'url' => Url::to(['/site/subcat'])
    ]
]);

//控制器

public function actionSubcat() {
$out = [];
if (isset($_POST['depdrop_parents'])) {
$parents = $_POST['depdrop_parents'];
if ($parents != null) {
$cat_id = $parents[0];
$out = self::getSubCatList($cat_id);
// the getSubCatList function will query the database based on the
// cat_id and return an array like below:
// [
// ['id'=>'<sub-cat-id-1>', 'name'=>'<sub-cat-name1>'],
// ['id'=>'<sub-cat_id_2>', 'name'=>'<sub-cat-name2>']
// ]
echo Json::encode(['output'=>$out, 'selected'=>'']);
return;
}
}
echo Json::encode(['output'=>'', 'selected'=>'']);
}

答案 1 :(得分:5)

在不使用任何第三方库的情况下在yii2中创建依赖下拉列表 就像yii1一样简单。您必须根据您的要求尝试以下编写的代码。   使用gii为各个表创建模型,视图和控制器。

假设你写了两个像国家,城市一样的表格。  然后将以下代码写入一个控制器(如国家/地区)的视图文件中:

         <?php
                    use yii\helpers\ArrayHelper;
                    use yii\widgets\ActiveForm;
                    ?>
               <div>
            <?php
     $dataCountry=ArrayHelper::map(\app\models\Country::find()->
     asArray()->all(),'id', 'name');    
                  $form = ActiveForm::begin();
                echo $form->field($model, 'id')->dropDownList($dataCountry, 
                                     ['prompt'=>'-Choose a Name-',
                                         'class'=>'adjust',
                          'onchange'=>'
             $.post("'.Yii::$app->urlManager->createUrl('city/lists?id=').
           '"+$(this).val(),function( data ) 
                   {
                              $( "select#city" ).html( data );
                            });
                        ']); 

                $dataPost=ArrayHelper::map(\app\models\City::find()->
                 asArray()->all(), 'id', 'city');
              echo $form->field($model, 'id')
                    ->dropDownList(
                        $dataPost,   
                         ['id'=>'city',
                             'class'=>'adjust'
                             ]
                    );
                 ActiveForm::end(); 
               ?>
            </div>

之后在另一个城市控制器中写下以下代码:

 <?php

namespace app\controllers;

class CityController extends \yii\web\Controller
{
        public function actionLists($id)
      {
         //echo "<pre>";print_r($id);die;
         $countPosts = \app\models\City::find()
         ->where(['country_id' => $id])
         ->count();

         $posts = \app\models\City::find()
         ->where(['country_id' => $id])
         ->orderBy('id DESC')
         ->all();

         if($countPosts>0){
         foreach($posts as $post){

         echo "<option value='".$post->id."'>".$post->city."</option>";
         }
         }
         else{
         echo "<option>-</option>";
         }

 }
}

然后进入url它有效!

编辑:固定网址构建。 http请求现在可以正常工作。

答案 2 :(得分:0)

上述代码无法正常运行。行

中有错误
$.post("'.Yii::$app->urlManager->createUrl('city/lists&id=').'"+$(this).val(),function( data ) 

控制台显示错误: 未找到(#404):无法解析请求:subcategory / lists&amp; id = 54

有没有解决方案 我的控制器如下所示

public function actionLists($id)
      {
         $posts = SubCategory::find()
         ->where(['category_id' => $id])
         ->orderBy('id DESC')
         ->all();

         if($posts){
         foreach($posts as $post){

         echo "<option value='".$post->id."'>".$post->name."</option>";
         }
         }
         else{
         echo "<option>-</option>";
         }

    }

当我从网址中删除id并将其硬编码到控制器时,它可以正常工作。

我找到了解决方案  请按以下方式更改您的观点

 <?= $form->field($model, 'category_id')->dropDownList($data,['prompt'=>'-Choose a Category-',

                                                            'onchange'=>'
             $.get( "'.Url::toRoute('product/catlists').'", { id: $(this).val() } )
                            .done(function( data )
                   {
                              $( "select#product-sub_categoryid" ).html( data );
                            });
                        ']); ?> 

和像这样的控制器

public function actionCatlists($id)
    {
        $mymodel = new Product ();
        $size = $mymodel->modelGetCategory ( 'product_sub_category',$id );
        if($size){
            echo '<option value="">Choose Sub category</option>';
            foreach($size as $post){
                echo "<option value='".$post['id']."'>".$post['name']."</option>";
            }
        }
        else{
            echo '<option value="0">Not Specified</option>';
        }

    }

请勿忘记将此信息包含在您的视图中

use yii\helpers\Url;

答案 3 :(得分:0)

您可以手动执行此操作而无需任何小部件:

使您的活动表单如下:

<?=  $form->field($model, 'nameofyourmodel')->dropDownList(
    ArrayHelper::map(\app\models\nameofyourmodel::find()->all(), 'id', 'name'),
    [
        'prompt'=>'smth',
        'onchange' => '
            $.post(
                "' . Url::toRoute('getoperations') . '", 
                {id: $(this).val()}, 
                function(res){
                    $("#requester").html(res);
                }
            );
        ',

    ]
); ?>

这里是从第一个模型接收ID的第二种形式:

 <?= $form->field($model,'nameofyourmodel')->dropDownList(
    [],
    [
        'prompt' => 'smth',
        'id' => 'requester'
    ]
); ?>

最后一个操作是在控制器中创建一个功能以匹配2个id并将其发送到您的模型:

public function actionGetoperations()
{
    if ($id = Yii::$app->request->post('id')) {
        $operationPosts = \app\models\firstmodel::find()
            ->where(['id' => $id])
            ->count();

        if ($operationPosts > 0) {
            $operations = \app\models\secondmodel::find()
                ->where(['firstmodelid' => $id])
                ->all();
            foreach ($operations as $operation)
                echo "<option value='" . $operation->firstmodelid. "'>" . $operation->name . "</option>";
        } else
            echo "<option>-</option>";

    }
}
相关问题