[Solved]Add Cgridview Item With Ajax And Save It

Good afternoon.

I have this:

  • 4 tables:

Notices

IdNotice

Species

IdSpecie

Conditions

IdCondition

RelTable

IdNotice

IdSpecie

IdCondition

The problem is that in RelTable, a specie will have a condition related to her. I don’t know how to make the views.

I had thought about having a dropdownlist to species, other to conditions and an add button to the right of it. Then, when I select one specie in dropdownlist, one condition in the other dropdownlist and when I press the add button, add these data to a CGridView with 2 columns (Specie and Conditon) below.

And have a delete button to the left of the grid.

But, how can I do this? I’m not an expert in AJAX.

And how do I collect the data from the grid to save?

Can anyone help me or write me a link to an example?

Greetings and thanks.

Dear Friend

I have made an attempt in a similar fashion in the following post.

Assigning Data to User

3742

multigrid.png

Have a look at the picture.

1.First grid is user grid. Where one is allowed to choose only one row (one user)

2.second grid is customer grid, where one can select multiple customer id.

3.third is a small form, which gather the ids users and customers when user select rows in user and customer grid.

4.Upon submitting the form, the grid below is updated by ajax without page load for that particular user.

We can also delete a customer from the delete button in the grid.

Thus we can add a customer and delete the customer for a particular user without page load or page changes in the last grid.

The picture clearly depicts one such scenario.

Regards.

Good mornig.

seenivasan, I just tested your code and it works perfectly, but I want to add items to the list before saving in the database.

In addition, the first column would be a model and the second is from another model. Or two pasted lists each with their model.

Anyway, thank you very much for the example. Now I have something to start testing things.

Has anyone done what I want? A help would be greatly appreciated.

Thanks.

PD.: Could I make it through a CActiveDataProvider?

Dear Friend

Kindly check whether the following is helpful in our case.

I have this:

  • 4 tables:

notice

id,description

species

id,name

condition

id,name

relation

n_id,s_id,c_id

Following are in nutshell:

1.Collect the data from dropDowns and send them via AJAX.

2.Convert the data to array and store them in session.

3.Use the CArrayDataProvider as dataProvider for the collected information.

4.Update the grid by AJAX, as user adds further information from dropdown.

5.Remove the particular row by AJAX, by collecting information from row elements and removing the data in session

and restoring changed data to session.

6.Finally saving the data to Relation table whatever existing in session.

7.Avoiding duplicates in adding to the list as well as adding to the database.

8.Upon successful entry into database, all the data in session are nullified.

views/notice/view.php




<h1>View Notice #<?php echo $model->id; ?></h1>


<?php $this->widget('zii.widgets.CDetailView', array(

	'data'=>$model,

	'attributes'=>array(

		'id',

		'description',

	),

)); ?>


<?php

echo CHtml::beginForm('','post',array("id"=>"nform"));?>


<?php echo CHtml::dropDownList('speciesName','',array(CHtml::listData(Species::model()->findAll(),"id","name"))); ?>

		

<?php echo CHtml::dropDownList('conditionName','',array(CHtml::listData(Condition::model()->findAll(),"id","name"))); ?>

		 

		

	

<?php echo CHtml::ajaxSubmitButton("ADD",'',array(

'data'=>'js:$("#nform").serialize()',

'success'=>'js:function(data){$("#relation-grid").yiiGridView("update",{})}'

),array("id"=>"butt","style"=>"color:green;"));?>


<?php echo CHtml::endForm();?>




<?php $this->widget('zii.widgets.grid.CGridView', array(

	'id'=>'relation-grid',

	'dataProvider'=>$relationProvider,

	//'filter'=>$relation,

	'columns'=>array(

		

		'n_id',

		array(

		'header'=>'Species',

		'name'=>'s_id',

		'value'=>'Species::model()->findByPk($data["s_id"])->name',

		),

		array(

		'header'=>'SpeciesField',

		'value'=>'CHtml::textField("species",$data["s_id"])',

		'type'=>'raw'

		),

		array(

		'header'=>"Condition",

		'name'=>'c_id',

		'value'=>'Condition::model()->findByPk($data["c_id"])->name',

		),

		array(

		'header'=>'ConditionField',

		'value'=>'CHtml::textField("species",$data["c_id"])',

		'type'=>'raw',

		),

		array(

		'value'=>'CHtml::button("REMOVE",array("style"=>"color:red;"))',

		'type'=>"raw"

		),

		

		

	),

)); ?>


<?php echo CHtml::button("SAVE",array(

"submit"=>array("notice/save")

));

?>

<?php


Yii::app()->clientScript->registerScript('test','

$("body").on("click","#relation-grid input[type=\"button\"]",function(){

	var data={};

	var sibs=$(this).parent().siblings();

		data.n_id=$(sibs[0]).html();

		data.s_id=$(sibs[2]).children().val();

		data.c_id=$(sibs[4]).children().val();

		console.log(data);

		$.ajax({

                    "url":"'.CHtml::normalizeUrl(array("notice/view","id"=>$model->id)).'",

		    "data":data,

		    "type":"POST",

		    "success":function(data){$("#relation-grid").yiiGridView("update",{});},

			})

		

		return false;

		});


');




NoticeController.php




public function actionView($id)

{   

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

	     if(!Yii::app()->user->hasState("related"))

	         Yii::app()->user->setState("related",array());

	    

	     if(Yii::app()->user->hasState("related"))

	     {  

                $relationProvider=new CArrayDataProvider(Yii::app()->user->getState('related'));

		$relationProvider->keyField=false;

             }

		

		

	    If(isset($_POST['speciesName']) && Yii::app()->request->getIsAjaxRequest())

            {

	        $related=Yii::app()->user->getState("related");

	        $posted=array('n_id'=>$model->id,'s_id'=>$_POST['speciesName'],"c_id"=>$_POST['conditionName']);

	        if(!in_array($posted,$related))

	           $related[]=$posted;

	        Yii::app()->user->setState('related',$related);

	        

	        $relationProvider=new CArrayDataProvider(Yii::app()->user->getState('related'));

		$relationProvider->keyField=false;

	   }

		

	   If(isset($_POST['n_id']) && Yii::app()->request->getIsAjaxRequest())

	   {

		$arr=Yii::app()->user->getState("related");	

		$post=$_POST;

		$list=array();

		foreach($arr as $a)

                {

			if ($a!==$post)

			  $list[]=$a;

		}

		Yii::app()->user->setState('related',$list);

		$relationProvider=new CArrayDataProvider(Yii::app()->user->getState('related'));

		$relationProvider->keyField=false;

          }

		

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

			'model'=>$model,

			'relationProvider'=>$relationProvider

		));

}


public function actionSave()

{

		$relations=Yii::app()->user->getState("related");

		foreach($relations as $relation)

                {

			$model=new Relation;

			$model->n_id=$relation["n_id"];

			$model->s_id=$relation["s_id"];

			$model->c_id=$relation["c_id"];

			if(!Relation::model()->exists("n_id=:n_id AND s_id=:s_id AND c_id=:c_id",array(":n_id"=>$model->n_id,":s_id"=>$model->s_id,":c_id"=>$model->c_id)))

			    $model->save(false);

	        }

		Yii::app()->user->setState('related',null);

		$this->redirect(array("relation/index"));

}



Note here I have used session for temporary storage.

Still I prefer tables for storing the data ,Which can be modified or dropped if needed.

This is the screenshot from my localhost.

3752

assort.png

Regards.

Seeni, you are the best!!!

I have adapted your code to me, and it works perfectly.

I still have some details to polish, but as soon as I have finished I will post the code and I’ll add [solved] to the title of my post.

Thanks a lot.

Well, I’ve already solved the problem.

Thanks to the seenivasan code I did it, but I’ve changed a lot.

Then, if someone needs it, you can ask me.

Regrds.