user5469526 user5469526 - 2 months ago 29
MySQL Question

Dynamic Form with Dependent drop down

Hey Developers i'm building a application form where the user input data into the different fields. One part of the application is a dynamic form from https://github.com/wbraganca/yii2-dynamicform. Now inside the dynamic form i have a dependent drop down but when i click the [+] sign the dependent drop down change data on the first row and not the second.

Here's my code.

in my controller

public function actionLists($name)
{
$countHs= Hs::find()
->where(['hscode'=> $name])
->count();
$Hs = Hs::find()
->where(['hscode'=> $name])
->all();
if($countHs > 0)
{
foreach ($Hs as $H)
{
echo "<option value='".$H->hsproduct."'> ".$H->hsproduct."</option>";


}
}else{
echo "<option> - </option>";
}


}


and my form

<div class="col-sm-6" style="width: 135px">
<?= $form->field($modelsItems, "[{$i}]hscode")->dropDownList(
ArrayHelper::map(Hs::find()->all(),'hscode','hsproduct'),

[


'prompt'=>'',

'onchange'=>

'$.get( "'.Url::toRoute('/hs/lists').'", { name: $(this).val() })
.done(function( data ) { $( "#'.Html::getInputId($modelsItems, "[{$i}]hsproduct").'" ).html( data ); } );'

])->label('HS.Code');


?>

</div>
<div class="col-sm-6" style="width: 135px">
<?= $form->field($modelsItems, "[{$i}]hsproduct")->dropDownList(
ArrayHelper::map(Hs::find()->all(),'hsproduct','hsproduct'),
[
'prompt'=>'',
])->label('HS.Product');
?>
</div>


Im a newbie sorry for my english

Answer

Updated for your case.

What I did was I declared global variable in JS file var i and assigned 0. After the first event is fired, I increase variable i by one. Now it contains 1 in memory. Next time it will take 1 and add 1 again. And so on:

var i = 0;

$(document).on('change', 'select', function(e) {
    i++;
})

Note that this will only work if you choose in each row just once and you will not come back to specific row. If you want to do something like that, you should instead get element ID's number, parse to float (instead of string) and use that number to your event script.

parseFloat($('#hs-0-hscode')[0].id.split('-')[1])

Leaving below one additional solution (but not according to yours). Just in case.


Use Inspect source and find how your input fields are named (name or ID). Let's say, we have name="hs-0-hscode". This is for just Then your jQuery:

$(document).on('change', 'select', function(e) {
    if ($(this)[0].id.indexOf('hscode') > 0) {
        // Now you can use Ajax to get a list of items you want to show.
        // Element itself can be reached: $(this).parent().parent().parent().children().eq(1);
        // For example:
        // var data = $.parseJSON(results);
        // $.each(data, function(key, value) {
        //    $('#client-company_size')
        //        .append($("<option></option>")
        //        .attr("value", key)
        //        .text(value)); 
        // });
    }
});