Search code examples
javascriptphpmongodbyii2active-form

According to the dropdown value, change the label name and value of an attribute in yii2 activeform


My active form :

dropdown

<?php
if($model->userType!="VENDOR" && $model->userType!="COMPANY"){
    echo $form->field($model, 'fixedOrPercentagevendor')->dropDownList([0=>'Percentage',1=>'Amount']);

}
?>

I need to get it done with onchange,

when I choose Percentage, it should show

<?= $form->field($model, 'vendorcommision')->label('Vendor Fee (%)')->textInput(['type' => 'number','value'=>'20', 'id'=>'percentage']); ?>

when I choose Amount, it should show

<?= $form->field($model, 'vendorcommision')->label('Vendor Fee (LKR)')->textInput(['type' => 'number','value'=>'1000','id'=>'amount']); }?>

Please Note that both dropdown options render the same attribute vendorcommision in the model and only the label names and values are different.

Thanks in advance.


Solution

  • Resolved my issue.

    <?php
    if($model->userType!="ADMIN" && $model->userType!="HOST"){
        echo $form->field($model, 'fixedOrPercentagevendor')->dropDownList([0=>'Amount',1=>'Percentage'],
                [
                    'onchange'=>'if($(this).val() == 1){
                        $("#percentage").val("20");
                        $("#ftype").html("Vendor Fee (%)");
                        }
                        else{
                        $("#percentage").val("1000");
                        $("#ftype").html("Vendor Fee (LKR)");}'
                ]);
    
        echo $form->field($model, 'vendorcommision',['template'=>"{label}\n<div>{input}</div>\n{hint}\n{error}",'labelOptions'=>['label'=>'Vendor Fee','id'=>'ftype']])
                ->textInput(['type' => 'number','id' => 'percentage']);
    }
    ?>