phpyii2yii2-advanced-appyii2-validation

Yii2 GridView search dependent dropdown


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);
          }
        ],

]); ?>

Solution

  • 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