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'
$models=$this->getItemsToUpdate();
//index models by pk
$items = array();
foreach ($models as $item)
$items[$item->id] = $item;
if(isset($ POST['Item']))
{
$valid=true;
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
// ...do something here
}
// displays the view to collect tabular input
$this->render('batchUpdate',array('items'=>$items));
}