May 26, 2011

D7 ajax login, it is that easy!

We were finishing a small site in D7 today at SeeD software and designs included a lightbox for the login form, which was to be submitted via ajax. For a second I cursed my life, cause I just hated doing Ajax in D6, it was possible to do, but it just wasn't pleasant.

Guess what, took us a total of 54 lines of code (including comments), to get it working; for the lightbox we used the colorbox module/library.

The .module:

<?php

/**
 * Implements hook_init().
 */
function ajax_login_init() {
  $path = drupal_get_path('module', 'ajax_login');
  drupal_add_js($path . '/ajax_login.js', 'file');
}

/**
 * Implements hook_form_form-id_alter().
 */
function ajax_login_form_user_login_block_alter(&$form, &$form_state) {
  $form['actions']['submit']['#ajax'] = array(
    'callback' => 'ajax_login_submit',
    'wrapper' => 'user-login-form',
  );
}

/**
 * ajax callback for login form().
 */
function ajax_login_submit($form, $form_state) {
  if (user_is_logged_in()) {
    // Let our JS know it should reload
    drupal_add_js(array('ajaxLogin' => array('logged' => '1')), 'setting');
  }
  return $form;
}

And the .js file:

(function ($) {

  Drupal.settings.ajaxLogin = Drupal.settings.ajaxLogin || {};

  Drupal.behaviors.ajaxLogin = {
    attach: function (context, settings) {
      // If logged in, reload
      if (Drupal.settings.ajaxLogin.logged == 1) {
        location.reload();
      }
      if ($('.block-user-login').length > 0) {
        $('[href*="user/login"]').once('ajax-login', function(a) {
          $(this).click(function(e) {
            e.preventDefault();
            jQuery.colorbox({
              inline:true, href:".block-user-login"
            });
          });
        });
      }
    }
  }

})(jQuery);

I might put it into a module, until then feel free to create your own.

Comments