Monday, 14 September 2015

Google autocomplete ambiguous address - same street name in different cities or suburbs

Ambiguous address issue

When entering the address of '29 Karaka Street' in the google autocomplete input, the first hint should be '29 Karaka Street, Auckland, New Zealand', but since there are quite a few streets in NZ having the same street name of 'Karaka', it may cause some issue/misunderstanding of using the location. In addition, when inputting this address in google maps, goold maps will note that 'we couldn't find this address'.

How to solve the issue

Use google maps geocoding API to check whether the address is unique as below:
https://maps.googleapis.com/maps/api/geocode/json?address=29%20karaka%20street&components=country:NZ&key=YOUR_KEY
If there are multiple 'address_components' in the result, it means the address is not unique and we need to display some notes for user such as 'add a suburb or a postcode to make the address more clear'


Wednesday, 2 September 2015

How to fix Theme Developer module not showing caused by the conflict with JQuery

Symptom and the error message from JS console

The theme developer pop-up doesn't show up on the website.
When open Chrome Console, there is an error message saying that 'Uncaught Error: Syntax error, unrecognized expression:
'


Solution

Open the file with path of 'sites/all/modules/devel_themer/devel_themer.js'
Search the following snippet which is the source of the issue:
$(Drupal.settings.thmr_popup)
      .appendTo($('body'));
Use the snippet below to replace the above one:
$($.parseHTML(Drupal.settings.thmr_popup))
       .appendTo($('body'));
Note: The reason of this issue is that JQuery doesn't support putting html string in to the dollar function anymore.

Monday, 31 August 2015

How to use svg logo

The easiest way of using svg logo

Upload the logo manually to the path of 'sites/all/themes/urbansherpa/images/urbansherpa-logo.svg' instead of using Drupal to upload the image to the drupal public folder, cause drupal image doesn't support svg format
Go to Drupal admin panel : admin/appearance/settings/urbansherpa
Untick the check-box of 'Use the default logo' and put the path where the logo was uploaded. In my example it's 'sites/all/themes/urbansherpa/images/urbansherpa-logo.svg'
All done and the svn logo should work as expected.

Trace the Drupal core code to understand the aforementioned steps

Open the file with the path of 'modules/system/system.admin.inc'
Search the function named 'system_theme_settings'
At the bottom of the function, the snippet of adding validate function can be found:
$form['#validate'][] = 'system_theme_settings_validate';
Search the validate function in the same file and at the bottom of this function you will find the magic snippet:
// If the user provided a path for a logo or favicon file, make sure a file
  // exists at that path.
  if (!empty($form_state['values']['logo_path'])) {
    $path = _system_theme_settings_validate_path($form_state['values']['logo_path']);
    if (!$path) {
      form_set_error('logo_path', t('The custom logo path is invalid.'));
    }
  }
  if (!empty($form_state['values']['favicon_path'])) {
    $path = _system_theme_settings_validate_path($form_state['values']['favicon_path']);
    if (!$path) {
      form_set_error('favicon_path', t('The custom favicon path is invalid.'));
    }
  }
From the snippet above, we can realize that it requires a logo path and a favicon path which are existing files.

Sunday, 30 August 2015

Make embeded video responsive

Settings when using 'Video Embed Field' Module

Go to Drupal admin : admin/config/media/vef_video_styles
Click the 'Edit' button of 'Normal'
Change the player width to 100% instead of default value of 640px


How to use CSS flex box in SASS

Add flex mixins to meet the browser compatibilities

@mixin flexbox() {
  display: -webkit-flex;
  display: -moz-flex;
  display: -ms-flex;
  display: flex;
}

@mixin flex($values) {
  -webkit-flex:  $values;
  -moz-flex:  $values;
  -ms-flex:  $values;
  flex:  $values;
}

@mixin flexflow($values){
  -webkit-flex-flow: $values; 
  -moz-flex-flow: $values;    
  -ms-flex-flow: $values;    
  flex-flow: $values;
}

@mixin order($val) {
  -webkit-order: $val;
  -moz-order: $val;    
  -ms-flex-order: $val;    
  order: $val;
}

@mixin alignitems($val){
    -webkit-align-items: $val;
    align-items: $val;
}
Note: these cover most of the frequently used flex css styles, but not all of them

A sample for displaying the images and making the images aligned centered which might not be able to achieve via div or table

.flex-box{
    @include flexbox();
    @include flexflow(row wrap);/* the items will fall down to the next line when the current line is full */
    @include alignitems(centre);/* the items will be aligned centred */
}

.flex-item{
    @include flex(1 15%); /*flex-grow flex-basis*/
}

Improve web page performance in Google PageSpeed

Google PageSpeed, a good tool to test and get advices from

Open the PageSpeed page: https://developers.google.com/speed/pagespeed/insights/ and enter the website URL you want to optimize
You will get a score and some suggestions. There should be some 'should fix' ones and some 'consider fixing' ones, and we should do our best to fix the ones marked as 'should fix'

Use drupal async_js module if there are numerous render-blocking javascript files

Install the module from the website : https://www.drupal.org/project/async_js and enable the module
One way to add the async for loading the js is using the built-in function in this module as below:
async_js_add_js("path/to/your/script.js")
The other way is to add an attribute in the options of drupal_add_js function as the following code:
drupal_add_js("path/to/your/script.js", array("async_js" => TRUE))

Note: some of the js might have dependencies, so this module also support setting the dependencies of the js by adding the attribute of async_dependencies. 


Always try to add the js via drupal_add_js function instead of in the template header

The reason is that when the js is added via the function, you can control where to load the js(in the header or footer) and the weight in the loading process.
Here are some examples of doing it:
//load js in the footer
drupal_add_js('sites/all/themes/ora_theme/js/jquery-1.9.1.js',
            array('type' => 'file', 'scope' => 'footer', 'weight' => 22));
//load js in the header
drupal_add_js('sites/all/themes/ora_theme/js/typekit.js',
            array('type' => 'file', 'scope' => 'header', 'weight' => 21));

Drupal Datatables module installation and usage

Install drupal Datatables plugin

Go to the web page: https://www.drupal.org/project/datatables
Use drupal update manager to install the module
Enable the module

Install JQuery Datatables

Go to JQuery Datatables  website: https://www.datatables.net/
Download the latest version
Unzip the downloaded plug-in and copy it to sites/all/libraries/datatables(datatables is a case-sensitive folder name which should be paid attention to)

Check whether JQuery Datatables was installed properly

Check whether the path of 'sites/all/libraries/datatables/media/js/jquery.dataTables.js' exists or not
Go to Drupal Admin page of 'admin/reports/status' and search 'datatables'. If there is no warning or error, it means the plug-in has been installed properly.

Use the Drupal Datatable module in drupal view

Go to Drupal admin page of admin/structure/views.
Click 'Add a new view' link
In the drop-down list of 'display format', the 'Data Tables' can be found.
Choose 'Data Tables' as the format and add some content for the view
You will see the paginated data table when you open the view on the front-end website

Thursday, 13 August 2015

Maxlength module used to set a limit and a counter for text related field

Install and enable the module

Go to the website and find the most recent stable version
Install and enable the module

Set the character limit for the text field of a node type which contains any content type, account type, etc.

Go the admin page of admin/structure/types
Click on the link of 'manage field' in the row of the content type containing the fields that needs to be set
Click the 'edit' button of the field that needs to be set a character limit on
Search 'Maxlength JS' and the input fields associated with the Maxlength module will be spotted
Set the value of the fields related to Maxlength module and it will take effect when you create a content of this content type

Set the character limit for the text field in the custom module using drupal form API

It's freaking easy to do it with just adding the #maxlength and #maxlength_js attribute for the form field. Here is an example:
$form['details'] = array(
      '#weight' => '2',
      '#required' => '0',
      '#type' => 'textarea',
      '#cols' => 60,
      '#rows' => 5,
      '#maxlength_js' => TRUE,
      '#maxlength' => 250,
      '#default_value' => isset($form_state['values']['futher_instructions']) ? $form_state['values']['futher_instructions'] : '',
      '#title' => t('Further Instructions'),
    );
In the example, the max length is set to be 250 characters and the maxlength_js is set to be true which means the Maxlength module has been enabled for this field.
Note: Both maxlength and maxlength_js have to be set to enable Maxlength module for the field.

Monday, 10 August 2015

Field Permission Moudle used to set the permission of any field of both the entity type and the account settings

Install and enable the module

Go to the module URL: https://www.drupal.org/project/field_permissions
Install and enable the module
Here is an example of using this module to set the permissions of a field of the account settings 

Set the permission of the field

Go to the Admin pane: admin/config/people/accounts
Switch to the Manage Fields tab
Click the edit link of the field that needs to be set permission for
Scroll down to the Field Settings part and choose Custom permissions radio button
The permission settings table will show up where we can set the permissions for the field

Check front page to see the effect

Use a front-end user to log in
Click the View tab of the profile page and the fields which is not empty and having the read permission will be displayed
Switch the Edit tab of the profile page and the fields which having the write permission will be editable, while the fields which having the read permission will show up with a read-only status


Sunday, 26 July 2015

Install Drupal Amazon S3 file system module (s3fs)

The modules that need to be installed

Drupal libraries: https://www.drupal.org/project/libraries
S3 File System : https://www.drupal.org/project/s3fs
AWS SDK for PHP: https://github.com/aws/aws-sdk-php/releases
Note: 
1. AWS SDK for PHP is a dependency, but you need to pay attention to the version, because the current version is 3, while S3 File System needs the version of 2. So remember to download the right version. 
2. There is also a drupal module trying to install AWS SDK for PHP by composer and the URL is https://www.drupal.org/project/awssdk2. It's not working for me, cause the composer manager module which the awssdk2 module depends on is not working with my drupal. So try to avoid using awssdk2 module to install AWS SDK.

Enable the modules

Put AWS SDK for PHP into the libraries folder and rename the AWS library folder as awssdk2.
Enable S3 File System module.

Check whether it's installed correctly

Go to Admin Pane : admin/config/media/s3fs
Switch to the Actions tab and click the 'Refresh file metadata cache'. If AWS SDK for PHP not found error doesn't show up, it means the installation is successful.

After installing it correctly, you just need to set the bucket name and amazon access keys and s3 will work

Tuesday, 7 July 2015

Drupal form API usage tips

How to set default value for date_popup

In New Zealand we often use 'd/m/Y H:i:s' as our time format, so I set it as the format of my date_popup field. But when I tried to set the default value using the same format as below, it wouldn't work for me:
'#default_value' =>date('d/m/Y H:i:s', strtotime('+1 hour')

The reason is that date_popup requires the default value to use the format of 'Y-m-d H:i:s' no matter what we are using for the date_popup format. Therefore it works well after I changed the default value using the required format as the following:
'#default_value' =>date('Y-m-d H:i:s', strtotime('+1 hour')

Always remember to set default value for the fields

For a simple form(one step form), it's better to pre-populate the fields to make it more user-friendly.
For a wizard form(multiple step form), to make it more convenient for users we need to both pre-populate the fields and keep user-input information when user go back and forth.
Based on the aforementioned reasons, it's required to always remember to set default value for the fields. Otherwise, we might have to set the default values for all the fields all at once which is a quite boring work.


 

Wednesday, 1 July 2015

Drupal Forena Report Module

Install and enable the module

Download and install from this link: http://ftp.drupal.org/files/projects/forena-7.x-4.5.tar.gz
Enable all Forena modules which should be three of them.

Configure forena report

 Go into admin/config/content/forena and set up Forena General settings.

Add data source

Go into admin/config/content/forena/data and add the data source.
Pay attention to the Path field which is the place where the data block files like sql files will be located, and the other fields can be left as default.

Grant permissions of data source

Go in to admin/people/permissions.
Search the data source created at the previous step and grant the permissions for specific roles.
Note: The data source won't show at the steps below if the permissions are not granted to the associated role.

Add sql data blocks

Add your sql query files under the path of the data source referring to the sql files under forena/repos/drupal folder.

Create forena report

Go in to admin/structure/forena and click 'Create New Report'.
Following the steps of 'Create Report' wizard and the new forena report will be created.
After the report created, the page will be redirected to reports/test_report/edit where you can add your data blocks.
Click the 'data' button and select the data block where your sql query resides in.

Add other formats of report such as csv html and email

Go to admin/structure/forena and click the edit link for the report you want to add formats for.
Switch to Document Type tab and the supported formats will show up.
Tick the formats you want to add and click the Update button, and the formats have been added.

Add data tables support for report pagination 

Download the JQuery Datatables plug-in on the website of https://www.datatables.net/
Unzip and copy the plug-in to the folder of 'sites/all/libraries/dataTables'(dataTables is case-sensitive).
Make sure the path named 'sites/all/libraries/dataTables/media/js/jquery.dataTables.js' exists
Go to Drupal status report page and search 'Forena dataTables support'. Make sure there are no warnings and errors

See the pagination results of the reports

Open any of the Forena reports and the pager should be added automatically

Tuesday, 23 June 2015

When must we clear drupal cache

Principle theories


The cache must be cleared when first add a drupal hook function.

Adding or changing menus in hook_menu function

Whenever you add a menu or change the menu in the hook_menu function, it won't take effect immediately, because it's requiring the Drupal cache to be cleared even if you have disabled drupal cache.

First add hook_theme function in a module or a theme

The cache needs to be cleared when you first add the hook_theme function in you code. After that you don't need to clear it when you change the code in the function.

First add hook_form_FORM_ID_alter/hook_form_alter function

The cache needs to be cleared only when you first add the hook function.

Tuesday, 16 June 2015

AWS drupal issue: nginx+php missing client IP address when using reverse proxy

Symptoms of this issue

The most front end presentation for this issue is that you will get an error of "the IP has been blocked because of log-in  failure for too many times".
The source of this issue can be found when you print the result of the function called ip_address() in drupal, cause the only IP address you can get from drupal is 127.0.0.1.

Reason of this issue

At default, drupal gets the IP address from the PHP variable called $_SERVER['REMOTE_ADDR'], but this variable is set to 127.0.0.1 by nginx proxy server. However, a new variable named $_SERVER['HTTP_X_FORWARDED_FOR'] is set as the real IP by nginx reverse proxy if nginx realip module  is installed. And drupal also get the ability to detect this variable by doing some configuration.

Solution of this issue

Go to drupal root folder and open the file named sites/default/settings.php.
Go to the line 404 and you will find the following php code of  $conf['reverse_proxy'] = TRUE; which is commented. What we need to do is to un-comment it.
Jump to a few lines after, the variable definition of $conf['reverse_proxy_addresses'] will be found. We can just add '127.0.0.1' in the array which will be eliminated from client IP addresses.
After the previous configuration, the correct IP address should be received by drupal.


AWS drupal issue: https missing when using ELB

Symptoms of this issue

First of all, some of the js, css, images will be lost when using https as the protocol to visit the website.

If http authentication is used or the grammatically log-in code, like drupal_form_submit('user_login', $form_state);, is used, the user logged-in session, which is in the global $user variable , might be missing in other modules.

Reason of this issue

ELB will terminate the https which will make $_SERVER['HTTPS'] disabled even if we are doing a https request. However, ELB sets another variable $_SERVER['HTTP_X_FORWARDED_PROTO'] to https which we can use to define the right protocol.

Solution of this issue

Go in drupal root folder and open the file named includes/bootstrap.inc.
Go to line 735 and the line with the code of $is_https = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on'; should be found.
Add the code below after the code of line 735:
//to make it compatible with AWS ELB
  $is_https = $is_https ? $is_https :
          isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https';
Here we are, drupal should work well with AWS ELB for https protocol.

Sunday, 14 June 2015

google places autocomplete js api business search doesn't work

If Google Places Autocomplete doesn't show business search results, you may solve the issue by following the checks below.

Check whether google places API has been activated

Go to google console with the URL of https://console.developers.google.com, and check whether google places service is in the list of activated services

Check the whether google client auth is included in the js code

Usually a google url like https://apis.google.com/js/client.js?onload=handleClientLoad will be the html scripts if the google client has been set up in your code.
Compare the APIKey in you js code with that in google console to make sure they are the same

Check the types attribute of Google Places Autocomplete API

When instantiating the google places autocomplete object, the types can be passed as a parameter. So check the types value to see whether it's including 'establishment' type.
The types can also be set up by calling the setTypes method of Autocomplete, so we need to check the types here as well.

After all of the checks and modifications, the business search should work if everything has been done properly.

Tuesday, 26 May 2015

Anatomy of drupal theme settings process

As we know it's very easy to implement the theme settings in a theme as below

First, we need to create a file called theme-settings.php under the theme root folder.

Second, we implement drupal hook named hook_form_system_theme_settings_alter by creating a function named MYTHEME__form_system_theme_settings_alter and add custom drupal form elements in this function. Here is a sample below:
function mytheme_form_system_theme_settings_alter( &$form, &$form_state )

At last, if we need custom submit function or reset function, we just need to explicit the submit or reset function in the form elements defined under the hook function at step 2, and create the associated submit or reset function. The following is a sample snippet:
/* file theme-settings.php*/
function mytheme_form_system_theme_settings_alter( &$form, &$form_state ){
        /* Submit function */
        $form['#submit'][] = 'mytheme_form_system_theme_settings_submit';

        /* Add reset button */
        $form['actions']['reset'] = array(
            '#submit' => array( 'mytheme_form_system_theme_settings_reset' ),
            '#type' => 'submit',
            '#value' => t( 'Reset to defaults' ),
        );
        //some other custom form code
}
function mytheme_form_system_theme_settings_submit( $form, &$form_state ){
        //custom submit code
}
function mytheme_form_system_theme_settings_reset( $form, &$form_state ){
        //custom reset code
}

When drupal display the settings page in the admin panel, it starts from the admin menu definition in system module. Here is the snippet defining the menu.

/* in the file modules/system/system.module at line 646*/
foreach (list_themes() as $theme) {
    $items['admin/appearance/settings/' . $theme->name] = array(
      'title' => $theme->info['name'],
      'page arguments' => array('system_theme_settings', $theme->name),
      'type' => MENU_LOCAL_TASK,
      'access callback' => '_system_themes_access',
      'access arguments' => array($theme),
      'file' => 'system.admin.inc',
    );
  }

From the aforementioned snippet, we can get that system_theme_settings is called to generate the form with the theme name passed. 

/* in modules/system/system.admin.inc at line 399 */
function system_theme_settings($form, &$form_state, $key = '') {
    //some code
    //at line 572
    // Process the theme and all its base themes.
    foreach ($theme_keys as $theme) {
      // Include the theme-settings.php file.
      $filename = DRUPAL_ROOT . '/' . str_replace("/$theme.info", '', $themes[$theme]->filename) . '/theme-settings.php';
      if (file_exists($filename)) {
        require_once $filename;
      }

      // Call theme-specific settings.
      $function = $theme . '_form_system_theme_settings_alter';
      if (function_exists($function)) {
        $function($form, $form_state);
      }
    }
    //some code
    //at line 597
    // We don't want to call system_settings_form_submit(), so change #submit.
    array_pop($form['#submit']);
    $form['#submit'][] = 'system_theme_settings_submit';
    $form['#validate'][] = 'system_theme_settings_validate';
}

In the previous function in the system module mytheme_form_system_theme_settings_alter function is called. The submit and validate function of theme settings are also set up here. 

The default submit and validate function are set in system module, but we can also add our custom submit and validate function in our theme-settings.php file.

Monday, 25 May 2015

submit function in theme-settings.php not found by drupal

reason of this issue

In some themes, it doesn't define $form_state['build_info']['files'][], so in some cases the theme-settings.php file wouldn't be loaded again when the form is submitted. Therefore, in the web page we will get a submit function not found error.

Solution

Add $form_state['build_info']['files'][] definition for every theme in a custom module by using theme hook of hook_form_FORM_ID_alter as the following

/**
 * Implements hook_form_FORM_ID_alter() for system_theme_settings().
 *
 * Workaround for bug https://drupal.org/node/1862892.
 */
function MYMODULE_form_system_theme_settings_alter($form, &$form_state) {
  if ($form['var']['#value'] != 'theme_settings') {
    $key = preg_replace(array('/^theme_/', '/_settings$/'), '', $form['var']['#value']);
    $themes = list_themes();

    if (isset($themes[$key]->base_themes)) {
      $theme_keys = array_keys($themes[$key]->base_themes);
      $theme_keys[] = $key;
    }
    else {
      $theme_keys = array($key);
    }

    foreach ($theme_keys as $theme) {
      $theme_path = drupal_get_path('theme', $theme);
      if (file_exists($theme_path . '/theme-settings.php')) {
        $form_state['build_info']['files'][] = $theme_path . '/theme-settings.php';
      }
    }
  }
}

Sunday, 15 March 2015

Media Vimeo

Download and install the following modules

  1. Media
  2. Media Internet Sources
  3. Media Vimeo
  4. enable Media Vimeo and its required Modules

Create a new content type where vimeo field will be attached

  1. enter admin page: admin/structure/types/add
  2. fill 'name' filed and save it
  3. enter admin page: admin/structure/types and click 'manage fields' of test vimeo
  4. add a field called 'test vimeo', choose 'File' as the FIELD TYPE and save the filed
  5. enter admin/structure/types/manage/test-vimeo/fields and click 'edit' of test vimeo
  6. Modify 'Allowed remote media types' and 'Allowed URI schemes' as the screenshot below
  7. enter admin/structure/types/manage/test-vimeo/display and change the FORMAT of test vimeo to 'rendered file'

Create a content of test vimeo content type

  1. enter admin/content, click 'add content' and then choose 'test vimeo' as content type
  2. click 'select media' button of 'test vimeo' field and paste the vimeo url of a video
  3. save the new content and view it

Notes

  1. Chrome bug: "SELECT MEDIA" and "REMOVE MEDIA" button can't be clicked

Enable vimeo JAVASCRIPT api (which allows us trace the embedded video)

  1. Go to D7 admin/config/media/file-types page
  2. Click the link 'manage file display' of Video
  3. Switch the bottom tab to 'Vimeo Video'
  4. Tick the check-box of 'Enable the Javascript API' and save the configuration
  5. Check a content page containing vimeo videos and notice the 'iframe' used for embedding the video. As a result, the vimeo 'player_id' which is the same as the 'iframe id' should be found in the html source code.



Google Analytics

Install the following modules

  1. Google Analytics 7.x-2.1
  2. Google Analytics Event Tracking 7.x-1.2
  3. Enable 'Google Analytics' and 'Google Analytics Event Tracking'

Install chrome extensions for debug

  1. install and configure 'Google Tag Assistant'

Set up Google Analytics account 

  1. Go to google analytics website and sign up or sign in an account : http://www.google.com/analytics/
  2. Follow the website step and go to the 'Admin/Property Settings'. The configuration is supposed to be similar as below:

    Note:  The value of 'Default URL' can be a website URL on your local computer, but it must respect the URL format, so URLs like 'http://localhost' is not allowed. In my case, I'm using 'http://drupal.localhost.com' and configure it in /etc/hosts.

Configure D7 'Google Analytics' module

  1. enter admin/config/system/googleanalytics, paster the 'Property ID' where you get from 'google analytics' on this page.
  2. enable 'internal search' tracking in the page entered by clicking 'Search and Advertising' tab on the left.
  3. toggle debug mode of this module which will output some debug information in 'chrome console' if it's on. And tick 'locally cache tracking code file' in case of downloading analytics.js from google every time visiting the website.
  4. click some links in the website and check the result on 'Google Analytics' website by accessing 'Overview' of 'Real Time' on 'Reporting' page.

    Note: 'Real-Time' is for instant tracking which is quite useful for developing and 'Audience' is for the actual website report.
  5. Pay attention that D7 'Google Analytics' is using analytics.js which is a more recent way of tracking with it's guide on the page: https://developers.google.com/analytics/devguides/collection/analyticsjs/,  while the old ga.js is still bing used by numerous developers.

Try 'Google Analytics Event Tracking' Module

  1. Enable 'Google Analytics Event Tracking Example' module which is a sample module of event tracking residing in 'Google Analytics Event Tracking'  module
  2. Open with your favourite editor the file: sites/all/modules/google_analytics_et/google_analytics_et_example/google_analytics_et_example.module
  3. Find the variable '$selectors' in the function '_google_analytics_et_example_set_selectors_array' where you put the JQuery selector and event to configure the event of the element being tracked. Below is a standard array indicating how to add them.
     array(
          'event' => 'mousedown',      //a JQuery event name
          'selector' => 'a#logo',      //a JQuery selector to figure out the specific element which will be tracked
          'category' => 'Home Link',   //Typically the object that was interacted with (e.g. button)
          'action' => 'click',         //The type of interaction (e.g. click)
          'label' => 'Logo',           //Useful for categorizing events (e.g. nav buttons)
          'value' => 0,                //Values must be non-negative. Useful to pass counts (e.g. 4 times)
          'noninteraction' => TRUE,
        ),
    // An explanation of label parameter: !textThis is what would be returned from the jQuery .text() method.!hrefThe value of the href attribute (handy with anchor //tags).!currentPageThe URL of the current page (this is taken with the code window.location.href
    //There is one more bit that is handy when configuring the module.
    //Passing !test will send an alert to the page when the event is triggered and not send the event to Google Analytics.

  4. Commentate the value of the variable $selectors and make yours
  5. Trigger the event you set up in array $selectors and enter the 'Event' tab of Goolge Analytics Real-Time page to watch the result

Tracking vimeo video in 'Google Analytics Event Tracking Example'

  1. Download vimeo.ga.js from the website: http://www.sanderheilbron.nl/vimeo.ga.js/
  2. Make sure the 'Javascript API' of 'Media: Vimeo' module is enabled referring to another wiki page: Media Vimeo
  3. Modify the file: google_analytics_et_example.module and add vimeo.ga.js in the drupal loaded Javascript list
    /**
     * Implements hook_page_alter().
     */
    function google_analytics_et_example_page_alter(&$page) {
        drupal_add_js(drupal_get_path('module', 'google_analytics_et_example') . '/js/vimeo.ga.js', array('scope' => 'footer'));
    }

  4. Open the content page containing vimeo videos and watching the 'Real-Time' event in Google Analytics.

















Form Builder

Install and enable the modules

  1. form builder: http://ftp.drupal.org/files/projects/form_builder-7.x-1.6.tar.gz
  2. Options_element: http://ftp.drupal.org/files/projects/options_element-7.x-1.12.tar.gz
  3. Enable form builder and form builder example



Add CSS classes in the div of rows of drupal view

Purpose :


add a class name called 'test-row-class' in the div of each row of drupal view

Solutions :


There are two ways to do it. First, add the class via drupal admin; Second, customize view template file named 'views-view-unformatted.tpl.php'.

Via Drupal Admin:


  1. Find the machine name of view using 'Theme Developer' module. Enable the module, click the view you want to modify on the web page, and clieck the views_view on the pop-up window of 'Theme Developer'. After that, the machine name called 'price_location' can be found in the 'candidate template files' part  
  2. Search the machine name of view in the database table of 'views_view' and get the 'human name' of view which is 'Theme Price Location Sidebar' 
  3. Go to drupal admin page of 'admin/structure/views' and search the 'human name' of view. And then click edit of the specific view. 
  4. Switch to the display block that needs to be changed  
  5. Click the 'Format: Settings' in the 'FORMAT' section  
  6. Add the class name whichever you want in the input of 'Row Class' and the class name will show up on the front page. Here using 'test-row-class' as an example. 

Via Modifying Template Files:


  1. Enable 'Theme Developer' and click the view that needs to be change on the web page  
  2. Click 'views_view_unformatted' which is the descendant of 'views_view'. ('views_view' template is the top template file, while 'views_view_unformatted' is the template file displaying the rows of the view elements). And then the candidate tmeplate files will show up. 
  3. Choose one of the candidate template files you want to use. Here will take the most specific template file name of 'views-view-unformatted--theme-price-location--theme-price-location.tpl.php'. 
  4. Create the template file in the currently used theme folder and copy the code from 'views-view-unformatted.tpl.php' which is the default template file
  5. Change the code in the specific template file as you want and it won't affect other views

Thursday, 12 March 2015

Background Image

Install and enable the modules

  1. Background Images 7.x-1.4: http://ftp.drupal.org/files/projects/bg_image-7.x-1.4.tar.gz
  2. Context 7.x-3.6: http://ftp.drupal.org/files/projects/context-7.x-3.6.tar.gz
  3. Backgroundfield 7.x-1.5: http://ftp.drupal.org/files/projects/backgroundfield-7.x-1.5.tar.gz
  4. Enable 'Context', 'Background Image', 'Background Image Context', 'Background Image UI', 'BackgroundField'

Configure 'Background Image' Module

  1. Enter D7 admin page: admin/structure/types/add, and create a new ContentType used for containing the images of background.
  2. view ContentType list and click 'manage fields' of 'background image'
  3. add an image filed which will be used to upload background images
  4. go to D7 admin page: admin/config/content/background-image
  5. select node type and node field as what we added at step 3
  6. Define the 'Selector' of CSS which by default is 'body', but we will probably change it to a specific class name whichever we want. 
  7. Attach the css 'Selector' defined at the previous step to the html tags in any of the D7 template files you want.
    Note: This is a global setting for 'Background Image' Module which will be used by 'Background Image UI' module. In 'Background Image UI' Module, we can choose different images for different pages. In order to make background image module effective,  Background Image UI must be enabled and set properly.

Set up 'Background Image UI' Module

  1. Add two nodes of 'Background Image' ContentType and upload two different images
  2. switch to 'Background Images' tab and select a background image for different pages
  3. save and browse a content page, and search the class where I'm use 'div.background-image' in the source html code.

    Note: 'Background Image' Module is good for setting a background image of the whole website or a group of web-pages. If you want to configure the background images of DIVs in the same web-page, it's better to use 'Background Field' Module.

Set up 'Background Field' Moudle

  1. Create a ContentType called 'background field' for test and add a new filed with a special type 'BackgroundField'
  2. Remember to set the CSS 'Selector' ('div.backgroundfiled' is used here) during the configuration steps of adding the new field
  3. Add a new content of 'Background Field' ContentType and search the CSS 'Selector' in the html source code
  4. You can use the CSS selector anywhere in this specific content page and it won't be found in the other content pages.

Upload Image using managed_file form api

  1. Add managed_file filed in the form containing the upload input referring to the drupal form api
  2. Add the code saving file permanently in the form submit callback function
  3. Get the URL of the uploaded file and use it

Monday, 9 March 2015

Context

  1. Download the module from the page: https://www.drupal.org/project/context, install it and enable it.
  2. Enter admin/structure/context and click 'add'
  3. Input the name of the context  
  4. Choose a condition of 'Node Type' and choose the content type of 'test'  
  5. Choose a reaction of 'Blocks' and select the blocks which are supposed to display for the contents of the content type using 'test' for instance 
  6. Click the 'Add' button of the region where the block should be put in using 'content' region as an example
  7. Browse any page of the content type and the blocks added at step 6 should show up