Friday, January 22, 2016

Drupal7 table with sortable headers and pagination

Using below code you can able to display table with sortable headers & pagination.

// Define table headers
     
$header = array(
  array('data' => 'ID', 'field' => 'id', 'sort' => 'ASC'),
  array('data' => 'Name', 'field' => 'name'),
  array('data' => 'Date of birth', 'field' => 'dob'),
  array('data' => 'Email', 'field' => 'email'),
);
Here 'field' values are database field values. (Ex: 'field' => 'name')
If you want to assign sort option to table field like ID, use 'sort' attribute (ex: 'sort' => 'ASC').

// DB query
     
   $select = db_select('my_table', 't')
      // This line is to enable pagination
      ->extend('PagerDefault')
      // This is for table sort
      ->extend('TableSort');
      // Example for LIKE condition
      if (condition) {
        $select->condition('email', '%' . db_like($qry['email']) . '%', 'LIKE');
      }
   $select->fields('t', array('id', 'name', 'dob', 'email'))
      // Pagination limit
      ->limit(10)
      // Sort table header
      ->orderByHeader($header)
      // Example for group by
      ->groupBy('t.email')
      // example for order by
      ->orderBy('updated_time', 'DESC')
      // Example for COUNT().
      ->addExpression('COUNT(*)', 'total');
    $results = $select->execute();

// Collect table row values
     
foreach ($results as $row) {
   $rows[] = array(
        // ID with hyperlink.
        l($row->id, 'url', array('query' => array('qry' => $row->email), 'attributes' => array('target' => '_blank'))),
        $row->name,
        $row->dob,
        $row->email, // $row->total can also be used here.
      );
    }
// Putting all together to form a table.
     
    $output .= theme('table', array('header' => $header, 'rows' => $rows, "empty" => t("Table has no row!"), "sticky" => true));
    $output .= theme('pager');
    return $output;

Some useful references:
-- A Drupal 7 table with sortable headers and pager
-- DRUPAL 7 - CREATING DRUPAL STYLE TABLES WITH PAGING, SORTING AND FILTER.

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' => 'kali.inc', // you can write code in separate file.
  )
 );
}

// Include below function as mentioned in kali.inc 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: http://stackoverflow.com/questions/7232083/add-and-remove-group-of-textelements-dynamically-from-a-web-form-using-javascr

// HTML
Name Year Description
// jQuery
function checkRemove() {
    if ($('div.container').length == 1) {
        $('#remove').hide();
    } else {
        $('#remove').show();
    }
};
$(document).ready(function() {
    checkRemove()
    $('#add').click(function() {
        $('div.container:last').after($('div.container:first').clone());
        checkRemove();
    });
    $('#remove').click(function() {
        $('div.container:last').remove();
        checkRemove();
    });
});

Below code to attach remove button against each group.
$(document).ready(function() {
    var removeButton = "";
    $('#add').click(function() {
        $('div.container:last').after($('div.container:first').clone());
        $('div.container:last').append(removeButton);

    });
    $('#remove').live('click', function() {
        $(this).closest('div.container').remove();
    });
});

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: http://rbayliss.net/drupal-queue-api

https://www.computerminds.co.uk/drupal-code/drupal-queues

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 https://stackoverflow.com/questions/5808923/filter-values-from-an-array-similar-to-sql-like-search-using-php/5809221#5809221