我的 $model->load(Yii::$app->request->post() 返回布尔值 (false)

cod*_*kie 0 ajax yii2

谁能告诉我为什么我$model->load(Yii::$app->request->post()返回布尔值 (false) ?我尝试 var_dump $model->load(Yii::$app->request->post(),它肯定有我的输入值(不为空)。

这是我的代码。我正在处理基于Vitalet's x-editable. 该字段将修改tema数据库列的值(tema的模型属性)。我尝试print_r($model->getErrors())在'else'语句中,我得到了 Array ( )

public function actionFetch(){
//There's only a single row in the table.
$model= Home::find()->one();

if (Yii::$app->request->isAjax) {

// use Yii's response format to encode output as JSON
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

// save posted model attributes
if ($model->load(Yii::$app->request->post()) && $model->save()) {

//extract the class name
$modelClassName = \yii\helpers\StringHelper::basename(get_class($model));
//grab the post parameters array (as attribute=>value)
$params = Yii::$app->request->post($modelClassName);
//pull the first value from the array (there should only be one) 
$value = reset($params);

// return JSON encoded output in the below format
return ['output'=>$value, 'message'=>'success'];

} else {
// else if nothing to do always return an empty JSON encoded output
// alternatively you can return a validation error
return ['output'=>'', 'message'=>'fail'];
}
};


}

Run Code Online (Sandbox Code Playgroud)

风景 :

<a href="#" id="tema" name="tema" data-type="text" data-pk=<?=$model->id?> data-url=<?=Url::to(['home/fetch']);?> data-title="Enter username"><?=$model->tema?></a>
Run Code Online (Sandbox Code Playgroud)

我的模型规则:

public function rules()
    {
        return [
            [[ 'id','isiTema', 'image', 'midLeft_title', 'midLeft_content', 'midCenter_title', 'midCenter_content', 'midRight_title', 'midRight_content', 'footerLeft', 'footerRight', 'created_at', 'updated_at'], 'required'],
            [['midLeft_content', 'midCenter_content', 'midRight_content', 'footerLeft', 'footerRight'], 'string'],
            [['id'],'integer'],
            [['created_at', 'updated_at'], 'safe'],
            [['tema', 'isiTema', 'image', 'midLeft_title', 'midCenter_title', 'midRight_title'], 'string', 'max' => 255],
        ];
    }
Run Code Online (Sandbox Code Playgroud)

这是我的var_dump(Yii::$app->request->post())包含:

array(3) {
  ["name"]=>
  string(4) "tema"
  ["value"]=>
  string(5) "aaabb"
  ["pk"]=>
  string(1) "1"
}

Run Code Online (Sandbox Code Playgroud)

我在我的控制器中尝试了这个,但结果仍然是一样的(基本上我认为我不需要,因为它只包含表中的一行):

...
 $pk = $_POST['pk'];

$model=Home::find()->where(['id'=>$pk])->one();
...
...

Run Code Online (Sandbox Code Playgroud)

Biz*_*ley 5

您需要使用load()设置为的第二个参数''来明确声明您的 POST 字段不包括模型名称。

$model->load(Yii::$app->request->post(), '')
Run Code Online (Sandbox Code Playgroud)