[SOLVED]:Increment variable using session

Hello Experts,

I am trying to increment a session variable. Below is the codes. I am having two issues with the codes.

  1. I am trying to increase the variable by 1, but it is incremented by 2 all the times.
  2. Last data is not getting saved.

Can you please guide me, where am I going wrong?

DB Structure:
id--------------> int(11)
slno ----------> int(11)
reqnum-------> int(11)

Model:

<?php

namespace frontend\models;

use Yii;

class IncForm extends \yii\db\ActiveRecord
{

public static function tableName()
{
    return 'test';
}

public function rules()
{
    return [
        [['reqnum','slno'],'required'],
          ];
}
 public function attributeLabels()
{
return [
'reqnum'=> 'Number input',
        ];
   }

}  

Controller:

<?php 

namespace frontend\controllers;
use Yii;
use yii\web\Controller;
use frontend\models\IncForm;
use  yii\web\Session;

class TestController extends Controller

public function actionTest(){
//------------------increment-------------------------
	$session=Yii::$app->session;
	if (isset($session['slno'])) {
		$session['slno'] = $session['slno'] + 1;
	} else{
		$session['slno'] = 1;
	}

	if ($session['slno'] >7) {
	      $session->remove('slno');
      return $this->redirect('success');
  }

	$model = new IncForm();
	 if ($model->load(Yii::$app->request->post())) {
					$model->save();
					return $this->refresh();
				}
			
				return $this->render('test', [
									  'sno'=>$session['slno'],
									  'model' => $model,
      				     		]);
}

public function actionSuccess(){
	return $this->render('success');
 }
}

View:

<?php
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\web\View;
use yii\widgets\ActiveForm;
?>
<div id= "content">

        <?php $form = ActiveForm::begin([
                    'id' => 'form-test'])?>
<div class="row">                 
  <div class="col-xs-3" id="slid">
    Serial No: <?= Html::encode($sno) ?>
  </div>
</div>


<div class="row" id=""> 
    <div class="col-xs-2" style="background-color:#90189e;" align="center">
            <?= $form->field($model, 'slno')->textInput(['readonly' => true, 'value' => $sno])?>
    </div>
    <div class="col-xs-2" style="background-color:#90189e;" align="center">
            <?= $form->field($model, 'reqnum')->textInput()->hint('Pease enter a number')?>
    </div>
    
</div>
<div class="row" id=""> 
    
                <?= Html::submitButton('Increment Test', ['class' => 'btn btn-success']) ?>
   
</div>

<?php ActiveForm::end() ?>

i think it is type wrong variable name $sno, it should be $slno

Hello Wilson,
Thanks for your reply. Above code is fine with

Serial No: <?= Html::encode($sno) ?>

If you see the controller code, there I have forwarded this variable in that way.

return $this->render('test', [
		'sno'=>$session['slno'],
		'model' => $model,
      		]);

No issue if I modified in controller as well as in view ‘sno’ with ‘slno’.

But the my initial problem persists.
Can you guide on the initial issue?

Regards,
Siddhartha

Hi Sid,

It’s because “actionTest” is called twice before you save the model.
At first, it is called when you first visit this page.
Then secondly, it is called when you submit the form .

Try this:

public function actionTest(){
    $session=Yii::$app->session;
    if (!isset($session['slno'])) {
        $session['slno'] = 1;
    }
    if ($session['slno'] >7) {
        $session->remove('slno');
        return $this->redirect('success');
    }

    $model = new IncForm();
    if ($model->load(Yii::$app->request->post())) {
        if ($model->save()) {
            $session['slno'] = $session['slno'] + 1;
            return $this->refresh();
        }
    }
    return $this->render('test', [
        'sno'=>$session['slno'],
        'model' => $model,
    ]);
}

By doing this, the variable will only be incremented when you have successfully saved the model.

Hello softark,

Thanks for your guidance.
It works as I wanted. Your modification guidance resolve both the problems.
This thread can be marked as solved.
Really appreciate your guidance.

Regards,
Sid