Collecting Tabular Input - best practices

In section 3.5 of the Yii guide an example is given on how to collect tabular input from a form.

The way it’s done, with items collected and updated by a numerical index, strikes me as not very safe. It can lead to messed up data in the case the underlying set changes between displaying and updating the data.

Unless you index the tabular array by primary key you can never be sure that the model you’re updating is the one that you intended to update in your form.

Maybe it’s written like this for the sake of simplicity but, if most people are like me, we tend to resort to the guide quite literally. In this case, I think at least it should be noted that in a real-world application you would index and update your data based on primary key.

What I’ve ended up doing is something like:

public function actionBatchUpdate()


	// retrieve items to be updated in a batch mode

	// assuming each item is of model class 'Item'



	//index models by pk

	$items = array();

	foreach ($models as $item) 

		$items[$item->id] = $item;


	if(isset($ POST['Item']))



		foreach($items as $id=>$item)


			if(isset($ POST['Item'][$id]))

				$item->attributes=$ POST['Item'][$id];

			$valid=$item->validate() && $valid;


		if($valid) // all items are valid

			// something here


	// displays the view to collect tabular input



Just learnt that you can actually retrieve active records as an indexed array:

$items = Item::model()->findAll(array('index'=>'id'));			

So, if I’m not mistaken, that would be the proper way to fetch records for updating tabular input…