Showing posts with label Drupal. Show all posts
Showing posts with label Drupal. Show all posts

Wednesday, 13 July 2016

How to load jQuery UI for anonymous users in Drupal 7?

jQuery UI is no longer loads for anonymous users. We can load it in the preprocess html function as follows:
function template_preprocess_html(&$vars){
        drupal_add_library('system', 'ui');
}

How to add select event to auto complete functionality in Drupal?

(function ($) {
  Drupal.behaviors.autocompleteSupervisor = {
    attach: function (context) {
      $("input#edit-autocompleteField", context).bind('autocompleteSelect', function(event, node) {
        console.log($(this).val()); // user-entered string
        console.log($(node).data('autocompleteValue')); // key of selected item
        console.log($(node).text()); // label of selected item
      });
    }
  };
})(jQuery);

How to add auto complete feature to text field in node form Drupal?

if ($form_id == 'test_node_form') {
        foreach($form['field_test']['und'] as $key => $value) {
            if (is_numeric($key)) {
                    $form['field_test']['und'][$key]['value']['#autocomplete_path'] = 'autosuggest-path';                    
            }
        }            
    }

How to get View result programatically by passing exposed filter inputs in Drupal?

    $view = views_get_view('view_name');
    $view->exposed_input['keyword'] = $searchtext;
    $view->set_items_per_page(4);
    $view->execute();
    $view->preview();
    $results = $view->result;

How to add IMCE Browser to Multi Image Upload Field in Drupal 7?

We need to alter the UI of image_miw widget and add the checkbox to select IMCE under the manage fields section of Content Type
/**
 * Implements hook_form_FORM_ID_alter().
 */
function custom_form_field_ui_field_edit_form_alter(&$form, &$form_state) {
  $instance = $form['#instance'];
  if ($instance['widget']['type'] == 'image_miw') {
    $form['instance']['widget']['settings'] += array('imce_filefield_on' => array(
      '#type' => 'checkbox',
      '#title' => t('Allow users to select files from <a href="!url">IMCE File Browser</a> for this field.', array('!url' => url('admin/config/media/imce'))),
      '#default_value' => $instance['widget']['settings']['imce_filefield_on'],
      '#weight' => 16,
    ));
  }
}
/**
 * Implements hook_field_widget_info_alter().
 */
function custom_field_widget_info_alter(&$info) {
  if (isset($info['image_miw'])) {
    $info['image_miw']['settings']['imce_filefield_on'] = 0;
  }
}
Add IMCE Field Process functions to  mfw_managed_file Field
/**
 * Implements hook_element_info().
 */
function custom_element_info() {
  $elements = array();
  $elements['mfw_managed_file']['#process'] = array('imce_filefield_field_process');
  $elements['mfw_managed_file']['#pre_render'] = array('imce_filefield_field_pre_render');
  $elements['mfw_managed_file']['#file_value_callbacks'] = array('imce_filefield_field_value');
  return $elements;
}

How to show content through Views in Drupal 7 from separate Database table?

/**
 * Implementation of hook_views_api
 */
function commportal_search_views_api() {
   return array(
      'api' => 3,
   );
}
/**
 * Implementation of hook_views_data
* custom is Module Name
custom_users is Table Name
* my_db is Database Name
 */
function  custom_views_data() {
    $data['custom_users']['table']['group'] = 'custom_users';
        $data['custom_users']['table']['base'] = array(
          // Use the first column's name as the primary field.
          'field' => 'id',
          'title' => 'custom_users',
          'database' => 'my_db',
          'weight' => -9001,
        );
/* Add Numeric Field Handlers */
    $numericFields = array('id', 'roll_number');
    foreach($numericFields as $fieldId){
        $data['custom_users'][$fieldId] = array(
            'title' => $fieldId,
            'help' => $fieldId,
            'field' => array(
            'handler' => 'views_handler_field_numeric',
                'click sortable' => TRUE,
            ),
            'sort' => array(
                'handler' => 'views_handler_sort',
            ),
            'filter' => array(
                'handler' => 'views_handler_filter_numeric',
            ),
            'argument' => array(
                'handler' => 'views_handler_argument_numeric',
            ),
        );
    }
/* Add String Field Handlers */
    $stringFields = array('email', 'first_name', 'last_name');
    foreach($stringFields as $fieldId){
        $data['custom_users'][$fieldId] = array(
            'title' => $fieldId,
            'help' => $fieldId,
            'field' => array(
            'handler' => 'views_handler_field',
                'click sortable' => TRUE,
            ),
            'sort' => array(
                'handler' => 'views_handler_sort',
            ),
            'filter' => array(
                'handler' => 'views_handler_filter_string',
            ),
            'argument' => array(
                'handler' => 'views_handler_argument_string',
            ),
        );
    }
   return $data;
}

How to Order the Select Query results based on Search Text Expression in Drupal 7?

Let us consider as user contents are stored in a indexed field "associatedetails" as below:
Row1 Contains : "AjayKumar Gudivada";
Row2 Contains : "Ajay Kumar Gudivada";
Row3 Contains : "Gudivada";
Now, if a user searches for text "Kumar", we need to show only the results where the searched text exists. And show the results where the searched text matches starting of word in priority and display the rest.
$searchtext = "Kumar";
$query = db_select('custom_users', 'u');
    $query->fields('u', array('email', 'phone_number', 'mobile_number', 'work_location'));
    $c = db_or()
        ->condition('associatedetails', db_like($searchtext) . '%', 'LIKE')
        ->condition('associatedetails', '% ' . db_like($searchtext) . '%', 'LIKE');
    $query->condition('status', 1, '=');
    $query->condition($c);
    $query->addExpression('CASE WHEN associatedetails LIKE :db_condition_placeholder_1 THEN 2 WHEN associatedetails LIKE :db_condition_placeholder_2 THEN 1 ELSE 0 END','order_col');
    $query->orderBy('order_col','DESC');
    $query->range(0, 10);
    $result = $query->execute();
Now, the results will show as Row2 in first position and Row1 in second position.

How to add Mobile Responsive Preview Links to Administration Menu in Drupal 7?

Need to enable Responsive Preview module and use hook_admin_menu_output_build() as below:
/**
 * Add responsive preview links to the Admin Menu.
 */
function custom_admin_menu_output_build(&$content){
    $content['responsive_preview'] = array(
        'device_options' => array(
                '#theme' => 'item_list',
                '#items' => responsive_preview_get_devices_list(),
                '#attributes' => array(
                    'id' => 'responsive-preview-navbar-tab',
                    'class' => array('responsive-preview-options'),
                ),
            ),
        '#wrapper_attributes' => array(
            'class' => array('navbar-tab-responsive-preview'), // Class Name is important as Responsive Preview JS will work based on the class name
        ),
        '#weight' => 200,
        '#access' => responsive_preview_access(),
    );
}
And, add Responsive Preview library in hook_init() function
function custom_init() {
    drupal_add_library('responsive_preview', 'responsive-preview');
}

How to sort Views results based on Content Type display name instead of machine name in Drupal 7?

We can join 'node' table with 'node_type' table in views_query_alter.  And, add the Node Type Display Name to the fields list so that it can be used to sort.
$join = new views_join;
        $join->construct('node_type',
                    'node',  // left table
                    'type',   // left field
                    'type'   // field
            );
        // Add join to query; 'node' is the left table name
        $view->query->add_relationship('node_type', $join, 'node');
        // Add fields from table (or where clause, or whatever)
        $view->query->add_field('node_type', 'name', 'type_name');
        $orderby = $view->query->orderby;
        if(isset($orderby[0]['field']) && $orderby[0]['field'] == 'node_type'){
        $view->query->orderby[0]['field'] = 'type_name';
        }

How to get Search API DB results?

We can use search_api_query function to get the results by passing index machine name and search key word as follows:
$index = 'nodes_index';
$keyword = 'learn subjects';
$query = search_api_query($index);
$query->keys($keyword);
$query->range(0,4);
$results = $query->execute();

Saturday, 30 May 2015

How to check whether a region contains block for current page?

At some cases, we might need to add some div structures to a group of regions, at that case, we need to check whether region has any block or not to place the div structure.
 
Ex:
Code in page.tpl.php
 
<?php if(region_empty($testRegion1)) { 
?>
<div id="testId">
<?php
print $testRegion1;
 print $testRegion2;
 print $testRegion3; 
 print $testRegion4;
?>
</div>
<?php 
}
?>
The function region_empty() would return 1 if it has a block to show.
<?php
function region_empty($test_region) {
  $test_empty = 1;
  $result = db_query_range('SELECT n.pages, n.visibility FROM {blocks} n WHERE n.region="%s" AND n.theme="%s"', $test_region, $GLOBALS['theme'], 0, 10);
  if (count($result) > 0) {
    while ($node = db_fetch_object($result))
    {
 
      if ($node->visibility < 2) {
        $path = drupal_get_path_alias($_GET['q']);
 
        // Compare with the internal and path alias (if any).
        $page_match = drupal_match_path($path, $node->pages);
        if ($path != $_GET['q']) {
          $page_match = $page_match || drupal_match_path($_GET['q'], $node->pages);
        }
        $page_match = !($node->visibility xor $page_match);
      } else {
        $page_match = drupal_eval($block->pages);
      }
 
      if ($page_match)
        $test_empty = 0;
    }
  }
  return $test_empty;
}
?>

How to add custom styles to form elements in template.php file?

Ex: 
/*To add styles to form elements in template.php file*/
function theme_form_element($element, $value) {
// This is also used in the installer, pre-database setup.
$t = get_t();
$output = '<div class="form-item"';
if (!empty($element['#id'])) {
$output .= ' id="'. $element['#id'] .'-wrapper"';
}
$output .= ">\n";
$required = !empty($element['#required']) ? '<span class="form-required" title="'. $t('This field is required.') .'">* </span>' : '';
if (!empty($element['#title'])) {
$title = $element['#title'];
if (!empty($element['#id'])) {
$output .= ' <label for="'. $element['#id'] .'">'. $t('!title !required', array('!title' => filter_xss_admin($title), '!required' => $required)) ."</label>\n";
}
else {
$output .= ' <label>'. $t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)) ."</label>\n";
}
}
$output .= " $value\n";
if (!empty($element['#description'])) {
$output .= ' <div class="description">'. $element['#description'] ."</div>\n";
}
$output .= "</div>\n";
return $output;
}
 
/* It would be possible to add styles to individual elements*/
function theme_button($element) {
   if (isset($element['#attributes']['class'])) {
    $element['#attributes']['class'] = 'form-'. $element['#button_type'] .' '. $element['#attributes']['class'];
  }
  else {
    $element['#attributes']['class'] = 'form-'. $element['#button_type'];
  }
  return '<input type="'.(isset($element['#button_type']) ? $element['#button_type'] : "submit").'" '. (empty($element['#name']) ? '' : 'name="'. $element['#name'] .'" ') .'id="'. $element['#id'] .'" value="'. check_plain($element['#value']) .'" '. drupal_attributes($element['#attributes']) ." />\n";
}
 
 
/* For Fieldset */
function phptemplate_fieldset($element) {
  if ($element['#collapsible']) {
    drupal_add_js('misc/collapse.js');
 
    if (!isset($element['#attributes']['class'])) {
      $element['#attributes']['class'] = '';
    }
 
    $element['#attributes']['class'] .= ' collapsible';
    if ($element['#collapsed']) {
     $element['#attributes']['class'] .= ' collapsed';
    }
  }
  return '<fieldset'. drupal_attributes($element['#attributes']) .'>'. ($element['#title'] ? '<legend>'. $element['#title'] .'</legend>' : '') .'<div class="top"><div class="bottom"><div class="bottom-ornament">'. (isset($element['#description']) && $element['#description'] ? '<div class="description">'. $element['#description'] .'</div>' : '') . (!empty($element['#children']) ? $element['#children'] : '') . $element['#value'] ."</div></div></div></fieldset>\n";
}

Added fields to content type, selected input type to allow PHP, however, while printing it, the PHP things are not getting rendered, any solution?

We have to use drupal_eval() in that case.
This function will render the PHP data.

When moved contents from one site to another, some contents were not came in the list, what would be the reason?

DRUPAL would check the authorization while retreving the content.
Hence, if the author is not available in the site, it wouldn't show the associated content.
Ex:
Dev environment logins wont be available in QA environment.  Hence, it would be good to change the author name to admin or make it blank  while creating contents if planned to move the content.

How to include css and js files in theme info file?

It could be possible to include js and css files in theme info file itself, eventhough, those are not in themes folder.
One more thing, if we include these files through link / script tags, while doing aggregation (cache), DRUPAL wont cache those files.
Ex:
stylesheets[all][] = ../../../default/files/styles/style.css
stylesheets[all][] = style1.css
conditional-stylesheets[if IE 7][all][] = ../../../default/files/styles/style_ie7.css
conditional-stylesheets[if IE 8][all][] = ../../../default/files/styles/style_ie8.css

scripts[]= ../../../default/files/javascript/AC_RunActiveContent.js
scripts[]= ../../../default/files/javascript/swfobject.js
In the above ex, style.css file is in a folder which is in sites/default/files ... path. 
It is similar in case of scripts too.
And we can see the way to include conditional style sheets for IE browser.  This could be possible with Conditional Styles module.  For more info, http://drupal.org/project/conditional_styles

How to remove auto completion for text fields in DRUPAL?

Add the following attribute to form variable, autocomplete="off"
Ex:
$form['firstname'] = array(
            '#type' => 'textfield',
            '#weight' => 0,
            '#attributes' => array(
                         "autocomplete"=>"off",
    )

Usage of system_settings_form() function

We can store the entered field values by default, if we use the form variables as variable names,
function custom_settings() {
$form['disclaimer_content'] = array(
           '#type' => 'textarea',
           '#required' => True,
           '#title' => t('Disclaimer Content'),
           '#default_value' => variable_get('disclaimer_content',''),
           '#description' =>  t('Enter Disclaimer content.'),
);
return system_settings_form($form);
}

Is there any naming conventions for the folders in files folder

Yes.
DRUPAL would create folders ( JS and CSS ) inside the FILES folder whenever we cache js and css. 
Hence, eventhough we named custom folders as JS/CSS, DRUPAL would delete all the files in those folders while clearing the cache.
So, if we named our custom folders in FILES folder as JS / CSS.  Whenever, we cleared the cache, DRUPAL would delete the files in those folders.

How to retrieve all the items of a menu tree and display with customized UI in Drupal 6

We can use the menu funtion menu_tree_all_data(), which war available in menu.inc file.  Need to pass the menu name with prefix of 'menu-' as a paramenter for this function.
Ex :
Let us create one menu with name as "test-menu".  And create few items in it, such as Menu1, Menu2, Menu3 as a sub link of Menu1 (Menu1--->Menu3). Now, whenever, we click on that menu under site building -> Menu section, the url would be with "menu-test-menu" as a last argument.  We need pass this one as a paramenter to the function menu_tree_all_data() as follows:
$menu_tree = menu_tree_all_data("menu-test-menu");
It would return an array which has  main menus (such as Menu1, Menu2 ) as keys, and values consists of array with two key-value pairs, keys are "link", "below". Here, the key "link" would associate with details of current menu which includes a key 'has_children', it would be '1' if the current menu has sub-links.  And the key "below" would associate with the sub-links details if any.
function get_sitemap() {

$menu_items = menu_tree_all_data('menu-test-menu');
foreach($menu_items as $key => $value) {
$output .= "<a href='".url($value['link']['link_path'])."' title='".$value['link']['link_title']."' >".$value['link']['link_title']."</a><br/>";
if($value['link']['has_children']) {
$output = add_child_menus($value['below'],$output);
}
}
return $output;
}
function add_child_menus($child_menus = array(),$output = null) {
foreach ($child_menus as $child_key => $child_value) {
$output .= "<a style='margin-left:".$child_value['link']['depth']."0px' href='".url($child_value['link']['link_path'])."' title='".$child_value['link']['link_title']."' >".$child_value['link']['link_title']."</a><br/>";
if($child_value['link']['has_children']) {
$output = add_child_menus($child_value['below'],$output);
}
}
return $output;
}
Here, in the get_sitemap() function, checking whether menu item has children or not, if TRUE, calling the recursive function add_child_menus() with the value associated with "below" key and current string.  Function add_child_menus() would recheck each and every sublink and associated links and returns the final output which has all menus with corresponding sublinks.  We can add classes in the anchor tags and place respective CSS.

What are the mandatory fields to write .info file for module in DRUPAL 6?

.info file should have the same name as .module file and it should be in the same folder in which the later one exists.
name, description and core are the mandatory fields for .info files in modules.


Format :
name : 
name = "Test module"   ---   This is Drupal Capitalization Standard to have a capital letter as the first letter of the first word.  This is used as a display name for this module to admin.

descpirtion :
description = "This is description for Test module."   ---   This is useful to explain the purpose of your module in brief.  It has a limitation to have 255 characters.

core :
core = 6.x   ---   This is DRUPAL version but not the specific version like 6.3


Hence, here is the entire contents of .info file which has only mandatory fields:
name = "Test module"
description = "This is description for Test module."
core = 6.x

The following are some of the optional fields for .info file of module :
dependencies[]   ---   It is an array which contains the modules which needs to be enabled for the current module functionality.
package   ---   Used to group modules which might have internal dependencies.
php   ---   Used to mention the required php version for this module to work in proper.