Hello Experts,
I am trying to increment a session variable. Below is the codes. I am having two issues with the codes.
- I am trying to increase the variable by 1, but it is incremented by 2 all the times.
- 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() ?>