mhplur
mhplur

Reputation: 218

Dependent fields yii2

I need 2 dependent fields in framework Yii2 Example:

2 fields in ActiveForm

I want when i insert in "Numero de Personas"= 5 or other numeric value, automatically "Consumo de Agua"= 2 * "Numero de Personas" = 10. I saw onchange yii2 but i don't know how use it, i think onchange yii2 is an alternative.

<?= $form->field($model, 'NUM_PERSONAS')->textInput(['maxlength' => true]) ?>

<?= $form->field($model, 'AGUA_CONSUMO')->textInput(['maxlength' => true]) ?>

Update:

With 2 calculated fields example:

$("#consumo-form #{$aguaId},#consumo-form #{$personaId}").on("keyup", function (e) {
        var persona = $("#consumo-form #{$personaId}").val();
        var agua = $("#consumo-form #{$aguaId}").val();
        $("#consumo-form #{$indConsumoAguaM}").val(persona*agua)
    });

Upvotes: 2

Views: 1875

Answers (1)

Clyff
Clyff

Reputation: 4076

Here is the approach i would use:

in your view:

<?php
    $personaId = Html::getInputId($model, 'NUM_PERSONAS');
    $aguaId = Html::getInputId($model, 'AGUA_CONSUMO');
?>

    <!-- Begin of form -->
    <?= $form->field($model, 'NUM_PERSONAS')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'AGUA_CONSUMO')->textInput(['maxlength' => true]) ?>
    <!-- End of form -->

<?php
$js = <<<JS
$("#my-form-id #{$personaId}").on("keyup", function (e) {
    var persona = $(this).val();
    $("#my-form-id #{$aguaId}").val(persona*2)
});
$("#my-form-id #{$aguaId}").on("keyup", function (e) {
    var agua = $(this).val()%2 == 0 ? $(this).val() : $(this).val() - 1;
    $("#my-form-id #{$personaId}").val(agua/2)
});
JS;
$this->registerJs($js);

With that, both fields will try to auto-complete after the other being changed. But, just to be safe, we need to add a validation on model's rules also.

In your Model:

public function rules()
{
    return [
        // Your rules 
        [['NUM_PERSONAS', 'AGUA_CONSUMO'], 'checkValues']
    ];
}

public function checkValues($attribute)
{
    $persona = $this->NUM_PERSONAS;
    $agua = $this->AGUA_CONSUMO%2 == 0 ? $this->AGUA_CONSUMO : $this->AGUA_CONSUMO - 1;
    if ($persona != $agua/2) {
        $this->addError($attribute, 'Error message');
    }
}

Upvotes: 3

Related Questions