简体   繁体   中英

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. If I use if(isset($_POST['money']) && isset($_POST['username'])){ to save data it works but not the load() function.

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.

Let's look at an example to illustrate the usage of the second parameter. (We assume that your formname is 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

//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{

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM