How to use a single form to collect data for two or more models?

You are viewing revision #2 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#3) »

Assume we want to use a single HTML form to collect input for both model A and model B, and we want to display input errors (if any) in the same error summary box. We can define the following action code:

public function actionCreate()
{
	$a=new A;
	$b=new B;
	if(isset($_POST['A'], $_POST['B']))
	{
		// populate input data to $a and $b
		$a->attributes=$_POST['A'];
		$b->attributes=$_POST['B'];
		
		// validate BOTH $a and $b
		$valid=$a->validate();
		$valid=$b->validate() && $valid;
		
		if($valid)
		{
			// use false parameter to disable validation
			$a->save(false);
			$b->save(false);
			// ...redirect to another page
		}
	}

	$this->render('create', array(
		'a'=>$a,
		'b'=>$b,
	));
}

And for the create view, we would need the following code,

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

<?php echo CHtml::errorSummary(array($a,$b)); ?>

...input fields for $a, $b...

</form>

The above approach can also be used if we have more than two models to deal with.

[hr]

Now, since version 1.0.3 and the _form.php view things change a litle. Folowing the example, we need to redlclare en the create view the parameters passed to the create view so the _form view can use them. ~~~

Create view

[<?php echo CHtml::link('List',array('list')); ?>] [<?php echo CHtml::link('Manage',array('admin')); ?>]

<?php echo $this->renderPartial('_form', array(

'a'=>$a,'b'=>$b,
'update'=>false,

)); ?> ~~~

And in the _form work as ever (i.e. we can use $a and $b)

88 0
79 followers
Viewed: 353 743 times
Version: Unknown (update)
Category: Tutorials
Written by: qiang
Last updated by: Yang He
Created on: Feb 27, 2009
Last updated: 12 years ago
Update Article

Revisions

View all history

Related Articles