Rugleh Rugleh - 7 days ago 12
PHP Question

Pass javascript value to a form action URL in Yii2

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.

Answer

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]);
}