How to install Drupal using Drush command line?

Installing Drupal using web browser is very hectic process. Every time you want to install new Drupal instance, download the latest Drupal version, copy paste it inside your working directory, open the browser and do etc etc etc...

I have a better solution for this.

If you have installed Drush in your machine then follow the below steps. Otherwise go to my this post and first installed Drush after that continue with this post.

You just need to go to your working directory for example (c:/wamp/www Or c:/xampp/htdocs) using your drush command line interface. Then run these two commands one by one.

This command will download drupal 7 inside your working directory.
Note - Make sure your machine is connected with internet.
drush dl drupal-7.x 

In below command, change "YourMySQLUser" with your Mysql username, "RandomPassword" with your Mysql  password and "YourMySQLDatabase" with your database name.
Note - Make sure your create database before running this command.
drush site-install standard --account-name=admin --account-pass=admin --db-url=mysql://YourMySQLUser:RandomPassword@localhost/YourMySQLDatabase

That's All. Your Drupal installation is completed. You don't even need to open any web browser. Just run these two commands and enjoy :)

How to install drush command line utility on Windows?

Installing Drush command line on Windows is very easy but sometimes it gives these errors such as
"Drush is recognized as internal or external command" Or "Php is not recognized by Drush"

In this situation please follow these steps to setup Drush perfectly on your Machine.

Step 1-
Download the drush from here, unzip it and copy paste it in c drive.

Step 2-
Install the following software's in default c: drive:-
gzip-1.3.12-1-setup(from here)
libarchive-2.4.12-1-setup(from here)
tar-1.13-1-bin(from here)
wget-1.11.4-1-setup(from here)

Step 3-
Download Drush Installer msi file from here
and Install.

Step 4-
Set the environment variable for drush and php location.
1. Go to my computer->Properties->Advanced->Environment Variables.
2. Edit the existing path and paste the following code at the end
   For wamp server -
  ;C:\wamp\bin\php\php5.4.3;C:\drush;C:\ProgramFiles\GnuWin32\bin;
  

   For xampp server -
  ;C:\xampp\php;C:\drush;C:\Program Files\GnuWin32\bin;

Step 5-
Start the drush command line interface and type following command:-
>drush status

You following links to execute Drush commands.

How to implement Facebook Like funtionality in drupal?

There are two ways to implement Facebook likes functionality in your project.

1. First of all it requires a Facebook Url for which you want to display likes count.
    Example:- www.facebook.com/xyz  //Here xyz could be anything.

2. If you want like count numbers with like button in your website then you need to get code from here. Provide the Url(Ex. www.facebook.com/xyz) and select other options as par your requirement.

3. Now Click get code.You will get 2 codes. First one is the Java-script code. You need to put this code in your html head tag.

4. The other code you need to put wherever you want to display like button and its count.

The requirement which I got to implement Facebook like functionality was bit different. I wanted to display only Facebook like count, and not to display like button. For this I have these solutions:-

1. You should use FQL(Facebook Query Language) here. Use the following code:-
https://api.facebook.com/method/fql.query?query=select like_count from link_stat where
url = “http://www.facebook.com/xyz”    // Change this Url

2. Pass this Url inside drupal_http_request() function and use json_decode() to get the value of like count. Then display it wherever you want.

3.You can get the like count by using this code also.
https://graph.facebook.com/?id=your_fb_page_id  // This id should be your page id in Facebook

4. Pass this Url inside drupal_http_request() function and use json_decode() to get the value of like count. Then display it wherever you want.

   

How to a send mail in Drupal?

To send a mail, we will use drupal_mail() function.
Here I am giving you an example, how you can send mail.

call this function where you want to send mail.
/*
  here test is the name of function, first_mail is the case value we are passing for switch case.
  $toEmail is the email id to whom you want to send mail, language is English and $params is the array of     parameters you want to send in mail.
 */
drupal_mail ('test', 'first_mail', $toEmail, "English", $params);
 
// The same way pass other case values to send some other mail.
drupal_mail ('test', 'second_mail', $toEmail, "English", $params);

Here we are writing mail function.
 
function test_mail($key, &$message, $params) {
$headers = array(
                        'Content-Type' => ' text/html'  // this is the header of the mail
                    );
$headers['From']="test@test.com";   // Write the email id from which you want to send the mails
$message['headers'] = $headers;
    switch($key) {
    case 'first_mail':    //case value which we are passing in drupal_mail
        $subject="Write Your Mail Subject";  // Write the subject of the mail here
        $body="";   // Write the body of your mail
        $message['subject'] = t($subject);
        $message['body'][] = $body;
    break;
    case 'second_mail':
        $subject="Write Your Mail Subject";  // Write the subject of the mail here
        $body="";   // Write the body of your mail
        $message['subject'] = t($subject);
        $message['body'][] = $body;
    break;
    }
}

How to create dependent drop down in custom form using Ahah module in Drupal?

Here I am explaining step by step, how you can create dependent drop down.

Please go through the code and read the comment.

function example_ahah_form( $form_state ) {
  $form = array();
 
  // this is standard method for register ahah helper for current form
  ahah_helper_register($form, $form_state);
 
  // provide default option for select one
  $select1_selected = 1;
 
  // $form_state['storage'], contains ahah submitted values
  if ( isset($form_state['storage']['dependent_select']['select1']) ) {
 
     // get 'select1' selected option
    $select1_selected = $form_state['storage']['dependent_select']['select1'] ;
  }
 
  // build select2 options depending upon select1
  if ( $select1_selected == 1 ) {
     $select2_options['11'] = 'option1 [select1]';
     $select2_options['12'] = 'option2 [select1]';
  }
  else if ( $select1_selected == 2 ) {
    $select2_options['21'] = 'option1 [select2]';
    $select2_options['22'] = 'option2 [select2]';
  }
  $form['dependent_select']['select1'] =
    array(
      '#type' => 'select',
      '#title' => t('Select 1'),
      '#options' => array( 1=> 'option1', 2 => 'option2'),
      '#default_value' => array( $select1_selected ),
     
      // specify ahah event
      '#ahah' => array(
      'event' => 'change', // this is onchange event of select
      'path' => ahah_helper_path(array('dependent_select')),
     
      // provide temporary path
      // no need to register it through hook_menu
      'wrapper' => 'dependent-select-wrapper',
     
      // provide the wrapper of element
      // here we have given the id of fieldset
     ),
   );
    $form['dependent_select']['select2'] =
    array(
      '#type' => 'select',
      '#title' => t('Select 2'),
      '#options' => $select2_options // set dynamic options
    );
    $form['submit'] =
    array( '#type' => 'submit',
      '#value' => t('Save')
      );
  return $form;
}

How to create block in custom module in Drupal?

1. First of all you need to use hook_block() to create block in custom module.
2. See the below code for creating block.

function apqc_benchmarking_block($op = 'list', $delta = 0, $edit = array()) {
  if ($op == 'list') {
    $blocks[1]['info'] = t('First Block');
    $blocks[1]['cache'] = BLOCK_NO_CACHE;
    $blocks[2]['info'] = t('Second Block');
    $blocks[2]['cache'] = BLOCK_NO_CACHE;

    return $blocks;
  }
  elseif ($op == 'view') {
    switch ($delta) {
      case 1:
        $block['subject'] = t('First Block');
        $block['content'] = theme('apqc_benchmarking_first_time_here');
        break;
      case 2:
        $block['subject'] = t('Second Block');
        $block['content'] = call_any_function();
        break;
    }
    return $block;
  }
}

In above code, I have created two blocks named First Block and Second Block.
In $op='list', I am listing the block names. You can add multiple blocks here.
In $op='view', You can display whatever you want to show.
For example, you can call any theme function or any function which is returning any HTML content.

How to add seprate css for IE Browsers in Drupal Theme

It is very normal scenario  that your main css file is not affecting in IE browsers. For that, you will have to create separate css files and add those files in page.tpl.php inside your drupal theme.

Note:- Paste following code inside head tag in page.tpl.php file.
Code for adding css file in page.tpl.php :-

For IE6:-
<!--[if IE 6]>
     <link type="text/css" rel="stylesheet" media="all" href="<?php print $base_url;?>/sites/all/themes/splendapro/css/ie6_splenda.css" />
   <![endif]-->

For IE7:-
<!--[if IE 7]>
     <link type="text/css" rel="stylesheet" media="all" href="<?php print $base_url;?>/sites/all/themes/splendapro/css/ie7_splenda.css" />
   <![endif]-->

For IE8:-
<!--[if IE 8]>
     <link type="text/css" rel="stylesheet" media="all" href="<?php print $base_url;?>/sites/all/themes/splendapro/css/ie8_splenda.css" />
   <![endif]-->

Note:-The code above looks like commented but it is not.So use as it is.
 
For Safari browser:-
<?php    
   if (strpos($_SERVER['HTTP_USER_AGENT'], 'Safari') !== FALSE) {
          ?>
      <link type="text/css" rel="stylesheet" media="all" href="<?php print $base_url;?>/sites/all/themes/splendapro/css/safari.css" />
    <?php
    }
?>


Note:- Yo just need to change the css file path in above codes,and use the rest code as it is.

Add more dynamically in PHP

This is very common feature that you have to integrate add more feature in your application.
It could be use in adding input field or adding any div or anything.

Here I am giving steps to use this feature by simple example. In this example, I an dynamically adding First Name and Last Name in PHP form.

1.Use the following code to create dynamic form in PHP and save this file with .php extension.

File Name - index.php

<?php
$count = 0;
?>
<html>
<head>
<script type = "text/javascript" src = "jquery.js" ></script>
<script type = "text/javascript" src = "add_more.js" ></script>
</head>
<form method = "POST" action = "insert.php"> 
<div id = "count_<?php echo $count; ?>">
    FirstName<input type = "textfield" name = "firstname_<?php echo $count; ?>" value = ""><br><br>
    LastName<input type = "textfield" name = "lastname_<?php echo $count; ?>" value = ""><br><br>
</div>
<input type = "hidden" value ="<?php echo $count; ?>" name = "hidden_val" id = "hidden_val">
<input type = "button" id = "add_more" value = "Add More"><br><br>
<input type = "submit" name = "Submit" Value = "Submit">
</form>
</html>

2. Add JQuery library in your working directory. And create one java-script file in same working directory.
   In above example, I have included both JS files. Paste the following code in your java-script file.

File Name - add_more.js

 $(document).ready(function() {
 
  $("#remove").hide();
  $('#add_more').click(function() {
        return addMore();
    });
});

function addMore(){
  var hidden = parseInt($("#hidden_val").val());
  var countNewVal = hidden+1;

$('#count_'+hidden).append('<div id="count_'+countNewVal+'">FirstName<input type="textfield" value="" name="firstname_'+countNewVal+'"><br><br>LastName<input type = "textfield" name = "lastname_'+countNewVal+'" value = ""><br><br></div>');
$("#hidden_val").val(hidden+1);
}
In java-script file, I am increasing count value by 1 after every click on Add More button, And assigning that value to the hidden_val id. 

Note:- Please do not forget to add the jquery library in your working directory.  



How to enable clean url in Drupal

There are two ways to enable Clean URLs feature in Drupal.
1. You can navigate to Drupal admin and inside Site Configuration, click on Clean URLs.
    Enable radio button and click Save Configuration.

2. This way of enabling Clean URLs is most important. Because sometimes after installing new Drupal instance, By    default Clean URLs feature will not work. To enable it, follow these steps.        
  • Go to the Apache configuration file in following path:-                                                                      C:\wamp\bin\apache\Apache2.2.11\conf  //change the path according to your working directory
  •  Now open httpd.conf file. Search for mod_rewrite.so keyword and enable the same line by removing # in front of that. 
  • Restart Apache server and now again navigate to clean url in Drupal admin, You will see that clean url feature is enable now. You can enable radio button and Save Configuration.

How to export database dump from mysql console

Export Database:-

If the size of the DB dump is large than instead of using PHPMYADMIN for exporting database, you can go for the mysql console.
Here I am mentioning  steps to export the Database:-
1. Start the Server which ever you are using. For examples wamp, xamp, lamp.

2. Open Command Prompt(cmd) not Mysql Console.

3. Now run the following cammand and change the directory to following path.
    C:\>cd wamp\bin\mysql\mysql5.1.36\bin // please check your working directory(C or D)
                                                                         and change accordingly in path.
4. Hit Enter. You will see path like this.
    C:\wamp\bin\mysql\mysql5.1.36\bin>

5. Run following command.
   mysqldump -u username -p db_name>sql_file_path_name
   For Ex: mysqldump -u root -p hemant>D:\sqlfile.sql  
   // You do not need to create sql file in any drive. Just mention the path in command line like above example, Sql file will be created automatically.

6. Hit enter, It will ask for the password.if you do not use password for mysql, just leave it and hit enter.

Note :- Please wait till the cursor is blinking(when database size is huge). 

How to import database dump from mysql console

Import Database:-

If the size of the DB dump is large than instead of using PHPMYADMIN for importing database, you can go for the mysql console.
Here I am mentioning  steps to import the Database:-
1. Start the Server which ever you are using. For examples wamp, xamp, lamp.

2. Open mysql console. It will ask for the password. Enter the password. If you do not use password, leave blank, and just hit enter.

3. Run the following command.
    mysql>show databases; // It will list all the databases

4. Now for selecting any particular database, run the following command.
    mysql>use databasename; //Mention you db name here

5. Now Run last command to import database.
    mysql>source path_to_sql_file.sql; // Ex.  mysql>source D:\my_sql_file.sql 

Submit Hanlder In Custom Drupal Forms

How to invoke two different functions from hook_form() in Drupal?
This can be achieved using submit handler.

Here is the explanation with code.
1:-Use following code in your hook_form() function:-

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

        //here we are defining the first submit handler and
          calling one submit function
        '#submit' => array('test_form_submit'),
        );  


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

        //here we are defining the second submit handler and
          calling second submit function
        '#submit' => array('enter_submit'),
        );

    
2:- By using  #submit =>  array('function_name'),you can call N number of functions from custom one form.
 

Different Page Template for Different Content Type in Drupal

This is one of the most frequently asked question in the interviews that
how can you provide different style(in terms of HTML & CSS) to any particulate page or any particulate content type in drupal?

 Here is the step by step answer for this question.
1:-First go to your themes folder(whichever theme is currently active) and search for this function in template.php file.
phptemplate_preprocess_page(&$vars)

2:-Now Copy the following code inside this phptemplate_preprocess_page(&$vars)
function:-
   if (isset($vars['node'])) {
        // This code looks for any page-custom_content_type.tpl.php page
        $vars['template_files'][] = 'page-'. str_replace('_', '-', $vars['node']->type); 
  }  

In the above code,I am checking the value for node,if its value is set(means if we are opening any node in our drupal site),than this if condition will be true and the code inside will get execute.

We are using $vars['template_files'] array for loading the template file from themes folder.

3:-Next step is to create new content type(or you can use existing content type).
    For example I am creating product content type.

4:-Now create one content of product content type.

5:-Create one file named page-product.tpl.php inside themes folder.Here product is our custom content type.

6:-Once we click on any content of product content type,the above will search for the template file with page-product.tpl.php name.If file is present inside themes folder,then it will take this template file other wise it will style take from page.tpl.php.    

7:-In this page-product.tpl.php file,we can provide the different style(HTML & CSS).

These Steps are useful for particular content type.You can provide different template to particular  page also by adding this code:- 
$vars['template_files'][] = 'page-'. str_replace('_', '-', $vars['node']->path);
Here we have replaced $vars['node']->type with $vars['node']->path(for specific path).

And create the template file with the name of your page url. For examples if you want different template for
test_image url.So create file page-test_image.tpl.php


Create Table Structure with Pagination in Drupal Using theme table


For creating tables in drupal, you don’t need to write html table tag structure.
It is very easy to implement this in drupal.

Here I am giving the step by step explanation with code:-

1:-First create a menu in hook_menu() function.
In this menu we will display the table using theme table.
function hook_menu() {
    $items = array();
    $items['theme_table'] = array(
            'title' => t('Theme Table'),
            //calling custom test_theme_table() function on this menu
            'page callback' => 'test_theme_table',
            'access arguments' => array('access content'),
            'type' => MENU_CALLBACK,
            );    
    return $items;
    }
2:- Code for test_theme_table function:-
function test_theme_table(){
    $html = '';
 
    //this $header array contains table header name,can be changed as per the requirement
    $header = array(t('BID'),t('Module'),t('Delta'),t('THEME'),t('Status'));
 
    //$count is the number of rows you want to display per page
    $count = 5;                   
   
    //fetching records from blocks tabble
    $res = "SELECT * FROM {blocks}";
    
   //passing sql query and count value in drupal pager_query function
    $query = pager_query($res, $count);
    $data = array();
    while ($row = db_fetch_array($query)) {
      $data[] = array(
                      $row['bid'],
                      $row['module'],
                      $row['delta'],
                      $row['theme'],
                      $row['status']
                      );
    }
    //adding id to the table(Not required)
    $table_attributes = array('id' => 'example');
    $output = theme('table', $header, $data, $table_attributes);
 
    //returning the resultant table with $count=5
return $output.theme('pager', $count);
}
Instead of displaying records from database,you can display any records using them table.
  

How to create date popup in drupal custom module?

This is one of the most common feature that we need to implement in any project.

Here I am giving the step by step explanation with code.

1:- First download the date module from drupal.org.
2:-Enable the date & date popup module.
3:-Now go to your .module file (inside your custom module folder) then in hook_form function, and give #type=>date_popup.

Here is the code for the reference:-
        $format='d-m-Y';
        $form['date'] = array(
                '#type' => 'date_popup', //this is the main line of code that need to be add
                '#title' => t('Date'),
                '#date_format' => $format, //this date format can be changed as per the requirment
       );