我在下拉菜单中添加了一个用于更新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'),
);
}
解决方法:
我认为您忘记为帖子请求添加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'
)
)); ?>