-->

yii2 - model load function does not set some model

2019-07-13 07:28发布

问题:

I'm working on a PHP Yii2 application. I have a strange problem with yii2 yii\base\Model.load function. Here is my problem:

I have a form model called PaymentIncreaseBalanceForm like below:

class PaymentIncreaseBalanceForm extends yii\base\Model {
     public $amount;
     public $receiptNumber;
     public $description;
     ...
}

Here is part of my view file:

<?= $form->field($model, 'amount')->textInput(['maxlength' => true]) ?>

<?= $form->field($model, 'receiptNumber')->textInput(['maxlength' => true]) ?>

<?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>

And this is my controller action:

 public function actionIncreaseBalance()
 {
      $modelForm = new PaymentIncreaseBalanceForm();
      if ($modelForm->load(Yii::$app->request->post()))
      {
              //some logic
      }

       return $this->render('increase-balance', [
                'model' => $modelForm,
      ]);
  }

After submitting the form, I logged Yii::$app->request->post() with die() and all three parameters amount, receiptNumber, description exist in the post with their right values(every thing is right). But after calling $modelForm->load function, this is my model attributes:

$amount => 1000,
$receiptNumber => 887412141,
$description => NULL,

$description always is NULL! I don't know what is the problem with this field. Is there any problem with my code?

回答1:

Probably there is no rule added for description attribute in your code.

Check the rules() method to confirm it.

As default, method load() applies only "safe" values to attributes and value is considered "safe" if there is rule for it in the current scenario.



回答2:

Remove $ sign from description <?= $form->field($model, 'description')->textarea(['rows' => 6]) ?> in view file



回答3:

Similar problems often may be caused by "safe attributes" (as say Bizley).

In complex cases with many rules and scenarios you can check current safe attributes via Model::safeAttributes. Execute it immediate before loading data.