Yii Framework Forum

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


(Juan Carlos Reyes Suazo) #5

which output? :scream:


(Mehdi Achour) #6

Change this:

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

to

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

tell me what it displays


(Juan Carlos Reyes Suazo) #7

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


(Mehdi Achour) #8

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 ‘==’


(Juan Carlos Reyes Suazo) #9

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


(Mehdi Achour) #10

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


(Juan Carlos Reyes Suazo) #11

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?


(Softark) #13

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

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

(Juan Carlos Reyes Suazo) #14

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


(Juan Carlos Reyes Suazo) #15

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


(Softark) #16

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']); ?>

(Juan Carlos Reyes Suazo) #17

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


(Juan Carlos Reyes Suazo) #18

I’ve already did that


(Softark) #19

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

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

(Juan Carlos Reyes Suazo) #20

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) { }

(Softark) #21
// 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?


(Juan Carlos Reyes Suazo) #22

My FormRegister.php

<?php

namespace app\models;
use Yii;
use yii\base\Model;
use app\models\Users;


class FormRegister extends model{
 
    public $role;
    public $nombre;
    public $rut;
    public $fono;
    public $direccion;
    public $email;
    public $id_curso;
    public $id_alumno;
    public $apoderado_sup;
    public $fono_apoderado_sup;
    public $email_apoderado_sup;
    public $username;
    public $password;
    public $password_repeat;
    public $id_apoderado;
    public $id_profesor;
    
    
    
    public function rules()
    {
        return [
            [['role', 'username', 'email', 'password', 'password_repeat'], 'required', 'message' => 'Campo requerido'],
            [['nombre', 'rut', 'fono', 'direccion'], 'required', 'message' => 'Campo requerido'],
            ['email', 'match', 'pattern' => "/^.{5,80}$/", 'message' => 'Mínimo 5 y máximo 80 caracteres'],
            ['email', 'email', 'message' => 'Formato no válido'],
            ['email', 'email_existe'],
            [['id_curso', 'id_alumno', 'nombre'], 'required', 'message' => 'Campo requerido'],
//            [['apoderado_sup', 'fono_apoderado_sup', 'email_apoderado_sup'], 'required', 'message' => 'Campo requerido'],
            ['username', 'match', 'pattern' => "/^.{3,50}$/", 'message' => 'Mínimo 3 y máximo 50 caracteres'],
            ['username', 'match', 'pattern' => "/^[0-9a-z]+$/i", 'message' => 'Sólo se aceptan letras y números'],
            ['username', 'username_existe'],
            ['password', 'match', 'pattern' => "/^.{6,16}$/", 'message' => 'Mínimo 6 y máximo 16 caracteres'],
            ['password_repeat', 'compare', 'compareAttribute' => 'password', 'message' => 'Los passwords no coinciden'],
        ];
    }
    
    public function email_existe($attribute, $params)
    {
  
        //Buscar el email en la tabla
        $table = Users::find()->where("email=:email", [":email" => $this->email]);
  
        //Si el email existe mostrar el error
        if ($table->count() == 1)
        {
            $this->addError($attribute, "El email seleccionado existe");
        }
    }
 
    public function username_existe($attribute, $params)
    {
        //Buscar el username en la tabla
        $table = Users::find()->where("username=:username", [":username" => $this->username]);
  
        //Si el username existe mostrar el error
        if ($table->count() == 1)
        {
            $this->addError($attribute, "El usuario seleccionado existe");
        }
    }
    
    public function attributeLabels()
    {
        return[
            'role' => 'Tipo de Usuario',
            'nombre' => 'Nombre',
            'rut' => 'Rut',
            'fono' => 'Fono',
            'direccion' => 'Dirección',
            'email' => 'Email',
            'id_curso' => 'Curso',
            'id_alumno' => 'Alumno',
            'apoderado_sup' => 'Apoderado Suplente',
            'fono_apoderado_sup' => 'Fono Apoderado Suplente',
            'email_apoderado_sup' => 'Email Apoderado Suplente',
            'username' => 'Nombre de Usuario',
            'password' => 'Contraseña',
            'password_repeat' => 'Repetir contraseña',
        ];
    }
 
}

(Softark) #23

Probably you have to add in validator for role.

    public function rules()
    {
        return [
            [['role', 'username', 'email', 'password', 'password_repeat'], 'required', 'message' => 'Campo requerido'],
            ['role', 'in', 'range' => [1,2]],
            ...

https://www.yiiframework.com/doc/guide/2.0/en/tutorial-core-validators#in


(Juan Carlos Reyes Suazo) #24

Thank you for your time my friend, but it didn’t work.


(Juan Carlos Reyes Suazo) #25

@softark @machour I also tried this with no success

SiteController.php

if (in_array('1', $model->role)){
$apoderado = new Apoderado;
...
$apoderado->save();
} elseif (in_array('2', $model->role)) {
$profesor = new Profesor;
...
$profesor->save();
}

register.php

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