How to validate multiple rows of the same Model with CActiveForm?

[color="#222222"][font="arial, sans-serif"][size="2"]is there a way to do this? In example:[/size][/font][/color]




<div class="row">

   <?php echo $form->label($model,'[0]option'); ?>

   <?php echo $form->textField($model,'[0]option'); ?>

   <?php echo $form->error($model,'[0]option'); ?>

</div>


<div class="row">

   <?php echo $form->label($model,'[1]option'); ?>

   <?php echo $form->textField($model,'[1]option'); ?>

   <?php echo $form->error($model,'[1]option'); ?>

</div>



[color="#222222"][font="arial, sans-serif"][size="2"]

CActiveForm::validate($model), as expected, doesn’t work[/size][/font][/color]

Here’s how you can do it:

$models = $_POST[‘YourModel’];

foreach ($models as $data) {

$model = new YourModel;

$model->setAttributes($data);

if ($model->validate()) {

 //Here its validated..

}

}

this will not work with ajax validation though,

I almost got to where I wanted by using a custom function instead of CActiveForm::validate() which could be part of an extension to CActiveForm


function validate($models, $attributes=null, $loadInput=true)

{

	$result = array();

	if(!is_array($models))

		$models = array($models);


	$post = $_POST;


	foreach($models as $model)

	{

		if (is_array($_POST[get_class($model)])) {

			$validateMultipleModels = array_shift($post[get_class($model)]);

			$validateMultipleModels = is_array($validateMultipleModels);

		}


		if ($validateMultipleModels) {

			foreach ($_POST[get_class($model)] as $key=>$vals) {

				$result = array_merge($result, validate_model($model, $attributes, $loadInput, $key));

			}				

		} else {

			$result = array_merge($result, validate_model($model, $attributes, $loadInput));

		}

	}


	return function_exists('json_encode') ? json_encode($result) : CJSON::encode($result);

}


function validate_model($model, $attributes=null, $loadInput=true, $key=null)

{

	$result = array();


	if ($loadInput) {

		$vals = array();

		if ($key !== null) {

			$vals = isset($_POST[get_class($model)][$key]) ? $_POST[get_class($model)][$key] : null;

		} else {

			$vals = isset($_POST[get_class($model)]) ? $_POST[get_class($model)] : null;

		}

	}


	if($loadInput && $vals) {

		$model->attributes = $vals;

	}


	$model->validate($attributes);


	foreach($model->getErrors() as $attribute=>$errors) {

		if ($key) {

			$attribute = "[$key]$attribute";

		}

		$id = CHtml::activeId($model,$attribute);//won't work for $_POST[model][0]


		$result[$id]=$errors;

	}


	return $result;}

but is there an officially good way to do that?

edit: code wasn’t exactly working, as it is now it works for all fields having their name in the form of “[0]name”

still looking for a more elegant way

starting from yii 1.1.10 there now exists validateTabular

http://www.yiiframework.com/doc/api/1.1/CActiveForm#validateTabular-detail