Difference between #4 and #3 of CJuiDialog for create new model

unchanged
Title
CJuiDialog for create new model
unchanged
Category
Tutorials
unchanged
Tags
juidialog, user interface, AJAX
changed
Content
Introduction
------------------

In this tutorial we will learn how to realize a create interface using a dialog.

[Here](http://www.yiiframework.com/wiki/72/cjuidialog-and-ajaxsubmitbutton
"other tutorial") there is a similar tutorial that uses
ajaxAjax link for achiveto achieve
the goal, but here we will use a
simpliersimpler and more effective approach: the event
onSubmit of the form.

Scenario
------------------

Let's immagine thatimagine we have a
classclassroom with many students. If the user
fillfills in the form of the
stundentstudent and there is not the
class,no classroom made, he haswill have
to create a class first, so loosingclassroom first and
lose the input already inserted.inserted
input.

We want to allow the user to insertcreate the class
inclassroom from the form of the
students,student, without changing
page.pages.

Preparation of the form
------------------

First of all we need a form for instertcreating the
class.classroom. We can generate a Crud for
classclassroom with gii and adapt the code to our needs.

Once we are satisfacted ofsatisfied with our form
thatand it works with the usual submit, we can
use it in a dialog.

Enhance the action create
------------------

We need now to enhance the action create of the
classclassroom controller.

Let's change init this way:



~~~
[php]
	public function actionCreate()
	{
		$model=new Classs;Classroom;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Classs']))		if(isset($_POST['Classroom']))
		{
			$model->attributes=$_POST['Classs'];			$model->attributes=$_POST['Classroom'];
			if($model->save())
			{
				if (Yii::app()->request->isAjaxRequest)
				{
					echo CJSON::encode(array(
						'status'=>'success', 
						'div'=>"Class						'div'=>"Classroom
successfully added"
						));
					exit;				
				}
				else
					$this->redirect(array('view','id'=>$model->id));
			}
		}
		
		if (Yii::app()->request->isAjaxRequest)
		{
			echo CJSON::encode(array(
				'status'=>'failure', 
				'div'=>$this->renderPartial('_form', array('model'=>$model),
true)));
			exit;				
		}
		else
			$this->render('create',array('model'=>$model,));
	}
~~~

We add some small changes: in case of ajax request we write a json encoded
array.

In this array we return a status (failure/success) and the whole form created
with renderPartial.

The dialog
------------------

Now the backendback-end is done, let's write the dialog
itself.

In the form of the student someweresomewhere we add this
code:



~~~
[php]

<?php echo CHtml::link('Create class',classroom',
"",  // the link for open the dialog
	array(
		'style'=>'cursor: pointer; text-decoration: underline;',
		'onclick'=>"{addClass();
$('#dialogClass').dialog('open');}"));?>		'onclick'=>"{addClassroom();
$('#dialogClassroom').dialog('open');}"));?>

<?php
$this->beginWidget('zii.widgets.jui.CJuiDialog', array( // the dialog
    'id'=>'dialogClass','id'=>'dialogClassroom',
    'options'=>array(
        'title'=>'Create class',classroom',
        'autoOpen'=>false,
        'modal'=>true,
		'width'=>550,
		'height'=>470,
    ),
));?>
<div class="divForForm"></div>

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

<script type="text/javascript">
// here is the magic
function addClass()addClassroom()
{
	<?php echo CHtml::ajax(array(
			'url'=>array('classs/create'),			'url'=>array('classroom/create'),
			'data'=> "js:$(this).serialize()",
			'type'=>'post',
			'dataType'=>'json',
			'success'=>"function(data)
			{
				if (data.status == 'failure')
				{
					$('#dialogClass					$('#dialogClassroom
div.divForForm').html(data.div);
                          // Here is the trick: on submit-> once again this
function!
					$('#dialogClass					$('#dialogClassroom
div.divForForm
form').submit(addClass);form').submit(addClassroom);
				}
				else
				{
					$('#dialogClass					$('#dialogClassroom
div.divForForm').html(data.div);
					setTimeout(\"$('#dialogClass').dialog('close')
					setTimeout(\"$('#dialogClassroom').dialog('close')
\",3000);
				}
				
			} ",
			))?>;
	return false; 
	
}

</script>
~~~


And that's all. In this code we have:

- A link for open the dialog
- the dialog itself, with a div inside that will be replaced with ajax
- the javascript function addClass().addClassroom().

This function fires an ajax request to the action create we prepared in the
previous step.

The returned form will be placed in the dialog (with eventually, all errors and
so on) in case of status failure, in case of status success in the example we
replace the div and we close the dialog after 3 seconds.

If you use this system in the form for student, you can return, for example, the
id of the newly inserted classclassroom and select it
authomaticallyautomatically in a ddl.drop
down list.

Summary
------------------

For make a long story short:

- Prepare the usual creation with gii generated code
- Change the action create for answer to ajaxAjax requests
- Place the link/dialog/js wherever you want.

This methodology is very confortablecomfortable because it
changes anything in the code of the _form, so any
evenutallyeventually added field in
classclassroom will be available in both standard and
dialog insert.