Yii2: Validations When Updating Form

0

I happened to comment I made a form with their respective validations, at the time of writing the username in the form, this validates if the user already exists and in that case reports the error. When the form is to add a user, the validation works perfect, what I do not know how to do is the validation when updating the form, because what happens? If I update the user's last name and in the username field I leave it as it is, the error that the user already exists jumps, but in reality that user is the one I am updating at that moment, I explain?

Here I leave the code:

class FormUpdateUser extends model{

public $nombre;
public $apellido;
public $usuario;
public $nombre_local;
public $direccion_local;
public $localidad_local;
public $banner;
public $email;
public $telefono_usuario;
public $telefono_local_primario;
public $telefono_local_secundario;

public function rules()
{
    return [
        [['nombre','apellido','usuario','nombre_local','direccion_local','localidad_local','email'], 'required', 'message' => 'Campo requerido'],
        ['nombre', 'match', 'pattern' => "/^[a-z]+$/i", 'message' => 'Sólo se aceptan letras'],
        ['nombre', 'match', 'pattern' => "/^.{3,50}$/", 'message' => 'Mínimo 3 y máximo 50 caracteres'],
        ['apellido', 'match', 'pattern' => "/^[a-z]+$/i", 'message' => 'Sólo se aceptan letras'],
        ['apellido', 'match', 'pattern' => "/^.{3,50}$/", 'message' => 'Mínimo 3 y máximo 50 caracteres'],
        ['usuario', 'match', 'pattern' => "/^.{3,50}$/", 'message' => 'Mínimo 3 y máximo 50 caracteres'],
        ['usuario', 'match', 'pattern' => "/^[0-9a-z]+$/i", 'message' => 'Sólo se aceptan letras y números'],
        ['usuario', 'usuario_existe'],
        ['nombre_local', 'local_existe'],
        ['banner', 'file',
            'skipOnEmpty' => false,
            'uploadRequired' => 'Banner obligatorio', //Error
            'maxSize' => 10240*10240*1, //10 MB
            'tooBig' => 'El tamaño máximo permitido es 10MB', //Error
            'minSize' => 10, //10 Bytes
            'tooSmall' => 'El tamaño mínimo permitido son 10 BYTES', //Error
            'extensions' => 'jpg, png',
            'wrongExtension' => 'El archivo {file} no contiene una extensión permitida {extensions}', //Error
        ],
        ['email', 'match', 'pattern' => "/^.{5,80}$/", 'message' => 'Mínimo 5 y máximo 80 caracteres'],
        ['email', 'email', 'message' => 'Formato no válido'],
        ['email', 'email_existe'],
        ['email', 'trim'],
        ['telefono_usuario', 'match', 'pattern' => "/^[0-9]{6,30}+$/i", 'message' => 'Escribe un número válido'],
        ['telefono_local_primario', 'match', 'pattern' => "/^[0-9]{6,30}+$/i", 'message' => 'Escribe un número válido'],
        ['telefono_local_secundario', 'match', 'pattern' => "/^[0-9]{6,30}+$/i", 'message' => 'Escribe un número válido'],
    ];
}

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 usuario_existe($attribute, $params)
{
    //Buscar el usuario en la tabla
    $table = Users::find()->where("username=:username", [":username" => $this->usuario]);

    //Si el username existe mostrar el error
    if ($table->count() == 1)
    {
        $this->addError($attribute, "El usuario seleccionado existe");
    }
}

public function local_existe($attribute, $params)
{
    //Buscar local en la tabla
    $table = Locales::find()->where("nombre=:nombre", [":nombre" => $this->nombre_local]);

    //Si el username existe mostrar el error
    if ($table->count() == 1)
    {
        $this->addError($attribute, "Este local ya existe");
    }
}

These are my validations, what I do not know is how I can validate if the user exists but without taking into account the current user.

Let's give an example:

I have a user whose name is "pepe", his surname "mengano" and his username "pmengano". I enter to update it and I only update the last name, but the user field will keep saying "pmengano", well I want to update when updating without any problem and not skip the error "this user already exists" in the user field.

    
asked by Majes7ik 04.07.2018 в 07:53
source

1 answer

0

For this purpose, there are scenarios, link

With it you will indicate when you want a validation rule to act, in your case it will only act when creating a user. For this you must:

1- In the model create a constant called SCENARIO_REGISTER for example

2- Place it in the validation rule you want

3- Finally add the stage to the model in the action you want

public function actionCreate()
{
    $model = new Usuarios();
    $model->scenario = Usuarios::ESCENARIO_CREAR;
    
answered by 05.09.2018 / 17:53
source