@Orbite

Как добавить новые данные в GridView yii2?

У меня на форме есть 2 связанных списка для выбора региона и городов и грид в котором находятся улицы городов. Как сделать чтобы при выборе города, улицы в гриде обновлялись на улицы по выбранному городу?

Вьюха:
<?php $form = ActiveForm::begin(['options' => ['class' => 'col_16 user_card_wrapper']]);?>
				<?= $form->field($form_model, 'reg')->dropDownList(
                  ArrayHelper::map(Region::find()->all(), 'reg_id', 'reg_name'),
                  [
                      'prompt' => 'Выберите регион',
                      'onchange' => '
                        $.post( "' . Yii::$app->urlManager->createUrl('/street/ajax?id=').'"+$(this).val(), function(data){
						  $("#citylist").html(data)
                        } );
                        '
                  ]);
				?>
					
              <?=
					$form->field($form_model, 'cit')->dropDownList(
					[],
					['prompt' => 'Выберите город','id' => 'citylist',
                     'onchange' => '
                        $.post("' . Yii::$app->urlManager->createUrl(['/street/streetajax?recid=']).'"+$(this).val(), function(data){
							
                        } );						
                        '						
					],
					['options' =>
						[],						
					]);
              ?>		  

<?php ActiveForm::end();?>	

	
<?php 
$data_new= City::find()->select(['cit_id', 'cit_name'])->where(['cit_reg_id' => Yii::$app->request->post('id')])->asArray()->all();	

Pjax::begin(['id' => 'pjax-grid-view']);
?>  
  <?= GridView::widget([
		'id' => 'grider',
        'dataProvider' => $dataProvider,
        'filterModel' => $model,		
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],	
            'str_id',
			
            [
                'attribute' => 'str_cit_id',
                'label' => 'Город (фильтр)',
                'headerOptions' => ['style' => 'width:300px;'],
                'filter' => ArrayHelper::map($data_new, 'cit_id', 'cit_name'),
				'format' => 'raw',
                'contentOptions'=>['style'=>'width:300px; max-width: 350px;'],  
            ],
			
            [
                'attribute' => 'sttypeName',
                'label' => 'Тип улицы',
            ],             
             
            'str_stt_id',
            'str_name',
            'str_name_short',
            // 'str_code',
            // 'str_type',
            // 'str_klcode',
            // 'str_AOGUID',

            ['class' => 'yii\grid\ActionColumn'],
        ],
        'layout'=>"{pager}\n{items}\n{summary}\n{pager}",
        'pager' => [
            'firstPageLabel' => 'Первая',
            'lastPageLabel'  => 'Последняя'
        ],
    ]); ?>	
	
<?php Pjax::end(); ?>


Контроллер:
public function actionChusovoi($recid=null)
    {	
		$form_model = new Chusovoi_sync;
        $searchModel = new StreetSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams,$recid);      //->with('streettype')
        $dataProvider->pagination->pageSize=30;
		
        return $this->render('chusovoi', [
			'recid' => $recid,
			'form_model' => $form_model,
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
		
	}
	
	
	public function actionAjax($id){

		if (Yii::$app->request->isAjax) {
			$operationsPost = City::find()
				->where(['cit_reg_id' => $id])
				->count();
				
			$operations = City::find()
				->where(['cit_reg_id' => $id])
				->all();
				
			echo "<option value = ''>Выберите город</option>";
			
			if($operationsPost > 0){
				foreach ($operations as $key){
					echo "<option value='".$key->cit_id."'>".$key->cit_name."</option>";			
				}
			}
			else{
				echo "<option></option>";
			}	
			
			\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
			return [
				
			];			
		}			
    }
	
	public function actionStreetajax($recid){
	/*
		$dataProvider1 = new ActiveDataProvider([
			'query' => Street::find()->where(['str_cit_id' => $recid])->all(),
			'pagination' => [
				'pageSize' => 20,
			],
			'sort' => [
				'attributes' => ['str_id', 'str_cit_id', 'sttypeName', 'str_stt_id', 'str_name', 'str_name_short'],
			],
		]);	
		
		if (Yii::$app->request->isAjax) {	
			$streetPost = Street::find()
				->where(['str_cit_id' => $recid])
				->count();
				
			$street = Street::find()
				->where(['str_cit_id' => $recid])
				->all();

			\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
			
			return [

				'street' => $street,
			];							
		}	*/		
	}
  • Вопрос задан
  • 367 просмотров
Пригласить эксперта
Ответы на вопрос 1
webinar
@webinar Куратор тега Yii
Учим yii: https://youtu.be/-WRMlGHLgRg
А зачем форма, если у Вас gridView с фильтрами?
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы