2014-04-24 71 views
2

我做了一個下拉阿賈克斯用於更新警予一個模型屬性,但似乎這種模式是不保存在數據庫中並沒有,而林檢查模型型號不保存在警予

視圖中沒有驗證錯誤

<?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'), 
    ); 
} 
+1

向我們展示您的模型規則,並且像'if(!$ model-> save()){print_r($ model-> getErrors()); ''看看有什麼錯誤。 –

+0

你好我已經做了$ model-> getErrors(),我沒有發現任何錯誤。如果我沒有ajax保存它,它工作正常,但如果我用ajax做它不是 – valrecx

+0

嘗試跳過驗證,使用$ model-> save(false); – Abudayah

回答

1

我想你忘記添加CSRF令牌,你的POST請求

<?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

我發現警予的生成jQuery代碼的問題,我忘了提及的是我創建的多個了CHtml ::下拉列表(」 roomType'),因爲我在這裏使用了GridView,問題是如果dropDownList被多次生成,yii將使用下拉元素的id,在這種情況下是roomtype。我以爲yii會使用元素類(房間類型)來代替。感謝您的回覆