简体   繁体   English

Yii2 $ model-> load(Yii :: $ app-> request-> post())不会从表单加载数据

[英]Yii2 $model->load(Yii::$app->request->post()) does not load data from form

When I take out condition to load data it saves it to db, the $_POST gets values but doesnt send them to controller , this way works in my other projects but not here. 当我取出要加载数据的条件时,将其保存到db,$ _POST获得值,但不将其发送到controller,这种方式在我的其他项目中有效,但在这里不行。 If I use if(isset($_POST['money']) && isset($_POST['username'])){ to save data it works but not the load() function. 如果我使用if(isset($_POST['money']) && isset($_POST['username'])){保存数据,它将起作用,但load()函数无效。

Controller 控制者

public function actionSend() {
    $model = new User();
    $model->getErrors();
    if ($model->load(Yii::$app->request->post())) {
        $model->money = 'something';
        $model->username = 'something';
        $model->save();
    }
    return $this->render('send', [
        'model' => $model
    ]);
}

Model 模型

<?php

namespace app\models;
use yii\db\ActiveRecord;

use Yii;

class User extends \yii\db\ActiveRecord {
    public static function tableName() {
        return 'user';
    }

    public function rules() {
        return [
            [['username', 'money'], 'safe'],
            [['username', 'password'], 'string', 'max' => 15],
            [['auth_key', 'access_token'], 'string', 'max' => 32],
            [['money'], 'string', 'max' => 8],
        ];
    }

    public function attributeLabels() {
        return [
            'id' => 'ID',
            'username' => 'Username',
            'password' => 'Password',
            'auth_key' => 'Auth Key',
            'access_token' => 'Access Token',
            'money' => 'Money',
        ];
    }
}

view 视图

<?php
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
?>

<h2>Send</h2>

<?php $form = ActiveForm::begin([
    'layout' => 'horizontal',
    'fieldConfig' => [
        'template' => "{label}\n<div class=\"col-lg-3\">{input}</div>\n<div class=\"col-lg-8\">{error}</div>",
        'labelOptions' => ['class' => 'col-lg-1 control-label'],
    ],
]); ?>
    <?= $form->field($model, 'username')->textInput(['name' => 'username']) ?>

    <?= $form->field($model, 'money')->textInput(['name' => 'money'])?>

    <div class="form-group">
        <div class="col-lg-offset-1 col-lg-11">
            <?= Html::submitButton('Send', ['class' => 'btn btn-success']) ?>
        </div>
    </div>

<?php ActiveForm::end(); ?>

Change your controller to this 将您的控制器更改为此

public function actionSend() {
    $model = new User();
    $model->getErrors();

    /* set the second parameters of load to empty string */
    if ($model->load(Yii::$app->request->post(), '')) {
        $model->money = 'something';
        $model->username = 'something';
        $model->save();
    }
    return $this->render('send', [
        'model' => $model
    ]);
}

If you review the implementation of load method, you would find that load takes two parameters, the first is the data you want to assign, the second is the data's prefix name. 如果查看load方法的实现,您会发现load有两个参数,第一个是要分配的数据,第二个是数据的前缀名称。

Let's look at an example to illustrate the usage of the second parameter. 让我们看一个示例来说明第二个参数的用法。 (We assume that your formname is User ) (我们假设您的表单名是User

$data1 = [
    'username' => 'sam',
    'money' => 100
];

$data2 = [
    'User' => [
        'username' => 'sam',
        'money' => 100
    ],
],

// if you want to load $data1, you have to do like this
$model->load($data1, '');

// if you want to load $data2, you have to do like this
$model->load($data2);

// either one of the two ways, the result is the same.
echo $model->username;    // sam
echo $model->money;       // 100

Hope it would be helpful. 希望对您有所帮助。

Let's Look The Below Example: Validate Objects or Array key with value with mode 让我们看下面的示例:使用mode值验证对象或数组键

//CONVERT OBJECT TO ARRAY
        $model_data = \yii\helpers\ArrayHelper::toArray($json);

Array
(
    [device_id] => abcd
    [device_type] => android
    [c_id] => 38   
    [device_for] => rent   
    [area_id] => 1
    [city_id] => 1
)

Let's Load Array Data to Model 让我们将数组数据加载到模型中

//LOAD POST DATA IN MODEL
$model->setAttributes($model_data);



if ($model->validate()) {

}else{

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Yii2中$ model-&gt; load()安全吗? - Is $model->load() in Yii2 is safe? Yii2:$ model-&gt; load()返回false - Yii2: $model->load() returns false Yii2 rest api getBodyParams() 无法获取参数加载(Yii::$app-&gt;getRequest()');getBodyPar 来自反应原生帖子 - Yii2 rest api getBodyParams() can't get params load(Yii::$app->getRequest()->getBodyParams(), ''); from react native post Yii2:Yii :: $ app-&gt; request-&gt; queryParams为foreach()提供的参数无效 - Yii2: Yii::$app->request->queryParams Invalid argument supplied for foreach() Yii2 Yii::$app-&gt;request-&gt;userIP 在 ELB 下没有给出正确的 IP 地址 - Yii2 Yii::$app->request->userIP is not giving right IP address under ELB Yii 2-使用$ _POST和Yii :: $ app-&gt; request-&gt; post()之间的区别 - Yii 2 - Difference between using $_POST and Yii::$app->request->post() Yii2 在 `$this-&gt;modelClass::find()-&gt;andWhere([&#39;post_id&#39; =&gt; \\Yii::$app-&gt;request-&gt;get(&#39;postId&#39;)])` 上出现语法错误,这是一个有效条款 - Yii2 Getting a Syntax error on ` $this->modelClass::find()->andWhere(['post_id' => \Yii::$app->request->get('postId')])` which is a valid clause Yii :: $ app&gt; request-&gt; post()是否清除$ _POST变量? - Does Yii::$app>request->post() clean $_POST variables? 无法加载表单 yii2 - Cannot load form yii2 问:Yii2从数据库加载数据 - Q: Yii2 load data from database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM