Controller Action To Handle Record Creation And Updation In Same Action Method

I am unable to chalk out layout of actions in my controller for some basic features. I have a view which provides account’s basic information. Account’s spans across many fields so users are most likely to do frequent saves. What I have experienced is every time I do a save, a new row is created. actionCreate is called and it simply dumps in the data in table. I am bound to keep the user on the same interface with all data filled in.

From what I have gathered so far, I can not have action parameter for actionCreate method because it fails since it is null for the very first save.

Following is my action method code:




    public function actionCreate()

{

    $model=new Account;

    $accaddress=new AccAddress;


    // Uncomment the following line if AJAX validation is needed

    // $this->performAjaxValidation($model);


    if(isset($_POST['Account'],$_POST['AccAddress']))

    {

        $model->attributes=$_POST['Account'];


        if($model->save()) //Account data saving


            if (isset($_POST['AccAddress'])){

            //Yii::log('Dumping infomration for multiple models.');

            $accaddress->attributes=$_POST['AccAddress'];

            $accaddress->acc_id=$model->id;




            if ($pataddress->save()){//Account address saving

            }

            //$this->redirect(array('create','id'=>$model->id));

            }

    }


    $this->render('create',array(

        'model'=>$model,

        'accaddress'=>$accaddress,

        'tabss'=>$tabarray,

    ));

}



Anxiously looking forward to suggestions / comments. Thanks in advance.

Regards, Faisal

Something along these lines maybe?

In your view, you add the model’s id in a hidden field (make sure that it’s not present in your model’s validation rules safe array).

And in your action:


public function actionCreate()

{

    if (isset($_POST['Account'])) {

        if ($_POST['Account']['id'] === '') {

            $model = new Account;

        } else {

            $model = Account::model()->findByPk( $_POST['Account']['id']);

        }

    ...

Thanks a lot. After I logged this problem here, I got the hidden id solution but was banging my head between safe - unsafe and so many other things on countless websites and then out of desperation I came back here in desperate hope if anyone had replied ! and there you go!!! You reply exactly pin pointed the 100% exact problem with the exact solution what I had been looking for. So many thanks to you man…you made my day…!! All the best !

Yii ROCKSsss…!!!

Dear FaisalKhan

I hope the following is helpful. The concept is the same as suggested by bennouna.

But it is more Yii way of doing things and also more secure.

The idea here is making something stateful in pages.

For example, I have got a model ‘Gene’.

_form.php in views folder.

Set the property stateful to true.




<div class="form">


<?php $form=$this->beginWidget('CActiveForm', array(

	'id'=>'gene-form',

	'stateful'=>true,//Here is the small addition.

	'enableAjaxValidation'=>false,

)); ?>


	<p class="note">Fields with <span class="required">*</span> are required.</p>


	<?php echo $form->errorSummary($model); ?>


	<div class="row">

		<?php echo $form->labelEx($model,'spot'); ?>

		<?php echo $form->textField($model,'spot'); ?>

		<?php echo $form->error($model,'spot'); ?>

	</div>


	<div class="row buttons">

		<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?>

	</div>


<?php $this->endWidget(); ?>


</div><!-- form -->



In controller.




public function actionCreate()

	{

		$model=new Gene;


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['Gene']))

		{

			$model->attributes=$_POST['Gene'];


			if( $this->getPageState('id')==null && $model->save())

				$this->setPageState('id',$model->id);


				//$this->redirect(array('view','id'=>$model->id));


			if($this->getPageState('id')!==null)

				$model=$this->loadModel($this->getPageState('id'));

		}


		$this->render('create',array(

			'model'=>$model,

		));

	}



Kindly check the hidden field in firebug to see how it is rendered.

Regards.

Yes seenivasan. Definitely better. Sessions are also an option.

Thanks seenivasan and bennouna! I moved on with hidden id solution and tested it with positive results. Thanks for your follow ups on the thread, will definitely try the session approach too.

Best regards

Faisal