当我更新表格输入字段表格(用于更新预订表单)和“保存”的表格输入字段之一时,会创建一个新行并更新现有行。任何人都可以指出我哪里错了吗?对于凌乱的代码感到抱歉。
来自预订控制器的getItemsToUpdate函数
public function getItemsToUpdate($id){
// create an empty list of records
$items = array();
// Iterate over each item from the submitted form
if (isset($_POST['BookingRoom']) && is_array($_POST['BookingRoom'])) {
foreach ($_POST['BookingRoom'] as $item) {
// If item id is available, read the record from database
if (( array_key_exists('roomId', $item) ) && ( array_key_exists('startDate', $item) && array_key_exists('endDate', $item) )){
if ((($item['roomId'] != NULL)) && (($item['startDate'] != NULL) && ($item['startDate'] > 0)) &&
(($item['endDate'] != NULL) && ($item['endDate'] > 0))){
$bookingIdExist = array_key_exists('bookingId', $item);
if (!$bookingIdExist) {
$item['bookingId'] = $id;
}
// check if already exists
$BookingRoom = BookingRoom::model()->findByAttributes(array('roomId' => $item['roomId'], 'bookingId' => $id, 'startDate' => $item['startDate'], 'endDate' => $item['endDate']));
// if already exists
if ($BookingRoom){
// append existing item onto items array
$items[] = BookingRoom::model()->findByAttributes(array('roomId' => $item['roomId'], 'bookingId' => $id, 'startDate' => $item['startDate'], 'endDate' => $item['endDate']));
} else if (!$bookingIdExist){
// if it's a new item
$itemNew = new BookingRoom();
$itemNew->attributes = $item;
$items[] = $itemNew;
} else {
// if it's an updated item
$itemNew = new BookingRoom();
$itemNew->attributes = $item;
$items[] = $itemNew;
}
}
}
}
} else {
$items = BookingRoom::model()->findAll('bookingId=:bookingId', array(':bookingId'=>$id));
}
return $items;
}
来自预订控制器的更新操作
public function actionUpdate($id)
{
$baseUrl = Yii::app()->baseUrl;
$cs = Yii::app()->getClientScript();
$cs->registerScriptFile($baseUrl.'/js/functions.js');
if (!isset($_POST['Booking'])) {
$model=$this->loadModel($id);
} else {
$model = $this->loadModel($id);
$model->attributes=$_POST['Booking'];
//$model->update();
}
$items = array();
$items=$this->getItemsToUpdate($id);
if(isset($_POST['BookingRoom']))
{
$valid=true;
foreach($items as $i=>$item)
{
if(isset($_POST['BookingRoom'][$i]))
$item->attributes=$_POST['BookingRoom'][$i];
//var_dump($item->attributes);
$valid=$item->validate() && $valid;
}
$valid=$model->validate() && $valid;
if($valid){
$model->save(false);
foreach($items as $item)
{
$item->save(false);
}
}
}
$this->render('update', array('model'=>$model, 'items'=>$items));
}