Session And Save Form Data

I’d like to save some part of the forms (inputs, select, …).

I share some example that is work correctly, but I like using the best practice.

The code below handle default, empty values too.

1) my base concept




  public function actionIndex($string=null) {

    if (is_null($string)) {

      if (isset(Yii::app()->session['string'])) {

        $string= Yii::app()->session['string'];

      } else {

        $string= "";

      }

    } else {

      Yii::app()->session['string'] = $string;

    }

  }



2) a little compact source




  public function actionIndex($string=null) {

      $string=

     	is_null($string)?

       	isset(Yii::app()->session['string'])?

         	Yii::app()->session['string']:"":

        Yii::app()->session['string'] = $string;

  }



3) multiple param handling




  public function actionIndex($string=null) {

      $varnames = array('string');

      foreach($varnames as $varname) {

        ${$varname} =

          is_null(${$varname})?

            isset(Yii::app()->session[$varname])?

           	Yii::app()->session[$varname]:"":

          Yii::app()->session[$varname] = ${$varname};    

      }

  }



If you don’t use sessions before don’t forget to config protected/config/main.php to handle Yii the sessions. For example:




   array(

 	// ...

 	'components' => array(

 	//...

        'session' => array (

            'sessionName' => 'yoursystemname',

            'cookieMode' => 'only',        

        ),

        // ...

      ),  



Do you have any, better idea?

Thanks!

Dear Friend.

This is the way I am doing.

For example there is a TestModel with two properties, name ,age.

Whether validated or not we can store the values of user submission.




Yii::app()->session->add('testForm',$_POST['TestForm']);



Then we can retrieve the values.




if(Yii::app()->session->contains('testForm')){

   $arr=Yii::app()->session->get('testForm');

   if(isset($arr['name']))

	echo $arr['name'];



We can also store and retrieve the values from a validated model.




if($model->validate()) 

{

	Yii::app()->session->add('testForm',$model);

}






if(Yii::app()->session->contains('testForm'))

{

   $model=Yii::app()->session->get('testForm');

   echo $model->name;

}



We can also store the form as a global value persistent across users sessions.




if($model->validate()) 

{

	Yii::app()->setGlobalState('testForm',$model);

}



we can retrieve the value in another session.




$model=Yii::app()->getGlobalState('testForm');

echo $model->age;