dongwei3866 2017-04-05 17:44
浏览 91

在字段具有初始值时,在Yii2中使用ActiveForm创建表单以填充错误的POST数据

I have set up many forms using ActiveForm with Yii2 and it always populate the fields with the correct $_POST data on errors, however I am having problems doing this with forms that are initially filled with data, such as users who want to update existing values - on submit if they get an error the fields always contain the initial value and not the $_POST value.

Here is an example of my form:

$form = ActiveForm::begin();

<?=$form->field($model, 'site_url', ['inputOptions' => ['value' => Yii::$app->params['settings']['site_url']]]); ?>

ActiveForm::end();

I was hoping Yii would automatically override the initial value since it was a POST and use the value of the model $site_url property, but unfortunately this is not the case.

Is there a easy way to handle this? ... a possible way I thought of was to avoid setting the value via the fields and instead set the model property values to the initial values and then Yii should automatically load those values in and on post it will have the $_POST values.

...unless there an easier/better way?

  • 写回答

2条回答 默认 最新

  • dshdsh2016 2017-04-05 17:50
    关注

    One option would be checking if it has a loaded value, and if not I would then set the value in params:

    $form->field($model, 'site_url', 
        ['inputOptions' => 
          ['value' => (!empty($model->site_url) ? 
            $model->site_url : Yii::$app->params['settings']['site_url']]]);
    
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!