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

You are viewing revision #7 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 (#6)next (#8) »

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(); ?>
//create.php
<?php echo $this->renderPartial('_form', array('a'=>$a,'b'=>$b)); ?>

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

Links

Chinese version

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

Revisions

View all history

Related Articles