yii2 - model load function does not set some model attributes

你离开我真会死。 提交于 2019-12-23 17:04:21

问题


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.



来源:https://stackoverflow.com/questions/39587538/yii2-model-load-function-does-not-set-some-model-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!