javascript - 在 Yii2 中使用 Javascript 获取隐藏输入字段设置的值

标签 javascript php yii2 active-form

我在ActiveFormview中有一个隐藏的输入字段

<?php $form = ActiveForm::begin(); ?>

    <input type="file" id="i_file" name="uploadfile" value="" onchange="abc()"> 
    <?= $form->field($model, 'path')->hiddenInput() ?>
    <div class="form-group">
        <?= Html::submitButton('submit', ['class' => 'btn btn-primary']) ?>
    </div>
<?php ActiveForm::end(); ?>

我使用 Javascript 设置它的值,如下所示:

<script>
function abc(){
    var tmppath = URL.createObjectURL(event.target.files[0]);
    $("#taskreports-path").val(tmppath);

alert(document.getElementById("taskreports-path").value);
}   
</script>

警报显示该值已成功设置到该字段中。 现在我想要某个 php 变量中该输入字段的值,例如:

$var path = //<?= $form->field($model, 'path')->hiddenInput() ?> this field's value

如何在 Yii2 中做到这一点?

最佳答案

由于您使用模型来构建表单,因此最好也使用模型方法加载数据。

$model = new MyModel();
...
if ($model->load(Yii::$app->request->post())) {
    $model->path; //Your field's value should be loaded here
}

请注意,“path”属性应列在模型规则中,以便通过“load”方法加载。 这是一个例子:

class MyModel extends ActiveRecord
{
   ...
   public function rules()
   {
       return [
           [['path'], 'string'],
           ...
       ];
   }
}

您还可以在此处找到有关验证用户输入的更多详细信息 http://www.yiiframework.com/doc-2.0/guide-input-validation.html

关于javascript - 在 Yii2 中使用 Javascript 获取隐藏输入字段设置的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34565649/

相关文章:

javascript - Angular : defining a module or not

javascript - 尝试创建按钮时出现异常 - 不变违规 : Text strings must be rendered within a <Text> component

javascript - 如何编辑 woocommerce 产品页面?

php - Yii2 delete() 没有主键

linux - 在 yii2 中设置 Gii 权限

具有多个 Controller 的 Yii2 Rest API 额外模式

javascript - 我有多个带有复选框及其值的 <td>。我想更改 <td> 的颜色

php - 我需要在 mongo php 中使用类似查询

php - 每 3 个帖子后添加 div

java - Volley 后数组请求不起作用