2
votes

I have a table with these fields:

aca_class_subjects: 
                    class_subject_id, class_subject_subject_id, 
                    class_subject_class_group_id, class_subject_class_id

class_subject_id is the Primary Key and it is auto_increment. class_subject_class_id and class_subject_class_group_id form a dependent dropdownlist.

class_subject_subject_id is from a table called aca_subjects and it will form the checkbox.

checkedboxlist

Controller: AcaClassSubjectsController

public function actionCreate()
{
    $model = new AcaClassSubjects();

    $searchModel = new AcaSubjectsSearch();
    $searchModel->is_status = 0 ;
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    return $this->render('create', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
        'model'=> $model,
    ]);
}    

public function actionUpdate($id)
{
    $model = $this->findModel($id);

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        return $this->redirect(['view', 'id' => $model->class_subject_id]);
    } else {
        return $this->render('update', [
            'model' => $model,
        ]);
    }
}

Model: AcaClassSubjects

    public function attributeLabels()
{
    return [
        'class_subject_id' => Yii::t('aca', 'ID'),
        'class_subject_subject_id' => Yii::t('aca', 'Subject'),
        'class_subject_class_id' => Yii::t('aca', 'Class'),
        'class_subject_class_group_id' => Yii::t('aca', 'Class Group'),      
         ];
}

AcaSubjectsSearch

    public function search($params)
{
    $query = AcaSubjects::find()->where(['<>', 'is_status', 2]);

    $dataProvider = new ActiveDataProvider([
        'query' => $query, 'sort'=> ['defaultOrder' => ['subject_id'=>SORT_DESC]],
        'pagination' => [ 'pageSize' => 5 ]
    ]);

    $this->load($params);

    if (!$this->validate()) {
        // uncomment the following line if you do not want to any records when validation fails
        // $query->where('0=1');
        return $dataProvider;
    }

    $query->andFilterWhere([
        'subject_id' => $this->subject_id,
    ]);

    $query->andFilterWhere(['like', 'subject_name', $this->subject_name])
        ->andFilterWhere(['like', 'subject_code', $this->subject_code]);         

    return $dataProvider;
}

View

<div class="col-xs-12" style="padding-top: 10px;">
    <div class="box">

		    <?php $form = ActiveForm::begin([
					'id' => 'academic-level-form',
					'enableAjaxValidation' => false,
					'fieldConfig' => [
					    'template' => "{label}{input}{error}",
					],
		    ]); ?>            
		    <div class="col-xs-12 col-lg-12 no-padding">  
		        <div class="col-xs-12 col-sm-6 col-lg-6">    

            <?= $form->field($model, 'class_subject_class_group_id')->widget(Select2::classname(), [
                'data' => ArrayHelper::map(\app\modules\academic\models\AcaClassGroups::find()->where(['is_status' => 0])->all(),'class_group_id','class_group_name'),
                'language' => 'en',
                'options' => ['placeholder' => '--- Select Class Group ---', 
                    'onchange'=>'
                        $.get( "'.Url::toRoute('dependent/getclassmaster').'", { id: $(this).val() } )
                            .done(function( data ) {
                                $( "#'.Html::getInputId($model, 'class_subject_class_id').'" ).html( data );
                            }
                        );' 
                ],
             //   'disabled'=>'true',
                'pluginOptions' => [
                    'allowClear' => true
                ],
            ]); ?>                         
		        </div>
		        <div class="col-xs-12 col-sm-6 col-lg-6">
		            <?= $form->field($model, 'class_subject_class_id')->widget(Select2::classname(), [
		            'data' => ArrayHelper::map(\app\modules\academic\models\AcaClassMaster::findAll(['class_id' => $model->class_subject_class_id]),'class_id','class_name'),
		                'language' => 'en',
		                'options' => ['placeholder' => '--- Select Class ---'],
		                'pluginOptions' => [
		                    'allowClear' => true
		                ],
		            ]); ?>                          	        
                </div>
		    </div> 

        <div class="box-body table-responsive">
           
                <h4><strong><u>Select Subject(s)</u></strong></h4>
                     
            <div class="course-master-index">
    <?= GridView::widget([
        'id'=>'grid',
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            [
            'class' => 'yii\grid\CheckboxColumn',
            'header' => Html::checkBox('selection_all', false, [    
            'class' => 'select-on-check-all',
            'label' => 'All',
                ]),
            'visible'=> true,
            'contentOptions' =>['style' => 'vertical-align:middle;width:30px'],

                'checkboxOptions' => function($model, $key, $index, $column) {
                    return ['value' => $model->subject_id];
                }
             ],
            ['class' => 'yii\grid\SerialColumn'],

           // 'id',
            'subject_name',

                                 ],
    ]); ?>
    <?= Html::input('hidden','keylists',$value='', $options=['id'=>'keylist'])  ?>
    <div class="form-group">
        <?= Html::submitButton('Submit', ['class' =>'btn btn-success btn-block btn-lg','id'=>"button123"]) ?>
    </div>
	</div>
      </div>
      <?php ActiveForm::end(); ?>
    </div>
</div>  

My questions are

After selecting particular rows (subject_id) using checkboxes from Table aca_subjects, and also select the dropdownlist as shown in the diagram

  1. How do I insert them (class_subject_subject_id,class_subject_class_id, class_subject_class_group_id) to the Table aca_class_subjects?
  2. How do I update them (class_subject_subject_id,class_subject_class_id, class_subject_class_group_id) to the Table aca_class_subjects?
  3. How do I display a dialogue box when nothing is selected?

Note: class_subject_subject_id (checkbox in gridview),class_subject_class_id (dropdownlist), class_subject_class_group_id (dropdownlist)

When I clicked on submit, nothing goes to the database

1
your question is too broad as you are asking a general question that how to you add them you should show you part for solving the problem so that it is more clear which part you are stucked or are unable to perform and is a showstopper for you? - Muhammad Omer Aslam
and which model are you using to populate the Select2 dropdowns ? you are using the ActiveForm in the view. - Muhammad Omer Aslam

1 Answers

2
votes

Well, the question is a bit broad as you haven't shown any code related to solving your problem specifically so my wild guess is that you have a basic showstopper for collecting the class_subject_subject_id from the gridview. so i will suggest the javascript part in my answer where it submits the form with ajax.

But before i suggest you a solution you have a basic problem that you are wrapping the gridview with the form you are using to insert the subjects in the aca_class_subjects

Why?

  • Because if you wrap the Gridview with a form along with the gridview filters the GridView does not create its own hidden form that it uses for submitting the filter inputs for search in the GridView, and hence when you will try search by typing in the GridView filter input it would submit it to the action specified in your outer form that can have a different action like in your case.

So if you still want to use the ActiveForm do not wrap the Gridview inside the form keep it separate, and close it before you call the GridView::widget() but you have the button placed in the end of the Gridview and you dont want to change the design so change the code for the button from Html::submitButton() to Html::button() and keep it outside the ActiveForm that you have created. You can submit the form with javascript.

So your view code should look like below

<div class="col-xs-12" style="padding-top: 10px;">
    <div class="box">

        <?php
        $form = ActiveForm::begin([
                    'id' => 'academic-level-form',
                    'enableAjaxValidation' => false,
                    'action'=>\yii\helpers\Url::to(['assign-subjects'])
                    'fieldConfig' => [
                        'template' => "{label}{input}{error}",
                    ],
        ]);
        ?>            
        <div class="col-xs-12 col-lg-12 no-padding">  
            <div class="col-xs-12 col-sm-6 col-lg-6">    

                <?=
                $form->field($model, 'class_subject_class_group_id')->widget(Select2::classname(), [
                    'data' => ArrayHelper::map(\app\modules\academic\models\AcaClassGroups::find()->where(['is_status' => 0])->all(), 'class_group_id', 'class_group_name'),
                    'language' => 'en',
                    'options' => ['placeholder' => '--- Select Class Group ---',
                        'onchange' => '
                        $.get( "' . Url::toRoute('dependent/getclassmaster') . '", { id: $(this).val() } )
                            .done(function( data ) {
                                $( "#' . Html::getInputId($model, 'class_subject_class_id') . '" ).html( data );
                            }
                        );'
                    ],
                    //   'disabled'=>'true',
                    'pluginOptions' => [
                        'allowClear' => true
                    ],
                ]);
                ?>                         
            </div>
            <div class="col-xs-12 col-sm-6 col-lg-6">
                <?=
                $form->field($model, 'class_subject_class_id')->widget(Select2::classname(), [
                    'data' => ArrayHelper::map(\app\modules\academic\models\AcaClassMaster::findAll(['class_id' => $model->class_subject_class_id]), 'class_id', 'class_name'),
                    'language' => 'en',
                    'options' => ['placeholder' => '--- Select Class ---'],
                    'pluginOptions' => [
                        'allowClear' => true
                    ],
                ]);
                ?>                                      
            </div>
        </div> 
        <?=Html::input('hidden', 'keylists', $value = '', $options = ['id' => 'keylist']) ?>
        <?php ActiveForm::end(); ?>

        <div class="box-body table-responsive">

            <h4><strong><u>Select Subject(s)</u></strong></h4>

            <div class="course-master-index">
                <?=
                GridView::widget([
                    'id' => 'grid',
                    'dataProvider' => $dataProvider,
                    'filterModel' => $searchModel,
                    'columns' => [
                        [
                            'class' => 'yii\grid\CheckboxColumn',
                            'header' => Html::checkBox('selection_all', false, [
                                'class' => 'select-on-check-all',
                                'label' => 'All',
                            ]),
                            'visible' => true,
                            'contentOptions' => ['style' => 'vertical-align:middle;width:30px'],
                            'checkboxOptions' => function($model, $key, $index, $column){
                                return ['value' => $model->subject_id];
                            }
                        ],
                        ['class' => 'yii\grid\SerialColumn'],
                        // 'id',
                        'subject_name',
                    ],
                ]);
                ?>

                <div class="form-group">
                    <?=Html::button('Submit', ['class' => 'btn btn-success btn-block btn-lg', 'id' => "button123"]) ?>
                </div>
            </div>
        </div>

    </div>
</div>  

Now about the saving of the records.

You can get all the selected subjects that are in the grid view by using the following javascript code where you select all the checked checkboxes which have the name selection[]. Add the below code on top of your view

$reflect = new ReflectionClass($model);
$subjectId = $reflect->getShortName() . '[class_subject_subject_id][]';
$js = <<<JS

    $("#button123").on('click',function(e){
        e.preventDefault();
        $("#academic-level-form").yiiActiveForm('submitForm');
    });

    $("#academic-level-form").on('beforeSubmit',function(e){
        e.preventDefault();
        // yii.getCsrfParam(),yii.getCsrfToken(),
        let subjects=$("input[name='selection[]']:checked");
        let subjectsSelected=subjects.length;

         if(!subjectsSelected){
             alert('select some subjects first');
         }else{
            let data=$(this).serializeArray();

            $.each(subjects,function(index,elem){
                data.push({name:"$subjectId",value:$(elem).val()})
            });

            let url=$(this).attr('action');
            $.ajax({
                url:url,
                data:data,
                type:'POST',
            }).done(function(data){
                alert(data);
            }).fail(function(jqxhr,text,error){
                alert(error);
            });
         }
        return false;
    });
JS;
$this->registerJs($js, \yii\web\View::POS_READY);

Now if you have print_r(Yii::$app->request->post()) inside the actionAssignSubjects() in your controller where the form is submitting you can see the output of the posted variables and your subjects will be under the same model array that you are using for populating the dropdowns with the name class_subject_subject_id and all the selected subjects would be under this array. You can loop over them to save to your desired model.

I leave the rest of the work on you to do by your self and if you run into any problems you should post a separate question with the targetted code.