olugbenga
olugbenga

Reputation: 25

Yii2 - Dropdownlist OnChange to Display Other Model Attribute

I have these Model Classes

Model:Subject

public function attributeLabels()
{
    return [
        'subject_id' =>Yii::t('app',  'ID'),
        'subject_title' => Yii::t('app', 'Subject Title'),
    ];
}

Model:Grouping

public function attributeLabels()
{
    return [
        'grouping_id' => Yii::t('app', 'Grouping ID'),
        'grouping_name' => Yii::t('app', 'Grouping Name'),
    ];
}

Model:SubjectGrouping

public function attributeLabels()
{
    return [
        'subject_grouping_id' => 'Subject Grouping ID',
        'subject_grouping_grouping_id' => 'Subject Grouping Grouping ID',
        'subject_grouping_subject_id' => 'Subject Grouping Subject ID',
    ];
}

Model:Exam

public function attributeLabels()
{
    return [
        'exam_id' =>Yii::t('app',  'ID'),
        'exam_name' => Yii::t('app', 'Exam Name'),
    'exam_group_id' => Yii::t('app', 'Exam Group'),
    ];
}

Model:SubjectGrouping has Foreign Keys from Model: Grouping (subject_grouping_grouping_id) and Model:Subject (subject_grouping_subject_id)

In Model:Exam, exam_group_id relates to subject_grouping_grouping_id in Model:SubjectGrouping.

Controller

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

    if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        return ActiveForm::validate($model);
    }
    if ($model->load(Yii::$app->request->post())) {

        $model->attributes = $_POST['Exam'];
        $model->save();
        return $this->redirect(['index']);
    } else {
        return $this->render(
            'create', [
                'model' => $model
            ]
        );
    }
}

View

<div class="col-xs-12 col-sm-4 col-lg-4">
    <?=$form->field($model, 'exam_name')->textInput(['maxlength' => 50, 'placeholder' => 'Enter Exam Name'])?>
</div>

<div class="col-xs-12 col-sm-4 col-lg-4">
<?=$form->field($model, 'exam_group_id')->widget(
    Select2::classname(), [
        'data' => ArrayHelper::map(app\models\Grouping::find()->all(), 'grouping_id', 'grouping_name'),
        'language' => 'en',
        'options' => ['placeholder' => '--- Select Grouping ---'],
        'pluginOptions' => [
            'allowClear' => true
        ]
    ]
);
?>
</div>

Dropdownlist

From the diagram, how do I achieve these?

  1. when Dropdownlist for exam_group_id is onChange the list of subjects with respect to grouping is displayed using the relationship between Model: SubjectGrouping and Model: Subject.

  2. Others fields such as exam_name (textInput) and exam_group_id (Dropdownlist) should be save into the Model: Exam. But the subject list should not be saved. It is only for display purpose.

How do I achieve these?

I am using kartik\widgets\Select2 for the dropdownlist

Upvotes: 0

Views: 1430

Answers (1)

Abhishek Srivastava
Abhishek Srivastava

Reputation: 151

I have done similar code by Kartik extension for state and country data.

here is the code for that.

<?php
    //in view use this

    use kartik\widgets\DateTimePicker; // or kartik\select2\Select2
    use kartik\widgets\DepDrop;
    use kartik\widgets\Select2;
?>

<?php
    echo
    $form->field($model, 'country_id')->widget(
        Select2::className(),
        [
            'data' => \yii\helpers\ArrayHelper::map(common\models\Country::find()->all(), 'id', 'name'),
            'options' => [
                'id' => 'country_id',
                'prompt' => Yii::t('aspns', 'Select')
            ]
        ]
    );
?>
<?php
    echo
    $form->field($model, 'state_id')->widget(
        DepDrop::classname(),
        [
            'data' => !empty($model->state_id) ? \yii\helpers\ArrayHelper::map(common\models\State::find()->where(['country_id' => $model->country_id])->all(), 'id', 'name') : [],
            'options' => ['id' => 'state_id', 'placeholder' => Yii::t('aspns', 'Select')],
            'pluginOptions' => [
                'depends' => ['country_id'],
                'url' => Url::to(['//country/get-states'])
            ]
        ]
    )->label(Yii::t('aspns', 'State'));
?>

// In Controller section you need to do this

 public function actionGetStates() {
    $out = [];
    if (isset($_POST['depdrop_parents'])) {
        $parents = $_POST['depdrop_parents'];
        if ($parents != null) {
            $country_id = (int)$parents[0];
            $out = State::find()->where(['country_id'=>$country_id])->select(['id', 'name'=>'name'])->asArray()->all();
            return Json::encode(['output'=>$out, 'selected'=>'']);

        }
    }
    return  Json::encode(['output'=>'', 'selected'=>'']);
}

Change the code according to your requirement.

Thanks

Upvotes: 0

Related Questions