Use Ajaxbutton In Update And Create Methode

Hi

I tested Ajax form in yii and it was worked on " create " in perfect way , but my target to do like Gii (create -update) in same form .

in this code only Create(insert ) work , but update not worked .

This my code :

Form View :




<?php

/* @var $this AjaxController */

/* @var $model Csection */

/* @var $form CActiveForm */

?>


<div class="form">


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

	'id'=>'csection-form',

  	'enableAjaxValidation'=>true,

    	//'enableClientValidation'=>true,

    	'clientOptions'=>array('validateOnSubmit'=>true), //This is very important

)); ?>


	<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,'en_name'); ?>

		<?php echo $form->textField($model,'en_name',array('size'=>60,'maxlength'=>255)); ?>

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

	</div>


	<div class="row">

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

		<?php echo $form->textField($model,'ar_name',array('size'=>60,'maxlength'=>255)); ?>

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

	</div>


	<div class="row">

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

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

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

	</div>


	<div class="row buttons">

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

    	

    	echo CHtml::ajaxButton($model->isNewRecord ? 'Craete' : 'Save',$model->isNewRecord ? array('ajax/create') : array('ajax/update') ,array(

    	'type'=>'POST',

    	'update'=>'#mydiv',

    	'beforeSend'=>'function(data){ 

        	

 			$("#mydiv").html("<img src=\"http://www.checkprg.com/images/loading.gif\" width=\"100\" height=\"100\" />");

        	

    	}',

          	'success'=>'

   		function(data){

      	

      	$("#mydiv").html("<p style=color:#FF0101;>Work <img src='http://www.yiiframework.com/forum/public/style_emoticons/default/smile.gif' class='bbc_emoticon' alt=':)' /></p>");

 	$.fn.yiiGridView.update("csection-grid");

   	}   	

        	

        	

        	',

 		'error'=>'

 		function(data){

        	

        	$("#mydiv").html("<p style=color:red;>Error</p>");

        	$.fn.yiiGridView.update("csection-grid");

 		}

 		', 

        	

 		

    	

 		

 		

  	

        	


));

 		?>




	</div>


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


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

<div id="mydiv" style="color:white;"></div>

This create Controller and it was worked :


	public function actionCreate()

	{

		$model=new Csection;


		// Uncomment the following line if AJAX validation is needed

      	$this->performAjaxValidation($model);


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

		{

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

			if($model->validate()){

			

        	$model->save();

        	

			}

        	else{

            	throw new CHttpException(404,'The specified post cannot be found.');

        	}

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

		}

        	if(Yii::app()->request->getIsAjaxRequest()){

             			

 echo $this->render('create',array('model'=>$model),false,true);//This will bring out the view along with its script.

   }

   else{

	

 	echo $this->render('create',array('model'=>$model));

 	

   }

	}

Update Controller return Error every request :




public function actionUpdate($id)

	{

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


		// Uncomment the following line if AJAX validation is needed

         $this->performAjaxValidation($model);


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

		{

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

			if($model->save()){

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

		}else{

           throw new CHttpException(404,'The specified post cannot be found.');

      	

		}

}

        			if(Yii::app()->request->getIsAjaxRequest()){

             			

 echo $this->render('update',array('model'=>$model),false,true);//This will bring out the view along with its script.

   }

   else{

	

 	echo $this->render('update',array('model'=>$model));

 	

   }

	}




Model :


	public function rules()

	{

		// NOTE: you should only define rules for those attributes that

		// will receive user inputs.

		return array(

			array('en_name, ar_name,order_by', 'required', 'message'=>'يرجى ملئ حقل {attribute} '),

			array('en_name, ar_name', 'length','max'=>50 ,'min'=>1,'tooShort'=>'عدد الأحرف أقل من {min}',

         	'tooLong'=>'عد الأحرف أكثر من {max} '),

  			array('order_by', 'numerical', 'integerOnly'=>true,'message'=>' {attribute}  هذا الحقل من النوع الرقمي فقط '),

        	

         	array('order_by', 'unique','message'=>'هذا الرقم موجود مسبقا'),

        	

			// The following rule is used by search().

			// Please remove those attributes that should not be searched.

			array('section_id, en_name, ar_name', 'safe', 'on'=>'search'),

		);

	}


	/**

	 * @return array relational rules.

	 */

	public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

		   'msections' => array(self::HAS_MANY, 'Msection', 'section_id'),

			'news' => array(self::HAS_MANY, 'News', 'section_id'),

        	

			'topstories' => array(self::HAS_MANY, 'Topstory', 'section_id'),

		);

	}

How to improve it to be work on update method also ?

Thanks in advance

Hi,

please post your model rule function…

Hi Ankit , I edited it and added the model .

Hi,

you can see the link…

http://www.yiiframework.com/forum/index.php/topic/43977-ajax-client-side-validation-without-refreshing-page/page__p__208536__fromsearch__1#entry208536

hope it will be help…

otherwise you can chnage the update action


public function actionUpdate($id)

	{

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


		// Uncomment the following line if AJAX validation is needed

		$this->performAjaxValidation($model);


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

		{

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

			if($model->save()){

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

			}else{

				throw new CHttpException(404,'The specified post cannot be found.');


			}

		}

		$this->render('update',array('model'=>$model),false,true);

	}



Thanks My Bro Ankit but it still not work , you know I guess the problem in model because in Tamper all data send

but validate() return false ?

Hi,

you can put the code in your update action…after action start




if((count(CJSON::decode(CActiveForm::validate($modelForm)))>0)) {

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

                        'model'=>$model,

		));

		Yii::app()->end();


	}

or




if(CActiveForm::validate($modelForm))>0)) {

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

                        'model'=>$model,

		));

		Yii::app()->end();


	}

otherwise best way when action call stop the jquery.js


  $cs = Yii::app()->clientScript;

        $cs->reset();

        $cs->scriptMap = array(

            'jquery.js'  =>  false,   // prevent produce jquery.js in additional javascript data

            'jquery.min.js'  =>  false,

        );

hope it will be helpful…

My Bro my code now look like this :




public function actionUpdate($id)

    	{

         	

         	

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


         	

         	if(CActiveForm::validate($model)>0) {

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

                    	'model'=>$model,

            	));

            	Yii::app()->end();


    	}

            	// Uncomment the following line if AJAX validation is needed

            	$this->performAjaxValidation($model);


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

            	{

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

                    	if($model->save()){

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

                    	}else{

                            	throw new CHttpException(404,'The specified post cannot be found.');


                    	}

            	}

            	$this->render('update',array('model'=>$model),false,true);

    	}

But also not worked , so can you tell me when my error ? or it’s correct

Thanks in advance


'enableClientValidation'=>true,

remove the uncommnet

or it’s not working another try…





$cs = Yii::app()->clientScript;

        $cs->reset();

        $cs->scriptMap = array(

            'jquery.js'  =>  false,   // prevent produce jquery.js in additional javascript data

            'jquery.min.js'  =>  false,

        );

[b] Ankit , thanks to help me .

I will try to fix it and inform you .

[/b]

Hi,

if you can use submitButton


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

it’s working but you can use ajaxButton it’s problem…


        echo CHtml::ajaxButton();

so let’s try…using submitButton i hope it’s work done.hopefully…