0

I'm trying to put a value from javascript into a form action in Yii2 is it possible? More specifically I need to make a URL change for each option that is selected in a dropdownList.

form in views/site.php

$form = ActiveForm::begin([
       'id' => 'form',
       'method' => 'POST',
       'action' => Url::to(['programas/'.Tours::findOne(['pk' => ])->programa]),
]); 

<?= $form->field(new \app\models\Tours(), 'nombre')->dropDownList([],
    [
        'prompt' => 'Programa',
        'id' => 'child1_child2',
        'onchange' => 'updateValue(this.value)',
   ]
)->label(false); ?>

Js file

    function updateValue(val){
  x = document.getElementById("test").value;
  // document.getElementById("form").action = "programas/";
}

So, I rescue the value from the selected option with JS but I need to put it in here 'pk' => 'value'

where value is the #child1_child2 selected option value.

'action' => Url::to(['programas/'.Tours::findOne(['pk' =>  ])->programa])

Thanks for the help.

1 Answer 1

1

You can use one of the following approach with some modification:

//pk => programa
$data = [
  1 => 'programa1',
  2 => 'programa2',
  3 => 'programa3',
];

1) Use JS

<?= $form->field(new \app\models\Tours(), 'nombre')->dropDownList($data, ['prompt' => 'Programa'])->label(false); ?>

JS

$this->registerJs('
$("#dropdownID").change(function() {
    var text = $("#dropdownID option:selected").text();
    $("#formID").attr("action", "/pathtoproject/programas/" + text);
});
', \yii\web\View::POS_END);

2) Use Ajax Call

<?= $form->field(new \app\models\Tours(), 'nombre')->dropDownList($data, [
   'prompt' => 'Programa',
    'onchange'=> '$.get( "'.Url::toRoute('get-action').'", { id: $(this).val() } )
       .done(function( data ) {
           $("#formID").attr("action", data); 
       } 
    );'
])->label(false); ?>

Controller

public function actionGetAction($id)
{
   $name = Tours::findOne(['pk' =>  $id])->programa];
   echo \yii\helpers\Url::to(['programas/'.$name]);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.