Testing for Login button click in CUserIdentity

Hi,

When the ‘enableAjaxValidation’ is set to true for the CActiveForm widget in the auto-generated login.php view, the logic in CUserIdentity::authenticate() is called whenever ajax validation is performed within the login.php page (view). For example, if you want to perform ajax validation of an email field and your CUserIdentity::authenticate() method contains logic to validate user entered credentials against a database, then the database will be hit with a query when the username field on the login form loses focus.

What I want to do is retain the ajax validation of the username (in my case an email address) but only run the authentication logic in UserIdentity::authenticate() if the "Login" button has been pressed (and not when the email ajax validation is executed). For example:




  public function authenticate()

  {

    if (LOGIN_BUTTON_WAS_PRESSED)

    {

      QUERY_DB;

      AUTHENTICATE_USER;

    }

  }



I added a print_r($_POST) in the authenticate method, and get notice there’s a [yt0] => Login entry. Should I just check the value of “yt0” to see if the Login button was pressed?

Thanks in advance.

yt0 is an ID that Yii framework generates automatically… it would be safer if you give to the submit button an ID that you can test afterwards…

Thanks for your reply. I have changed the name of the button in the view using:




<?php echo CHtml::submitButton('Login', array('name' => 'btnLogin')); ?>



In my UserIdentity component I’m now using:




  public function authenticate()

  {

    if (isset($_POST['btnLogin']))

    {

      if ($_POST['btnLogin'] == 'Login')

      {

        // Perform authentication here, set $this->errorCode accordingly...

        return !$this->errorCode;

      }

    }

    // Always return TRUE here since login button was NOT pressed.

    // This prevents the ajax validation failing when the textbox loses focus.

    return 1;

  }



Using the above I achieve what I wanted to - ajax validation without the authentication code being executed whenever textboxes lose focus.

Is there a better/cleaner way of achieving this?

I still don’t really understand what you want/don’t want to do. But it sounds like scenarios could help you. You can define different sets of attributes to validate in each scenario. Then all you do is set different scenarios for ajax requests and standard form submission.

Scenarios are explained in more detail here:

http://www.yiiframework.com/doc/guide/1.1/en/form.model