How can I make batch update work on my application? It displays item but not able to save changes to database. Please help me.
On my controller:
public function actionBatchUpdate(){
$items=$this->getItemsToUpdate();
if(isset($_POST['MyModel']))
{
$valid=true;
foreach($items as $i=>$item)
{
if(isset($_POST['MyModel'][$i]))
$item->attributes=$_POST['MyModel'][$i];
$valid=$item->validate() && $valid;
if($valid){
$item->save();
echo "Item Saved<br/>";
}
}
}
// displays the view to collect tabular input
$this->render('batchUpdate',array(
'items'=>$items));
}
public function getItemsToUpdate() {
// Create an empty list of records
$items = array();
// Iterate over each item from the submitted form
if (isset($_POST['MyModel']) && is_array($_POST['MyModel'])) {
foreach ($_POST['MyModel'] as $item) {
// If item id is available, read the record from database
if ( array_key_exists('id', $item) ){
$items[] = MyModel::model()->findByPk($item['id']);
}
// Otherwise create a new record
else {
$items[] = new MyModel();
}
}
}
return $items;
}
My batchUpdate view:
<table>
<?php
$criteria=new CDbCriteria;
$criteria->condition='user_id isNull';
$items = MyModel::model()->findAll($criteria);
foreach($items as $i=>$item):
?>
<tr>
<td><?php echo CHtml::activeTextField($item,"[$i]id", array('size' =>'7')); ?></td>
<td><?php echo CHtml::activeTextField($item,"[$i]class_name", array('size' =>'60')); ?></td>
<td><?php echo CHtml::activeDropDownList($item,"[$i]user_id",CHtml::listData(MyModel::model()->findAll(),'user_id','user_id', 'classification')); ?> </td>
</tr>
<?php endforeach; ?>
</table>
<?php echo CHtml::submitButton('Save'); ?>
<?php echo CHtml::endForm(); ?>