Choxx
Choxx

Reputation: 945

Getting value of hidden input field set-in using Javascript in Yii2

I have a hidden input field in view in the ActiveForm

<?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(); ?>

I am setting it's value using Javascript as shown below:

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

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

Alert shows that the value is set into the field successfully. Now I want the value of that input field in some php variable like:

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

How can I do that in Yii2?

Upvotes: 0

Views: 1997

Answers (2)

Dmitriy
Dmitriy

Reputation: 168

Since you are using Model to build your form it would be better to load data using Model method also.

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

Note that 'path' attribute should be listed in your Model rules to be loaded by 'load' method. Here is an example:

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

You can also find more details about validating user input here http://www.yiiframework.com/doc-2.0/guide-input-validation.html

Upvotes: 1

Hanafi
Hanafi

Reputation: 151

In your controller action's function, you can get the hidden input's value this way.

$post = Yii::$app->request->post();
$var = $post[$model->formName()]['path'];

Upvotes: 0

Related Questions