Friday, September 30, 2011

Adding Jquery for the Contact Us Form

So as each jquery file, in template.php you can add the js file with:

<?php
drupal_add_js
(path_to_theme(). '/jquery.contact.js'); ?>
 
In our JS File, jquery.contact.js, we add a function to the submit function, which checks whether all fields are filled up, if not it alerts some messages

if (Drupal.jsEnabled) {
  $(document).ready(function() {
  $('form#contact-mail-page').submit(function () {
    //if one of this fields as nothing in print out that the form is not ready yet
    //  if ready the field is send
    if ($('#contact-mail-page #edit-name').val() == "") {
      alert(Drupal.t("The Field @name isn't filled out yet", ['@name'] = Drupal.t("name")]);
      return false;
    }
    else if ($('#contact-mail-page #edit-subject').val() == "") {
      alert(Drupal.t("The Field @name isn't filled out yet"), ['@name'] = Drupal.t("subject")]);
      return false;
    }
    else if ($('#contact-mail-page #edit-mail').val() == "") {
      alert(Drupal.t("The Field @name isn't filled out yet"), ['@name'] = Drupal.t("mail")]);
      return false;
    }
    else if ($('#contact-mail-page #edit-message').val() == "") {
      alert(Drupal.t("The Field @name isn't filled out yet"), ['@name'] = Drupal.t("message")]);
      return false;
    }
    else {
      return true;
    }
  });
});
}

Thursday, September 29, 2011

Managing JavaScript in Drupal 7

Drupal 7 has introduced several new techniques that allow you far greater flexibility and control in the scripts you can have on your Drupal site's pages.

Weighted JavaScript

drupal_add_js() now allows you to add a weight value to each script you’re adding so you can completely control the order in which the script tags appear:
- JS_LIBRARY: Any libraries, settings, or jQuery plugins.
- JS_DEFAULT: Any module-layer JavaScript.
- JS_THEME: Any theme-layer JavaScript
Example:
drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));

Adding JavaScript in the module's .info file

You can now add Javascript in the module's .info file if it should be added on every page. This allows Javascript to be aggregated in an optimal way, and is the preferred method of adding Javascript that most visitors will need on a typical site visit:
scripts[] = somescript.js

External JavaScript

drupal_add_js() now allows you to add external scripts.
Example:
drupal_add_js('http://example.com/example.js', 'external');

Overriding JavaScript

hook_js_alter() allows you to modify the path referenced by one of the scripts added by core or another module. An obvious example is if you want to use a newer version of jQuery than what comes with core:
function hook_js_alter(&$javascript) {
  $javascript['misc/jquery.js']['data'] = drupal_get_path('module', 'jquery_update') . '/jquery.js'; // Swap out jQuery to use an updated version of the library
}

JavaScript Libraries

There is now a standard way of adding collections of JavaScript and CSS, such as jQuery plugins. If you have a set of JavaScript and/or CSS that could be considered a package, provide it as a library to other modules by implementing hook_library(), and include it it in your own pages either by using #attached['library'] or drupal_add_library(). This is the preferred way to deal with JavaScript and CSS which might be used by other modules.
Modules define libraries which can be added when needed. For example, system.module defines the Vertical Tabs library, which includes one js file and one css file:
function system_library() {
  ...
  // Vertical Tabs.
  $libraries['vertical-tabs'] = array(
    'title' => 'Vertical Tabs',
    'website' => 'http://drupal.org/node/323112',
    'version' => '1.0',
    'js' => array(
      'misc/vertical-tabs.js' => array(),
    ),
    'css' => array(
      'misc/vertical-tabs.css' => array(),
    ),
  );
  ...
  return $libraries;
}

The library gets added when it's needed, through a call to drupal_add_library:
function theme_vertical_tabs($variables) {
  $element = $variables['element'];
  // Add required JavaScript and Stylesheet.
  drupal_add_library('system', 'vertical-tabs');

  return '<div class="vertical-tabs-panes">' . $element['#children'] . '</div>';
}

Prefer drupal_add_library() and always use it for core JavaScript files

drupal_add_js() should not be used for JavaScript which is already included in a library (as all core JavaScript libraries are). Use drupal_add_library() instead.

Using jQuery

jQuery is now namespaced to avoid conflicts with other Javascript libraries such as Prototype. All your code that expects to use jQuery as $ should be wrapped in an outer context like so.
(function ($) {
  // All your code here
}(jQuery));

If you don't, you may see the error Uncaught TypeError: Property '$' of object [object DOMWindow] is not a function or similar.

Behaviors

Behavior handling has changed again in Drupal7, with modules now required to explicitly define their attach handler, and optionally specify a detach handler.
Instead of the settings being a global object, settings are now passed to your handlers directly, after the context.
These changes, besides namespaced jQuery, mean basic module code should go from
something like this in Drupal 6:
Drupal.behaviors.exampleModule = function (context) {
   $('.example', context).click(function () {
    $(this).next('ul').toggle('show');
  });
}
To something like this in Drupal 7:
(function ($) {

  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $('.example', context).click(function () {
        $(this).next('ul').toggle('show');
      });
    }
  };

}(jQuery));

AJAX Forms in Drupal 7

<?php/**
* AJAX-enabled select element causes replacement of a set of checkboxes
* based on the selection.
*/
//the AJAX-enabled element is a select, $form['howmany_select'], which causes replacement of the HTML ID 'checkboxes-div' (named in #ajax['wrapper']), which is a wrapper around a the fieldset $form['checkboxes_fieldset']:

function ajax_example_autocheckboxes($form, &$form_state) {

 
$default = !empty($form_state['values']['howmany']) ? $form_state['values']['howmany'] : 1;

 
$form['howmany_select'] = array(
   
'#title' => t('How many checkboxes do you want?'),
   
'#type' => 'select',
   
'#options' => array(1 => 1, 2 => 2, 3 => 3, 4 => 4),
   
'#default_value' => $default,
   
'#ajax' => array(
     
'callback' => 'ajax_example_autocheckboxes_callback',
     
'wrapper' => 'checkboxes-div',
     
'method' => 'replace',
     
'effect' => 'fade',
    ),

  );


 
$form['checkboxes_fieldset'] = array(
   
'#title' => t("Generated Checkboxes"),
   
// The prefix/suffix provide the div that we're replacing, named by
    // #ajax['wrapper'] above.
   
'#prefix' => '<div id="checkboxes-div">',
   
'#suffix' => '</div>',
   
'#type' => 'fieldset',
   
'#description' => t('This is where we get automatically generated checkboxes'),
  );

When the 'howmany_select' element is changed, a background request is issued to the server requesting that the form be rebuilt. After the form is rebuilt, using the changed 'howmany' field as input on how to rebuild it, the callback is called:

  $num_checkboxes = !empty($form_state['values']['howmany_select']) ? $form_state['values']['howmany_select'] : 1;
  for (
$i=1; $i<=$num_checkboxes; $i++) {
   
$form['checkboxes_fieldset']["checkbox$i"] = array(
     
'#type' => 'checkbox',
     
'#title' => "Checkbox $i",
    );
  }

 
$form['submit'] = array(
   
'#type' => 'submit',
   
'#value' => t('Submit'),
  );

  return
$form;
}
/**
* Callback element needs only select the portion of the form to be updated.
* Since #ajax['callback'] return can be HTML or a renderable array (or an
* array of commands), we can just return a piece of the form.
*/
function ajax_example_autocheckboxes_callback($form, $form_state) {
  return
$form['checkboxes_fieldset'];
}
?>
The callback in this case (and in many cases) just selects the portion of the form which is to be replaced on the HTML page and returns it. That portion of the form is later rendered and returned to the page, where it replaces the #ajax['wrapper'] which was provided.
That's AJAX forms in a nutshell. A form element with the #ajax property submits a background request to the server when it is triggered by a click or change. The form gets rebuilt (on the server) by the form-builder function, and then the callback named in #ajax['callback'] is called, which selects the portion of the form to return for replacement on the original page.

Simple Form API Example

<?php
//Menu Hook
function formcreation_menu() {
$items = array();
$items['formcreation/new_form'] = array(
    'title' => t('New form'),
      'page callback' => 'drupal_get_form',
    'page arguments' => array('create_form'),
    'access arguments' => array('access content'),
    'description' => t('New form'),
    'type' => MENU_CALLBACK,
);
return $items;
}
// Menu Callback
function create_form($form_state) {
$form['personal_details'] = array(
    '#type' => 'fieldset',
    '#title' => t('Personal Details'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
);
$form['personal_details']['first'] = array(
    '#type' => 'textfield',
    '#title' => t('First name'),
    //'#required' => TRUE,
    '#description' => "Please enter your first name.",
    '#size' => 20,
    '#maxlength' => 20,
);
$form['personal_details']['last'] = array(
    '#type' => 'textfield',
    '#title' => t('Last name'),
    //'#required' => TRUE,
    '#description' => "Please enter your last name.",
    '#size' => 20,
    '#maxlength' => 20,
);

$form ['personal_details']['year_of_birth'] = array(
    '#type' => 'textfield',
    '#title' => "Year of birth",
    '#description' => 'Format is "YYYY"',
    '#size' => 10,
    '#maxlength' => 4,
);
//Adding more fields for the form
if (isset($form_state['storage']['other_details'])) {
      $form['personal_details1'] = array(
        '#type' => 'fieldset',
        '#title' => t('More Details...'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
      );
      $form['personal_details1']['age'] = array(
        '#type' => 'textfield',
        '#title' => t('Age'),
        '#description' => "Please enter your Age.",
        '#size' => 3,
        '#maxlength' => 3,
        '#default_value' => $form_state['values']['age'],
      );
      $form['personal_details1']['sex'] = array(
        '#type' => 'textfield',
        '#title' => t('Sex'),
          '#description' => "Please enter your Sex.",
          '#size' => 6,
        '#maxlength' => 6,
        '#default_value' => $form_state['values']['sex'],
      );
      $form['personal_details1']['city'] = array(
        '#type' => 'textfield',
        '#title' => "City",
        '#description' => 'Please enter your City.',
          '#size' => 20,
        '#maxlength' => 20,
        '#default_value' => $form_state['values']['city'],
      );
    }
   
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
);
//Reset the form, Hook;
$form['clear'] = array(
    '#type' => 'submit',
    '#value' => 'Clear',
    '#validate' => array('create_form_clear'),
  );
  //Adding more fields, Hook;
if (empty($form_state['storage']['other_details'])) { 
      $form['other_details'] = array(
        '#type' => 'submit',
        '#value' => 'Add Some more Details',
        '#validate' => array('create_form_other_details'),
      );
    }
return $form;
}
//Form validation
function create_form_validate($form, &$form_state) {
    $year_of_birth = $form_state['values']['year_of_birth'];
    $first_name = $form_state['values']['first'];
    $last_name = $form_state['values']['last'];
        if (!$first_name) {
            form_set_error('first', 'Please enter your first name.');
        }
        if (!$last_name) {
            form_set_error('last', 'Please enter your last name.');
        }
        if ($year_of_birth == '') {
        form_set_error('year_of_birth', 'Kindly enter the year of Birth');
        }else if($year_of_birth < 1900 || $year_of_birth > 2000){
        form_set_error('year_of_birth', 'Enter a year between 1900 and 2000.');
        }
//validation for the extra fields that added newly
    if ($form_state['storage']['other_details']) {
        $age = $form_state['values']['age'];
        $sex = $form_state['values']['sex'];
        $city = $form_state['values']['city'];
        if (!$age) {
            form_set_error('age', 'Please enter your Age.');
        }
        if (!$sex) {
            form_set_error('sex', 'Please enter your Sex.');
        }
        if (!$city) {
            form_set_error('city', 'Please enter your City.');
        }
    }
}
//Adding more fields Menu Callback
function create_form_other_details($form, &$form_state) {
    $form_state['storage']['other_details'] = TRUE;
    $form_state['rebuild'] = TRUE;
}
//Reset the form Callback
function create_form_clear($form, &$form_state) {
    unset ($form_state['values']); 
    unset ($form_state['storage']);
    $form_state['rebuild'] = TRUE;
}
//Form Submit
function create_form_submit($form, &$form_state) {
unset($form_state['storage']);
drupal_set_message(t('The form has been submitted.'));
}

?>

Wednesday, September 28, 2011

Drupal Awards, Logo's and Banners

Awards

The following is a list of awards that Drupal has won, in chronological order:

2011

2010

2009

2008

2007

  • Webware 100
    http://drupal.org/node/152770
  • Packt Publishing Open Source CMS Awards:
    Best Overall Open Source CMS (1st place)
    Best PHP Open Source Content Management System (2nd place)
    Best Open Source Social Networking Content Management System (2nd place tie)

2006

  • Packt Publishing Open Source CMS Awards:
    Best Overall Open Source CMS (2nd place)

 

Banners and Community Logos

For special events and holidays special banners are often created. These are often featured on the Drupal.org front page.
A template for these logos is available in Paint Shop Pro and Photoshop format (note the Photoshop mask layer needs to be applied manually).

What's New in Drupal

What's New in Drupal 7

Drupal 7 is released. Download the full release version.
Here is a summary of changes introduced to Drupal 7. You can also see the complete Drupal change log.

New Minimum System Requirements:

This is not a complete list of requirements. Please read the complete list of requirements.
  • Database: MySQL 5.0.15 or PostgreSQL 8.3
  • PHP Version 5.2 or higher
  • PHP Memory: 40M - 64M

Security:

  • More secure implementation for scheduled tasks (cron.php).
  • More secure password system.
  • More secure log-in system.
  • Modules can be updated via the web.

Usability:

  • Administrative links to edit existing page elements are now available on each web page, without having to go to an administration page first.
  • Improved support for integration of WYSIWYG editors.
  • Added more drag-and-drop for administrative tasks.
  • Permissions now have the ability to handle more meta-data (permissions now have a description).
  • User 1 created as part of the installation process.
  • Added features to the default install profile (tagging on the Article content type).
  • Setting up automated task runs (cron) can now be achieved via Drupal's configuration alone, without having to install any scripts on the web server.
  • Redesigned password strength validator to make it kinder and gentler, and clearer.
  • Renamed "input formats" to "text formats".
  • Added support for default text formats to be assigned on a per-role basis.
  • Moved text format permissions to the main permissions page
  • Added "vertical tabs", a reusable interface component that features automatic summaries and increases usability.
  • Improved time zone support
  • Removed per-user themes: Contributed modules with similar functionality are available.
  • Added new "Shortcuts" module to allow user to create their own menu for the pages they visit the most.

Database:

  • Added query builders for INSERT, UPDATE, DELETE, MERGE, and SELECT queries.
  • Support for master/slave replication, transactions, multi-insert queries,delayed inserts, and other features.
  • Added support for the SQLite database engine.
  • Default to InnoDB engine, rather than MyISAM, on MySQL when available for greater scalability and data integrity.

Several Performance Improvements Implemented

Documentation:

  • Hook API documentation now included in Drupal core.

News aggregator:

  • Added OPML import functionality for RSS feeds.
  • Added feed update options.

Search:

  • Added support for language-aware searches.

Testing:

  • Added test framework and tests.

Theme system:

  • Removed the Bluemarine, Chameleon and Pushbutton themes. These themes live on as contributed themes
  • Added "Bartik" theme as the default user interface theme.
  • Added "Seven" theme as the default administration interface theme.
  • Added "Stark" theme to make analyzing Drupal's default HTML and CSS easier.

File handling:

  • Files are now first class Drupal objects with file_load(), file_save(),
    and file_validate() functions and corresponding hooks.
  • Files use PHP stream wrappers to enable support for both public and private files and to support pluggable storage mechanisms and access to remote resources (e.g. S3 storage or Flickr photos).
  • Added a field specifically for uploading files, previously provided by
    the contributed module FileField.

Image handling:

  • Improved image handling, including better support for add-on image
    libraries.
  • Added a field specifically for uploading images, previously provided by the contributed module ImageField.

Better Support for Multisite Installations

Added RDF support

Better support for search engine optimization and web linking

Added ability to add custom fields

  • Provides most of the features of the former Content Construction Kit (CCK) module.
  • Custom data fields may be attached to nodes, users, comments and taxonomy terms.
  • Node bodies and teasers are now fields instead of being a hard-coded property of node objects.
  • Fields are translatable.

Installer can be run from the command line

JavaScript changes

  • Upgraded the core JavaScript library to jQuery version 1.4.2.
  • Upgraded the jQuery Forms library to 2.36.
  • Added jQuery UI 1.8, which allows improvements to Drupal's user experience.

Improved node access control system

Task handling

  • Improved handling of long-running tasks.

Friday, September 23, 2011

Prevent Cut, Copy and Paste Operations in textbox using jquery

<script type="text/javascript">
        $(function() {
        $('input[id$=tb1]').bind('cut copy paste', function(e) {
                e.preventDefault();
                alert('You cannot ' + e.type + ' text!');
            });
        });
    </script>

Tuesday, September 20, 2011

Solution For HTTP_REFERER not working in IE

Solution For HTTP_REFERER not working in IE:

The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted. 

If we use this in the firefox,it will work as fine as it is.But if we use this for IE,it will not fetch the url of the previous window,
So we will use the Javascript code here to get the url of the referrer window like this,

var strReferrer = window.opener.location.href;
            $("#referrer").val(strReferrer);


use this code in your popup widow page js file,then pass that referrer url 'strReferrer' to the id 'referrer' to your tpl file as hidden value,

<input type="hidden" name="referpage" id="referrer" value="" />

then take this hidden value using $form value in ur module for your email the referrer window url,

$referrerpath = $form['aaa']['#post']['referrer'];

Here you can get that url,,,

Monday, September 12, 2011

Multiple Email Validation using Jquery

Simple Jquery Validation for Sending Multiple Email:

After creating a form with submit button,Call the jquery function in that submit button while Onclicking,
Use this submit button code, if your submit button with image,

$form['send'] = array(
         '#type' => 'image_button',
         '#src' => path_to_theme() . "/images/btn_0_0_send_off.gif",
         '#attributes' => array('onclick' => "validateEmailForm(); return false;", 'onMouseOver'=>"this.src=Drupal.settings.basePath + 'your image path/btn_0_0_send_ro.gif';",'onMouseOut'=>"this.src=Drupal.settings.basePath + 'your image path/btn_0_0_send_off.gif';" ),
    );

Now we are validating that Multiple email field,assume that the field id is"edit-mailid",..

$(function () {

    validateEmailForm = function(){           

        var mailid  = $('#edit-mailid').val();
/* Your Mail address Validation */
        if(mailid  == ''){
            errorCount = 1;
            error+="<li>You must supply a value for the 'mailid' field of this form.</li>";
        }
        else {
            var result = mailid  .split(",");
            for(var i = 0;i < result.length;i++)
                if(!validate_email(result[i])) {
                    errorCount = 1;
                    error+="<li>Please enter a valid email address</li>";
                }
        }
}
});

/**
 * Function for validating Multiple email
 */

function validate_email(email)
{
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

     if (!filter.test(email))
           {
             return false;
           }
           else
           {
               return true;
           }

}





Print this Page and Open New window in Drupal

 Use this printPage() and openWin() Function in your main js file and call this where ever you want to print a page and Opens in a new window popup respectively.

function printPage() {
    var agt = navigator.userAgent.toLowerCase();
    var is_win = ( (agt.indexOf("win")!=-1) || (agt.indexOf("16bit")!=-1) );
    var is_mac    = (agt.indexOf("mac")!=-1);
    var macos  = (is_mac && ((agt.indexOf("mac os") != -1) || (agt.indexOf("macos") != -1) || this.ie));
    var macosx = (macos && ((agt.indexOf("os x") != -1) || (agt.indexOf("osx") != -1)));

    if(macosx || is_win ){
        window.print();
    } else {
        alert("To print this page, press 'command+P'.");
    }
}

function openWin(theURL, windowName, features) {
    newWin = window.open(theURL, windowName, features);
    newWin.focus();
}

 Ex:
onclick="javascript:window.open('<?php print base_path();?>privacy_page(your URI)','popup(Window name)','width=625,height=600,scrollbars=1'(features));

Then,cal this function in your module file:

** printPage() function is used to print a page

**openWin() is used to open a page in a new window,ther you can use the print option also