Dropdown value with array data wont work in if condition (user role) [solved]

Hey folks, I got this problem.

It always create the profesor object when I do if ($model->role === ‘1’)
It jumps directly to the else statement

SiteController.php

public function actionRegister()
    {
        //Creamos la instancia con el model de validación
        $model = new FormRegister;
        //Mostrará un mensaje en la vista cuando el usuario se haya registrado
        $msg = null;
   
        //Validación mediante ajax
        if ($model->load(Yii::$app->request->post()) && Yii::$app->request->isAjax)
        {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
   
        //Validación cuando el formulario es enviado vía post
        //Esto sucede cuando la validación ajax se ha llevado a cabo correctamente
        //También previene por si el usuario tiene desactivado javascript y la
        //validación mediante ajax no puede ser llevada a cabo
        if ($model->load(Yii::$app->request->post()))
        {
            if($model->validate())
            {
                //Preparamos la consulta para guardar el usuario
                $table = new Users;
                $table->role = $model->role;
                $table->username = $model->username;
                //Encriptamos el password
                $table->password = crypt($model->password, Yii::$app->params["salt"]);
                //Creamos una cookie para autenticar al usuario cuando decida recordar la sesión, esta misma
                //clave será utilizada para activar el usuario
                $table->authKey = $this->randKey("abcdef0123456789", 200);
                //Creamos un token de acceso único para el usuario
                $table->accessToken = $this->randKey("abcdef0123456789", 200);
                $table->email = $model->email;
                if($model->role === 1){
                    $apoderado = new Apoderado;
                    $apoderado->nombre = $model->nombre;
                    $apoderado->rut = $model->rut;
                    $apoderado->fono = $model->fono;
                    $apoderado->direccion = $model->direccion;
                    $apoderado->email = $model->email;
                    $apoderado->id_alumno = $model->id_alumno;
                    $apoderado->apoderado_sup = $model->apoderado_sup;
                    $apoderado->fono_apoderado_sup = $model->fono_apoderado_sup;
                    $apoderado->email_apoderado_sup = $model->email_apoderado_sup;
                    $apoderado->save();
                } else {
                    $profesor = new Profesor;
                    $profesor->nombre = $model->nombre;
                    $profesor->rut = $model->rut;
                    $profesor->fono = $model->fono;
                    $profesor->direccion = $model->direccion;
                    $profesor->email = $model->email;
                    $profesor->save();
                }
                $table->id_apoderado = $model->id_apoderado;
                $table->id_profesor = $model->id_profesor;
     
                //Si el registro es guardado correctamente
                if ($table->insert())
                {
                    //Nueva consulta para obtener el id del usuario
                    //Para confirmar al usuario se requiere su id y su authKey
                    $user = $table->find()->where(["email" => $model->email])->one();
                    $id = urlencode($user->id);
                    $authKey = urlencode($user->authKey);
      
                    $subject = "Confirmar registro";
                    $body = "<h1>Haga click en el siguiente enlace para finalizar tu registro</h1>";
                    $body .= "<a href='http://localhost:8080/sie2gii/web/index.php?r=site/confirm&id=".$id."&authKey=".$authKey."'>Confirmar</a>";
      
                    //Enviamos el correo
                    Yii::$app->mailer->compose()
                        ->setTo($user->email)
                        ->setFrom([Yii::$app->params["adminEmail"] => Yii::$app->params["title"]])
                        ->setSubject($subject)
                        ->setHtmlBody($body)
                        ->send();
     
                    $model->username = null;
                    $model->email = null;
                    $model->password = null;
                    $model->password_repeat = null;
     
                    $msg = "Enhorabuena, ahora sólo falta que confirmes tu registro en tu cuenta de correo";
                }
                else
                {
                    $msg = "Ha ocurrido un error al llevar a cabo tu registro";
                }
            }
            else
            {
                $model->getErrors();
            }
        }
        return $this->render("register", ["model" => $model, "msg" => $msg,]);

Here’s the dropdownlist in the view
register.php

<div class="form-group">
    <?= $form->field($model, 'role[]')->dropDownList(
            ['1' => 'Apoderado', '2' => 'Profesor'], 
            ['prompt' => 'Seleccione tipo de usuario']); ?>
</div>

Try to var_dump($model->role); before your if.
I think that you will see a string, but you’re doing a type-strict comparison against an integer.

@machour I tried your solution and it doesn’t do the job

What do you mean? What’s the output of the var_dump() ?

which output? :scream:

Change this:

if($model->role === 1){

to

var_dump($model->role);die;
if($model->role === 1){

tell me what it displays

array(1) { [0]=> string(1) “1” }

you are comparing array("1") to 1, it can’t work.
check what your form is sending to understand why it’s array("1") instead of 1.
Then, as it’s a string, change your if from ‘===’ to ‘==’

I changed the dropdownlist to

<div class="form-group">
    <?= $form->field($model, 'role')->dropDownList(
            ['1' => 'Apoderado', '2' => 'Profesor'], 
            ['prompt' => 'Seleccione tipo de usuario']); ?>
</div>

and if to

if($model->role == '1'){

and the output changed to

string(1) "1"

but it still doesn’t work

You should remove the var_dump(…); die; line now

I know, I did. But as I said it still doesn’t work. Anyways I thank you for your help. @softark can you help me?

I would use == instead of === as @machour suggested.

if ($model->role == 1) {
   ...

@softark thank you for your answer. it doesn’t do the job. what else can I try?

I also tried this

switch ($model->role){
                    case 1:
                    $apoderado = new Apoderado;
                    $apoderado->nombre = $model->nombre;
                    $apoderado->rut = $model->rut;
                    $apoderado->fono = $model->fono;
                    $apoderado->direccion = $model->direccion;
                    $apoderado->email = $model->email;
                    $apoderado->id_alumno = $model->id_alumno;
                    $apoderado->apoderado_sup = $model->apoderado_sup;
                    $apoderado->fono_apoderado_sup = $model->fono_apoderado_sup;
                    $apoderado->email_apoderado_sup = $model->email_apoderado_sup;
                    $apoderado->save();
                    break;
                    case 2:
                    $profesor = new Profesor;
                    $profesor->nombre = $model->nombre;
                    $profesor->rut = $model->rut;
                    $profesor->fono = $model->fono;
                    $profesor->direccion = $model->direccion;
                    $profesor->email = $model->email;
                    $profesor->save();
                    break;

but it doesn’t work either

What exactly do you mean by “doesn’t work”?

Ah, OK.
Your form has an error:

   <?= $form->field($model, 'role[]')->dropDownList(
           ['1' => 'Apoderado', '2' => 'Profesor'], 
           ['prompt' => 'Seleccione tipo de usuario']); ?>

Just role instead of role[].

    <?= $form->field($model, 'role')->dropDownList(
            ['1' => 'Apoderado', '2' => 'Profesor'], 
            ['prompt' => 'Seleccione tipo de usuario']); ?>

when I select ‘apoderado’ in the dropdown it doesn’t create a record in table apoderado

I’ve already did that

You can check the error to see what’s happening.

$ret = $apoderado->save();
if (!$ret) {
   var_dump($model->errors());
}

I did this

if ($model->role == '1'){
                    $apoderado = new Apoderado;
                    $apoderado->nombre = $model->nombre;
                    $apoderado->rut = $model->rut;
                    $apoderado->fono = $model->fono;
                    $apoderado->direccion = $model->direccion;
                    $apoderado->email = $model->email;
                    $apoderado->id_alumno = $model->id_alumno;
                    $apoderado->apoderado_sup = $model->apoderado_sup;
                    $apoderado->fono_apoderado_sup = $model->fono_apoderado_sup;
                    $apoderado->email_apoderado_sup = $model->email_apoderado_sup;
                    $apoderado->save();
                } else {
                    $profesor = new Profesor;
                    $profesor->nombre = $model->nombre;
                    $profesor->rut = $model->rut;
                    $profesor->fono = $model->fono;
                    $profesor->direccion = $model->direccion;
                    $profesor->email = $model->email;
                    $profesor->save();
                }
var_dump($model->getErrors()); die;

and it returns

array(0) { }
// check what's in $model->role
var_dump($model->role);
if ($model->role == 1 ) {
    ...
    // save apoderado
} elseif ($model->role == 2) {
   ...
   // save profesor
} else {
   // check what's happening
   var_dump($model->role);
}

And would you please show us your code for FormRegister model?