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

You are viewing revision #3 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 or see the changes made in this revision.

« previous (#2)next (#4) »

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.

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.

<h2>Create view</h2>

<div class="actionBar">
[<?php echo CHtml::link('List',array('list')); ?>]
[<?php echo CHtml::link('Manage',array('admin')); ?>]
</div>

<?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 756 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