1

I am using Yii2 gridview to load country, state,city. I have set search option for country, state, city using dropdown. How do I create dependent dropdown in filter?

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
         [
        'attribute' => 'country_id',
        'label' => 'Country',
        'filter' => Country::country(),
        'value' => function($data){
        return Country::countryname($data->country_id);
        }
         ],
        [

          'attribute' => 'state_id',
          'filter' => State::state(),
          'value' => function($data){
            return State::statename($data->state_id);
          }
        ],
         [

          'attribute' => 'city_id',
          'filter' => City::city(),
          'value' => function($data){
            return City::cityname($data->city_id);
          }
        ],

]); ?>
arogachev
  • 33,150
  • 7
  • 114
  • 117
JeevaRekha
  • 383
  • 1
  • 7
  • 21

4 Answers4

4

Since Filter Form in grid view changes send request onChange of form.. You can easily create a your filter list as

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
         [
        'attribute' => 'country_id',
        'label' => 'Country',
        'filter' => Country::country(),
        'value' => function($data){
        return Country::countryname($data->country_id);
        }
         ],
        [

          'attribute' => 'state_id',
          'filter' => State::state($searchModel->country), //Country Id/name from SearchModel --- you can add condition if isset($searchModel->country) then show else [] blank array
          'value' => function($data){
            return State::statename($data->state_id);
          }
        ],
         [

          'attribute' => 'city_id',
          'filter' => City::city($searchModel->state),   //Country Id/name from SearchModel --- you can add condition if 
          'value' => function($data){
            return City::cityname($data->city_id);
          }
        ],

]); ?>

As you have provided your own function in filter of state/city ,,, fetch array list of the behalf of setted value of $searchModel->state

In State Model

class State extends \yii\db\ActiveRecord{

  public static state($country){
    if($country){
        return ['state'];
    }else{
        return [];
    }
  }
}

Just same for city model

GAMITG
  • 3,810
  • 7
  • 32
  • 51
Double H
  • 4,120
  • 1
  • 15
  • 26
0

If $searchModel is an object of ModelSearch, in the view:

$this->registerJs( <<< EOT_JS

      $('#ModelSearch[state_id]').on('change', function(ev) {
            $.get(
                '<url>',
                { parameters }
                function(data) { 
                      // if data is an html response...
                      $('#ModelSearch[city_id]').html(data);
                }
            );
      }

EOT_JS
);
Fabrizio Caldarelli
  • 2,982
  • 11
  • 14
0

Here is Country State City Dependent Dropdown functionality where city is multiple choosen

Here is View

            <?php 
            echo $form->field($model, 'country_id')->dropDownList(
                $con,
                [
                    'prompt'=>'Select Country',
                    'labal'=>false,
                    'onchange'=>'
                        $.get( "'.Url::toRoute('/site/lists').'", { id: $(this).val() } )
                            .done(function( data ) {
                                $( "#'.Html::getInputId($model, 'state_id').'" ).html( data );
                            }
                        );
                    '    
                ]
        )->label('Country Name'); 



        // echo $form->field($model, 'state_id')->dropDownList(['prompt'=>'Select State']);



            echo $form->field($model, 'state_id')->dropDownList(
                $state,
                [
                    'prompt'=>'Select State',                    
                    'onchange'=>'
                        $.get( "'.Url::toRoute('/site/citi').'", { id: $(this).val() } )
                            .done(function( data ) {
                                $( "#'.Html::getInputId($model, 'citi_id').'" ).html( data );

                            }
                        );
                    '    
                ]
        )->label('State Name');



               echo $form->field($model, 'citi_id')->dropDownList(
                $state,
                [
                    'prompt'=>'Select City',
                    'multiple' => true,
                    'onchange'=>'
                        $.get( "'.Url::toRoute('/site/citi').'", { id: $(this).val() } )
                            .done(function( data ) {
                                $( "#'.Html::getInputId($model, 'citi_id').'" ).html( data );

                            }
                        );
                    '    
                ]
        )->label('City Name');

           // echo $form->field($model, 'citi_id')->dropDownList(['prompt'=>'Select City']);
            ?>

Here is Sitecontroller function

State Related to Country

public function actionLists($id)
{
    $model = new State();
    $rows = $model::find()->where(['country_id' => $id])->all();        
    $countPosts = $model::find(); 
    echo "<option>Select State</option>";

    if(count($rows)>0){
        foreach($rows as $row){
            echo "<option value='$row->id'>$row->name</option>";
        }
    }
    else{
        echo "<option>Select State</option>";
    }
}    

**City Related to State**

  public function actionCiti($id)

{
      //die('hello');
    $model = new Citi();
    $rows = $model::find()->where(['state_id' => $id])->all();        
    $countPosts = $model::find(); 
    echo "<option>Choose City</option>";

    if(count($rows)>0){
        foreach($rows as $row){
            echo "<option value='$row->id'>$row->name</option>";
        }
    }
    else{
        echo "<option>No City Available</option>";
    }
}
Ashish Pathak
  • 827
  • 8
  • 16
0

You can do it more and more simplier. E.g., I have theatre with spectacles, so my gridview is:

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        'id',
        [
            'attribute' => 'theatre_id',
            'value' => 'theatre.title',
            'header' => '',
            'filter' => Html::activeDropDownList($searchModel, 'theatre_id', ArrayHelper::map(Theatre::find()->asArray()->all(), 'id', 'title'),['class'=>'form-control','prompt' => 'Select theatre']),
        ],
        [
            'attribute' => 'spectacle_id',
            'value' => 'spectacle.title',
            'header' => '',
            'filter' => Html::activeDropDownList(
                $searchModel,
                'spectacle_id',
                ((empty($searchModel->theatre_id))?
                    ArrayHelper::map(Spectacle::find()->asArray()->all(), 'id', 'title'):
                    ArrayHelper::map(Spectacle::find()->where(['theatre_id' => $searchModel->theatre_id])->asArray()->all(), 'id', 'title')),
                ['class'=>'form-control','prompt' => 'Select spectacle']),
        ]...

When I'm selecting theatre I have dropdown with spectacles from this theatre only. When theatre is not selected, I have all possible spectacles from all theatres.

slashka
  • 99
  • 2
  • 8