Set Active Year End

Am developing an application with Academic Year using this model attribute below:

[b]

model[/b]




    public function attributeLabels()

    {

        return [

            'year_id' => Yii::t('app', 'ID'),

            'year_name' => Yii::t('app', 'Year Name'),

            'start_date' => Yii::t('app', 'Start Date'),

            'end_date' => Yii::t('app', 'End Date'),

            'is_status' => Yii::t('app', 'Status'),

        ];

    }



  1. year_id is auto-generated

  2. is_status is tinyint

  3. year_name is concatenation of start_date and end_date (start_date-end_date)

[b]

Controller

[/b]




    public function actionCreate()

    {

        $model = new AcademicYear();


	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['AcademicYear'];

		$model->start_date = Yii::$app->dateformatter->getDateFormat($_POST['AcademicYear']['start_date']);

		$model->end_date = Yii::$app->dateformatter->getDateFormat($_POST['AcademicYear']['end_date']);

		if($model->save())

			return $this->redirect(['index']);

		else

			return $this->render('create', ['model' => $model,]);

	

        } else {

            return $this->render('create', [

                'model' => $model,

            ]);

        }

    }



[b]

Question

[/b]

I want to have a platform to set Active/Inactive Academic Year. Once I set the academic year active, all the other (rows) ones should be automatically set to inactive. That is, the field is_status should be set to 0 as inactive, and only the current one should be set to 1 as Active.

How do I go about this

Hi,

The following code may help you!





//First set all to in-active

$connection->createCommand()

        ->update('AcademicYear', ['is_status' => 0], '1 = 1')

        ->execute();


//Set your particular model as 1

$model = new AcademicYear();

$updateSingle = $model->findOne($pk);// Your primary key

$updateSingle->is_status = 1;

$isUpdated = $updateSingle->save();