我已经在yii中更新了ajax用于更新模型属性,但似乎模型没有保存在数据库中,并且我在检查模型时没有验证错误
视图
<?php echo CHtml::dropDownList('roomType', $bed->room_type, SiteBed::roomTypes(), array('class' => 'room-types',
'ajax' => array(
'type' => 'POST',
'url' => Yii::app()->createUrl("admission/admit/bedUpdate", 'ajax' => TRUE)),
'data' => array('Bed[room_type]' => 'js:this.value', 'bed_id' => $bed->bed_id),
'update' => '#Bed_room_type'
)
)); ?>
控制器
public function actionBedUpdate()
{
if(!isset($_POST['bed_id']))
throw new CHttpException(400, 'Bad Request');
if(!isset($_POST['Bed']))
throw new CHttpException(400, 'Bad Request');
$model = Bed::model()->findByPk($_POST['bed_id']);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
$model->attributes = $_POST['Bed'];
$model->save();
// throw new CHttpException(422, 'Saving Error');
}
模型规则
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('name, status, price, room_type, house_id', 'required'),
array('status, room_type, house_id', 'numerical', 'integerOnly'=>true),
array('name', 'length', 'max'=>150),
array('description', 'length', 'max'=>500),
array('price', 'length', 'max'=>10),
array('date_created, date_modified', 'length', 'max'=>14),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('bed_id, name, description, status, price, room_type, house_id, date_created, date_modified', 'safe', 'on'=>'search'),
);
}
答案 0 :(得分:2)
我认为您忘记为帖子请求添加csrf令牌
<?php echo CHtml::dropDownList('roomType', $bed->room_type, SiteBed::roomTypes(), array('class' => 'room-types',
'ajax' => array(
'type' => 'POST',
'url' => Yii::app()->createUrl("admission/admit/bedUpdate", 'ajax' => TRUE)),
'data' => array(
'Bed[room_type]' => 'js:this.value',
'bed_id' => $bed->bed_id,
'YII_CSRF_TOKEN' => Yii::app()->request->csrfToken
),
'update' => '#Bed_room_type'
)
)); ?>
答案 1 :(得分:2)
我发现yii生成的jQuery代码是问题所在,我忘了在这里提到我创建了多个CHtml :: dropDownList(&#39; roomType&#39;)因为我在这里使用了GridView,问题是如果dropDownList多次生成,yii将使用下拉元素的id,在这种情况下是roomtype。我认为yii会使用元素类(房间类型)。感谢您的回复