Wednesday, November 25, 2015

Drupal preview image with remove option after upload file using form API

Preview image with remove option after upload file using form API.

// Create form with '#type' => 'managed_file'.
function kali_custom_form($form, &$form_state) {
 $form['upload'] = array(
  '#type' => 'managed_file',
  '#title' => t('Image Preview'),
  '#upload_location' => 'public://',
  '#theme' => 'kali_preview_theme', // define theme for preview
  '#progress_indicator' => 'throbber',
  '#upload_validators' => array(
  'file_validate_is_image' => array(),
 'file_validate_extensions' => array('jpg jpeg gif png'),
// Write hook_theme() as mentioned below.
function hook_theme() {
  return array(
   'kali_preview_theme' => array(
   'render element' => 'element',
   'file' => '', // you can write code in separate file.

// Include below function as mentioned in file or remove file include in hook_theme
and write below function in module file.
function theme_kali_preview_theme($variables) {
 $element = $variables['element'];
 $output = '';
 if($element['fid']['#value'] != 0 ) {
  $output .= '
'; $output .= theme('image_style', array('style_name' => 'thumbnail', 'path' => file_load($element['fid']['#value'])->uri, 'getsize' => FALSE)); $output .= drupal_render_children($element); $output .= '
'; } return $output; }

Some useful references:
-- Preview image after upload usinf FAPI.
-- Display uploaded image after upload.

Enable PHP OPcache in XAMPP windows

PHP 5.5.0 & later OPcache will be available by default.
Please add below code in php.ini to enable it.
 zend_extension = "C:\xampp\php\ext\php_opcache.dll"
 // Restart apache after enabled it.

opcache in xampp windows

Wednesday, November 4, 2015

Add group of fields using jquery or javascript

I had one requirement that adding some group of fields into some form.

Have used below set of HTML & jQuery codes.

Original posts:

Name Year Description
// jQuery
function checkRemove() {
    if ($('div.container').length == 1) {
    } else {
$(document).ready(function() {
    $('#add').click(function() {
    $('#remove').click(function() {

Below code to attach remove button against each group.
$(document).ready(function() {
    var removeButton = "";
    $('#add').click(function() {

    $('#remove').live('click', function() {

Tuesday, November 3, 2015

Drupal Queues

Using Drupal Queues, you can do so many bulk operation or batch process easily.

Shared some interesting links for further reading.

Original posts:

Javascript get array key value

Using below simple code, you can read Key & value from Java script array or object

var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' },
keys = $.map(foo, function(v, i){
  return i;

Filter values from an array similar to SQL LIKE '%search%' using PHP

Array search or array filter similar to SQL LIKE '%search%' in PHP.

In one of my project, I need to display all the country names in select option as a drop down list.

Client expected filter option based on user input.
Ex: If user type "IN", we need to display country name starts with "IN".

Result like "INDIA", "INDONESIA", etc ..

Used below code to achieve it.
 $input = preg_quote('IN', '~');
 $result = preg_grep('~^' . $input . '~i', $list); // List is PHP array of values
// ~^ - to start from beginning.
// ~i - for case insensitive
Original post

Drupal custom pagination - override theme_pager

You can override Drupal pagination using below code.

I have faced below issue in one of my project.

ie, Actual total query result is different than displaying result.

Ex: My query total count was 100. But while displaying, based on requirement we need to display only 80 items. So when I use theme('pager') in template, I got result for 100 which is wrong. We need to display pager for only 80 items.

I have done below changes to override Drupal pagination.
// Menu callback function
function display_some_items() {
  // Query to fetch data with pager.
  $data['result'] = It contains filtered items, not equal with actual total count.
  $data['custom_pager'] = my_custom_pager($filtered_count); // custom pagination callback.
  $output .= theme('some_tpl_file', $data);

// custom pagination
function my_custom_pager($filtered_count = 0) {
  pager_default_initialize($filtered_counts, 10); // Pagination Limit 10
  $args = array('quantity' => 10,'tags' => array('<<','<','','>','>>'));
  return theme('pager', $args);

// Print below code in your template
print $custom_pager; // It will display pager based on filtered count.

Tuesday, May 26, 2015

Change Browser URL & Title without reloading (refreshing) page

Change browser URL & Title with out refreshing / reload the page.

Please see below link for more details.

Thursday, May 21, 2015

Drupal template redirect

I have faced one challenge recently where we need to redirect from one custom node template to another one template.
  • Created one template for custom content type (nature).
  • node--nature.tpl.php
  • node--my_nature.tpl.php (if your content type - my_nature: some time you will face this situation.)
  • This content type has one taxonomy reference.
  • For particular taxonomy reference(condition), we need to display different appearance (layout).
  • So done below fix to redirect for different tpl.
When ever you visit nature content, you will be landed on node--nature.tpl.php.
Inside this tpl, I have used below condition to use different tpl file.

// Write below code inside node--natute.tpl.php on top of the file.
if (condition) {
 print theme('use_different_layout', array('node' => $node)); // pass argument if you need.
// Create different tpl file for "use_different_layout" theme by using hook_theme().

hook_theme() example.
function hook_theme() {
return array(
    'use_different_layout' => array(
      'variables' => array('node' => array()),
      'template' => 'templates/different-layout.tpl.php',

Google Analytics to track AJAX requests

Recently I have faced one problem based on Google analytics.
  • We were displaying slide show with node navigation.
  • Means, for each next/prev click, we were displaying different page view. 
  • Each page view contains, its own node(page) URL & title.
  • Implemented below google analytics code to track each hits.
  • But problem is, on ajax success or at next / prev click, we could not able to send new node details to google analytics.
  • I have fixed that solution using below code.
1) Code will be available on each page reload.

I have placed below code at "html.tpl.php" , so that for each and every page load, it will send page details like node URL & title to google analytics.

(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),



ga('create', 'UA-56232568-1', 'auto');

ga('send', 'pageview');


2) Code for ajax success.

Use below code on ajax success or next/ prev slide success. So that on every ajax hit success, it will trigger page details based on below settings.
ga('send', 'pageview', {'page': 'send/your/site/url', 'title': 'some-page-tile-ajax-success'});

1. You should have valid google analytics account to get above script.
2. After creating your account, add your site.
3. It will take at least 24 hrs(Not exactly) to track your site. Don't expect immediate track after adding site.

Wednesday, May 20, 2015

Drupal social share - Service links

Service links is a Drupal module used to attach social share(like FB, Twitter, etc,..) icons on every pages.

I have attached one video URL ( Drupal 7 Service Links Module - Daily Dose of Drupal episode 103 ) here to get basic set up / Config about this module.

But if you want to attach this option on your custom tpl file / on ajax success. please follow the below steps.

1) Code to use in your tpl file.
$social_block = module_invoke('service_links', 'block_view', 'service_links');
print render($social_block['content']);

2) Code to use in ajax success / ajax call back function.
$social_load = block_load('service_links', 'service_links_not_node>>' . $node_id); // Drupal node ID.
$get_social_array = _block_get_renderable_array(_block_render_blocks(array($social_load)));
$get_social_block = render($get_social_array);

3) Below code used to attach meta details on page for SEO purpose.
$element = array( 
 '#tag' => 'meta',
 '#attributes' => array(
 'property' => 'og:url',
 'content' => 'node/url',
drupal_add_html_head($element, 'og_url');
$element = array(
 '#tag' => 'meta',
 '#attributes' => array(
 'property' => 'og:title',
 'content' => $node->title,
drupal_add_html_head($element, 'og_title');
// This code is to attach image on meta to share.
// Image wont be there on share if its missing.
$element = array(
 '#tag' => 'meta',
 '#attributes' => array(
 'property' => 'og:image',
 'content' => 'your/image/url',
drupal_add_html_head($element, 'og_image');
$element = array(
 '#tag' => 'meta',
 '#attributes' => array(
 'property' => 'og:description',
 'content' => 'some_description',
drupal_add_html_head($element, 'og_description');

Wednesday, January 28, 2015

Print an array or object in watchdog Drupal

Use below lines of code to print an array or object in watchdog  Drupal.

// Directly use values.
watchdog("log_name", '<pre>' . print_r( $my_object, true) . '</pre>');

// With place holder as per Drupal standard.
watchdog('log_name', '<pre>@place_holder</pre>', 
  array('@place_holder', print_r( $my_array, TRUE))

About Git - Git Basics - Become a git guru - Getting Started - Git Basics

About Version Control

What is “version control”, and why should you care? Version control is a system that records changes to a file or set of files over time so that you can recall specific versions later.

Personally I love some links to study about Git. Listing those links below.

1) - One of the wonderful kick start link to Git.

You will get  clear idea about Git from this link. Topic wise explanation is there as mentioned below.

2) - Video links about Git.

Tuesday, January 27, 2015

Add a new configurations block to admin/config

We have frequent requirement to create admin form in Drupal.

Below is the simple example to create admin configuration block for your setting form.

$items['admin/config/myblk'] = array(
'title' => 'Title of the block',
'description' => 'description',
'position' => 'left',
'weight' => -25,
'page callback' => 'system_admin_menu_block_page',
'access arguments' => array('access administration pages'),
$items['admin/config/myblk/myblk-setting'] = array(
'title' => 'Link to settings',
'description' => 'Description about link',
'page callback' => 'drupal_get_form',
'page arguments' => array('call_your_setting_form'),
'access arguments' => array('administer authentication'),
'weight' => 10, );

Using coder.module to auto-format your code with drush

Coder  is a one of the best Drupal module to format / clean your Drupal codes.

Find more details about it here

After installed coder module, got to http://your-site/admin/config/development/coder

Select module / theme which is needs to be cleaned and click RUN REVIEWS.

You will get report as listed below.

you can automate this process by one line Drush command (drush coder-format ../path/to/your/module).

// download coder module
drush dl coder
// enable this module
drush en coder // drush en coder -y (Yes by default)
// auto format Or clean code
drush coder-format sites/all/modules/custom/your-module - path to your module

Note: Its cleaning inc,tpl,module,install files. Not cleaning js & css files.
Link to original post.

Friday, January 23, 2015

Export data to excel in php

Below is the simple script to exporting your data to Excel file.

You can download below codes from github.

function download_xls() {

  $data = array(
    array("Kali", "Sundar", 28),
    array("Amala", "silk", 18),
    array("Vinoth", "bharath", 31)

  // Form header names.
  $header = array("Firstname", "Lastname", "Age");

  // File name for download.
  $file_name = "Export_data_" . date('Ymd') . ".xls";

  // This option to trigger download widget.
  header("Content-Disposition: attachment; filename=\"$file_name\"");
  header("Content-Type: application/");

  // push header to file.
  echo implode("\t", $header) . "\n";

  foreach($data as $row) {
    // Push each row contents.
    echo implode("\t", $row) . "\n";

// Phpexcel is a drupal module to do export / create xls files.

Below is the example code to export xls file with out any open file format issue.

 module_load_include('inc', 'phpexcel');

// Create directory my_dir.
  $filepath = 'public://my_dir/';
  file_prepare_directory($filepath, FILE_CREATE_DIRECTORY);

  // Store file.
  $dir = file_stream_wrapper_get_instance_by_uri('public://my_dir')->realpath();
  $filename_timestamp = "file-name" . date('d-m-Y') . ".xls";
  $path = "$dir/$filename_timestamp";

  // Use the .xls format
  $options = array('format' => 'xls');
  $excel_result = phpexcel_export($header, $data, $path, $options);

  // To avoid file format issue while open file.
  $file = new stdClass();
  $file->uri = $path;

  header('Content-Type: application/');
  header('Content-Disposition: attachment; filename="' . $filename_timestamp . '"');
  header('Expires: 0');
  header('Cache-Control: must-revalidate');
  header('Pragma: public');

Usage in Drupal:

1) Create hyper link in your page <a href="download/xls"> Export </a>
2) Create menu call back for this URL.

  $items['download/xls'] = array(
    'page callback' => 'download_xls',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,

Original post - See more details here [>>];

Wednesday, January 7, 2015

PHP sort multi-dimension array by value

Below is the example code for sorting multi-dimension array by its value.

$my_array = array (
  '0' => array (
      'ID' => 425,
      'ln' => 'CBolware',
      'fn' => 'Christian',
      'mi' => '',
  '1' => array (
      'ID' => 423,
      'ln' => 'Bernstein',
      'fn' => 'ZBear',
      'mi' => 'D.',
  '2' => array (
     'ID' => 419,
     'ln' => 'DBellweather',
     'fn' => 'Brent',
     'mi' => '',
  '3' => array (
     'ID' => 356,
     'ln' => 'ABayleaf, III',
     'fn' => 'Joe',
     'mi' => 'X.',
  '4 '=> array (
     'ID' => 336,
     'ln' => 'Public',
     'fn' => 'John',
     'mi' => 'Q.',

usort($my_array, function($a, $b) {
   return strcmp($a['fn'], $b['fn']);  // fn -> key of the array