yii2before-save

yii2 beforeSave with modal dropdownlist


I'm trying to implement a beforeSave function that from a selected modal dropdownlist changes a value to positive or negative number accordingly, but it always change accordingly to the first if:

this is the modal code:

<?= $form->field($model, 'tipo_fatura')->dropDownList([ 'Fatura' => 
'Fatura', 'Nota de Crédito' => 'Nota de Crédito', ], 
    ['prompt' => '']) ?>

and this is the model code:

public function beforeSave($insert)
{
if (!parent::beforeSave($insert)) {
    return false;
}
     $tipo_fatura = $this->tipo_fatura;
     if ($tipo_fatura->index = 2) {
         $this->valor_fatura = 2;            
     } else if ($tipo_fatura = 'Fatura') {
         $this->valor_fatura = 1; 

     } else {

     }

return true;
}

Sorry, about my bad English.

And thank's in advance.


Solution

  • That is because you are assigning value inside if condition, not checking them.

    if ($tipo_fatura->index = 2) {
    

    Notice the = operator here, it should be ==. Same goes for other other conditions too.

    Assigning value is a valid operation and PHP will not throw any error or notice about this. So a good rule of thumb would be to always use the value part on left side in a condition, like this:

    if ( 2 == $test ) {
    
        // do something
    }
    

    In this case even if you mistakenly add a single = here PHP will throw a PHP Parse error because 2 = $test will not be valid operation.