alexandernst
alexandernst

Reputation: 15109

Sending error messages to browser after adding them to model

Let's say I have a model that extends CActiveRecord and I add a few errors to that model using $this->addError("foo", "Bar is broken");.

Now let's say I validate my model when the browser sends an AJAX request, like this:

if(isset($_POST['ajax']) && $_POST['ajax']==='user-login-form')
{
    echo CActiveForm::validate($model);
    Yii::app()->end();
}

My question is: ¿How can I send the errors ($model->getErrors() returns an array) to the browser so the Yii code that handles validation errors from CActiveForm will take my errors and show them, without having to modify that client-side code?

=========== EDIT ==========

Login view:

<div class="form">

<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'usuarios-login-form',
    'enableAjaxValidation'=>true,
)); ?>

    <div class="row flush">
        <div class="4u">
            <?php echo $form->labelEx($model,'correo', array(
                'class'=>'pull-right'
            )); ?>
        </div>
        <div class="4u">
            <?php echo $form->textField($model,'correo'); ?>
        </div>
        <div class="4u">
            <?php echo $form->error($model,'correo', array(
                'class'=>'pull-left alert'
            )); ?>
        </div>
    </div>

    <div class="row flush">
        <div class="4u">
            <?php echo $form->labelEx($model,'password', array(
                'class'=>'pull-right'
            )); ?>
        </div>
        <div class="4u">
            <?php echo $form->passwordField($model,'password'); ?>
        </div>
        <div class="4u">
            <?php echo $form->error($model,'password', array(
                'class'=>'pull-left alert'
            )); ?>
        </div>
    </div>

    <div class="row flush">
        <div class="4u">&nbsp;</div>
        <div class="8u">
            <div class="pull-left infotxt">Los campos con <span class="required">*</span> son obligatorios.</div>
        </div>
    </div>

    <div class="row flush">
        <div class="4u">&nbsp;</div>
        <div class="8u">
            <?php echo CHtml::submitButton('Iniciar sesion', array(
                'class'=>'button alt pull-left loginbtn'
            )); ?>
        </div>
    </div>

<?php $this->endWidget(); ?>

</div><!-- form -->

Controller:

public function actionLogin()
{
    $model=new Usuarios('login');

    // if it is ajax validation request
    if(isset($_POST['ajax']) && $_POST['ajax']==='usuarios-login-form')
    {
        echo CActiveForm::validate($model);
        echo $model->login()->getErrors();
        Yii::app()->end();
    }

    if(isset($_POST['Usuarios']))
    {
        $model->attributes=$_POST['Usuarios'];
        if($model->validate() && $model->login()){
            if(Yii::app()->user->getState('type')=='Admin'){
                $this->redirect(array("admin"));
            }elseif(Yii::app()->user->getState('type')=='User'){
                $this->redirect(array("perfil"));
            }
            //$this->redirect(Yii::app()->user->returnUrl);
        }else{
            echo "adadasd";
            echo $model->login();
        }
    }
    $this->render('login',array('model'=>$model));
}

Login method in Usuarios class:

public function login(){
    $identity = new UserIdentity($this->correo, $this->password);
    $res = $identity->authenticate();
    if($res == UserIdentity::ERROR_NONE){
        Yii::app()->user->login($identity, 3600*24*7);
    }else if($res == UserIdentity::ERROR_USERNAME_INVALID){
        $this->addError("correo", "El usuario no existe");
    }else if($res == UserIdentity::ERROR_PASSWORD_INVALID){
        $this->addError("password", "La contraseña es incorrecta");
    }else{
        $this->addError("", "Error desconocido");
    }
    return $this;
}

Upvotes: 0

Views: 68

Answers (1)

Developerium
Developerium

Reputation: 7265

in your model, you can override beforeValidate() and in there check your logic for errors,

protected function beforeValidate()
{
   if($this->foo == 'broken') // check your logic
   {
        $this->addError("foo", "Bar is broken");//error on foo attribute
        return false;
   }

   return parent::beforeValidate(); // keep the chain
}

Upvotes: 1

Related Questions