Setup Drush alias to run Drush on remote server.

Drush alias  help me to run the drush command on  the remote server from my local computer.

How to setup ?

Setting up the aliases is quite easy, It just required file named in this below format


in your drush folder. Most of the time location of your  drush folder should be ~/.drush.

Putting it in home folder makes it accessible from anywhere.

Content for  [my-site.]aliases.drushrc.php

// You can create as many environments you want.
$aliases['dev'] = array(
'remote-host' => 'ssh-host',
'remote-user' => 'ssh-user',
'root' => 'my-drupal-root',
'uri' => 'my-site-name',

To add more environments, create one more alias array in the same file. Like this

$aliases['prod'] = array(
'remote-host' => 'ssh-host',
'remote-user' => 'ssh-user',
'root' => 'my-drupal-root',
'uri' => 'my-site-name',

Below is the command to access your remote site via drush

drush status    // Dev env

drush status  //Prod env

To list all Drush alias run the below command

drush sa

Now we are ready to run almost every drush command locally to control our remote drupal site.


drush sql-dump > dbdump.sql

drush rsync sites/default/files/

Put Cursor Automatically in the text input area

This should work on both Drupal 7 and drupal 8.  I have tested for drupal 8 and working fine.

$form['textfield'] = array(
  '#type' => 'textarea',
  '#attributes' => array(
  'id' => 'unique-textarea'
  'autofocus' => TRUE,

Jquery way to do it.


Remember to put this after complete page load.

Disable Form Submit after click to prevent multiple submissions.

For Drupal 7, Hide Submit Module can be used.

Features of ‘Hide Submit’:

  1. Hide or disable the submit button after it has been clicked
  2. Display a message and/or image while waiting

For Drupal 8, the above module is not present. This piece of code will work.

$form['submit_button'] = array(
  '#type' => 'submit',
  '#value' => 'Save',
  '#attributes' => array(
  'onclick' => 'javascript:var s=this;setTimeout(function()      {s.disabled=true;},1);',

Hide Custom block if there is no block content Drupal 8

I had a situation when my custom block doesn’t have content and I don’t want to display the block at all, but rest of the block markup will be there in the DOM.  To avoid this situation you might like to render it programmatically, only when there is content in the block markup.

You can add these lines of code in your hook_preprocess or hook_preprocess_page, wherever you want.

$block = \Drupal\block\Entity\Block::load('BLOCK_MACHINE_NAME');
$block_content = \Drupal::entityTypeManager()
// this line is preety important, this helps making makrp visible in block object
$block_markup = \Drupal::service('renderer')->renderRoot($block_content);
$markup = $block_content['content']['#markup'];

Now you can check if the markup is not empty then set the variable else don’t.

if(isset($markup)) {
$variables['custom_block']  = $block_content

Now you can access this variable in your twig template file and render it conditionally

{% if custom_block %}
{% endif %}

Create a modal popup Drupal 8

This is the simplest way to create a popup in drupal 8. You don’t need any other contributed module to achieve this.

Actually, you just need to create URL similar to this one.

open in popup

This will open the content of hyperlink reference into the modal.

To create above hyperlink in form API, use the below code.

use Drupal\Core\Url;
$url = Url::fromRoute('entity.node.edit_form', ['node' => 23]);
$form['link'] = array(
  '#type' => 'link',
  '#title' => 'open in popup',
  '#url' => $url,
  '#attributes' => [
  'class' => ['use-ajax'],
  'data-dialog-type' => 'modal',

Create a link form api Drupal 8

use Drupal\Core\Url;
$nid = 23   // node id you want to open
$url = Url::fromRoute('entity.node.edit_form', ['node' => 23],['query' => ['key' => 'value']]);  //get the route name from module.routing.yml file
$form['link'] = array(
'#type' => 'link',
'#title' => 'open link',
'#url' => $url,

This will generate below html

<a href="/node/23/edit?key=value" data-drupal-selector="edit-link" id="edit-link">open link</a>

Trim Query Parameters From URL

There are several ways to solve this problem. These are the two most prominent way to achieve this.

1. Php way: Parse, trim and rebuild

2. Using preg_replce

First one is the easy way to do it and also do not require any external library.

On the other hand, the second one is bit lengthy but clean way to achieve it and also require an external library (pecl/http) to rebuild the URL which has been disassembled by parsing it.

Porting Drupal modules from D7 to D8.

There are hell lot of resources available on web which will help you porting from D7 to D8. There are lot of changes in Drupal 8. Drupal 8 has borrowed some components from symfony. Read following articles about drupal and symfony.



I suppose porting module will be a great way to understand drupal 8. So i tried to porting  a module name username_check to drupal 8. Here is the github repo for D8 module and the presentation i created to record all the changes involved in porting the module to D8.

Here are the few resources which i collected and few which i created.which will help you to learn porting.




There are more available on web. Since D8 is still in beta  so you can’t just stick to these blogpost or article, you need to keep exploring.

Mark node for indexing manually

day to day activity

When an associated node gets changed, the original node doesn’t reflect the changes on solr. In this case the node which contains such information on solr should be pushed/marked for indexing. It is considered that search_api is being used. The current example will work when node gets pushed immediate to solr when changes are made.

Right now is taken to show the example.
Here the site has Club group which is a node. This group is used in projects. So whenever s project is created, the Group on solr should show the total number of projects. Also when a donation is made to a project, the corresponding club/group gets sum to donation made to this.

In this case, whenever such case occurs, we only need to make an entry in search_api_item.

mysql> desc search_api_item;
| Field | Type | Null | Key | Default | Extra |

View original post 137 more words

How to make a form element required with states ?

So the problem is when you try to make a field required using ‘states’ , it is not getting validated because everything happens in the browser (client side), nothing get validated on server side. So if you try this code.

'required' => array(
':input[name="save_settings"]' => array('checked' => TRUE),

This will add the red asterisk to the form element but it will not get validated. So the solution is

You need to add custom validation in hook_form_validate function.

Reference :

Copy files or folder from remote server to local machine.

Copy the file “foobar.txt” from a remote host to the local host

$ scp /some/local/directory

Copy the file “foobar.txt” from the local host to a remote host

$ scp foobar.txt

For Copying the folder use  “-r”

$ scp -r /home/user/Desktop/
Reference :

Create a menu item whenever a taxonomy term is created

function your-module-name_taxonomy_term_insert($term) {
    $menu_item = array(
  'link_title' => $term->name,
  'menu_name'  => 'your-menu-machine-name', // It uses '-', not '_'
  'customized' => 1, // Must be 1 in order to not dispaly the link in any language
  'link_path'  => 'taxonomy/term/' . $term->tid, // menu_link_save() does not like aliases. Then 'nid' is used
  'language'  => 'en', // language is required in order to make the item translatable
  'plid' => $plid, // id of the sub-menu if you want to add this in sub-menu
  'weight' => '-50',
$mlid = menu_link_save($menu_item); // You don't need to receive it in a variable
$ml = menu_link_load($mlid); // I'm loading $mlid just to display the result and verify it

Tweet automagically when you login command line.

This is simple hack to tweet whenever you open the command line. We are going to use twidge and fortune for this.
The very first thing we need to do is install twidge and fortune.
Step 1 : Install Twidge
sudo apt-get install twidge

Step 2: Configure Twidge
twidge setup
This command will tell you what to do next 🙂

Step 3 : Update twitter status using twidge
twidge update "your status"
Just to test everything is working fine.

Step 4. Now install fortune
sudo apt-get install fortune or sudo apt-get install fortune-mod

Step 5. Now the last step, let twidge and fortune work together.Put the below command in your ~/.bashrc file.
fortune -n 140 | twidge update
We used -n 140 to limit the fortune to 140 char because twitter doesn’t allow more than 140 char.

Now whenever you open your terminal, a tweet will be posted from your fortune file to your account, 🙂
Lots of configure are available in fortune and twidge to tweak your hack.You can even schedule your tweet to post on some specific time.

You can follow this twitter account to get the 140 char fortune probably once in a day 🙂

Display Flag count

* Implements hook_node_view_alter()
function flag_alter_node_view_alter(&$build) {
if (isset($build[‘links’][‘flag’][‘#links’][‘flag-like’])) {
//find out the number of bookmarks for this node
$node_id = $build[‘body’][‘#object’]->nid;
// fid should not be hard coded
$results = db_query(“SELECT count FROM {flag_counts} WHERE content_type =’node’ AND content_id = :nid AND fid = ‘3’”, array(‘:nid’=>$node_id));
foreach ($results as $record) {
$result = $record->count;
if (empty($result)) {
$result = 0;
$build[‘links’][‘flag’][‘#links’][‘flag-like’][‘title’] .= “($result)”;

In the reference example we have D6 code.


How to recover the deleted branch in git?

Simply push the local deleted branch. If that is not present on local and then follow the these steps.

Yes, it’s easy to restore a deleted branch from git.

Create a new branch:

git checkout -b recover_branch
Use git reflog to view information in your reflog:

git reflog
Find the entry that shows HEAD@{0}: this is your HEAD commit for that branch. Note the commit id and use it in the following command:

git merge
You might also be able to use:

git branch

Add custom breadcrum

I have to add a custom breadcrumb to my twitter page (Share >> Members >> User >> Recent tweets) . for this we need to add a the following code in templete.php. We will user your_theme_preprocess_breadcrumb() function.

function your_theme_preprocess_breadcrumb(&$variables) {
// Replace the default search api breadcrumb.
foreach ($variables['breadcrumb'] as $key => $breadcrumb) {
  $strip_breadcrumb = strip_tags($breadcrumb);
if ($strip_breadcrumb == '[all items]') {
  $variables['breadcrumb'][$key] = t('All Content');
if ((arg(0) == "user") && (is_numeric(arg(1)))) {
  $user = profile2_load_by_user(arg(1));
  $user_name = $user['main']->field_ekn_name['und'][0]['value'];
  $user_uid = $user['main']->uid;
  //echo ""; print_r($user_uid);
  //echo ""; print_r($user);die();
  $variables['breadcrumb'][1] = l('Share', 'share');
  $variables['breadcrumb'][2] = l('Members', 'share/members');
  $variables['breadcrumb'][3] = t($user_name);
if ((arg(0) == "user") && (is_numeric(arg(1))) && arg(2) == 'tweets') {
  $variables['breadcrumb'][3] = l(t($user_name),'share/members/' .$user_uid);
  $variables['breadcrumb'][4] = t('Recent Tweets');

Run hook_cron on submit

In twitter module imported status only get updated on cron run. So whenever a account is added in the twitter block nothing is displayed. So i run hook_cron on submit, i just added the hook_cron in custom submit handler as in last post.

function twitter_account_form_submit_custom($form, &$form_state) {
module_load_include('lib.php', 'twitter','twitter');
module_load_include('inc', 'twitter','twitter');
$name = ($form_state['profiles']['main']->field_twitter_handle['und'][0]['value']);
$twitter = new Twitter($name);
try {
$account = $twitter->users_show($name, FALSE);
} catch (TwitterException $e) {
form_set_error('screen_name', t('Request failed: @message.', array('@message' => $e->getMessage())));
$uid= $form_state['values']['uid'];
$result = db_select('twitter_account' , 't')
->condition('uid',$uid, '=')
->condition('uid', $uid, '=')
twitter_account_save($account, TRUE, user_load($form_state['values']['uid']));

Add a extra submit handler to the hook_form_alter

In my case i have to add a twitter account to the user profile, but by default it comes in a tab. So i have to add a field( for twitter handler) in the user profile so that on submit that twitter handler can be added to the user profile.
i created a custom function for submitting the form, this is mainly a overriding the default submit handler by just changing the function name.

function twitter_account_form_submit_custom($form, &$form_state) {
module_load_include('lib.php', 'twitter','twitter');
module_load_include('inc', 'twitter','twitter');
$name = ($form_state['profiles']['main']->field_twitter_handle['und'][0]['value']);
$twitter = new Twitter($name);
try {
$account = $twitter->users_show($name, FALSE);
} catch (TwitterException $e) {
form_set_error('screen_name', t('Request failed: @message.', array('@message' => $e->getMessage())));
$uid= $form_state['values']['uid'];
$result = db_select('twitter_account' , 't')
->condition('uid',$uid, '=')
->condition('uid', $uid, '=')
twitter_account_save($account, TRUE, user_load($form_state['values']['uid']));

Now i have to add submit handler to the hook_form_alter. i just need to add a extra submit handler the $form[#sumit][]= ' '; .
function hook_form_alter {
if($form_id == 'user_profile_form')
$form['#submit'][] = 'ekn_user_profile_form_submit';
$form['#submit'][] = 'twitter_account_form_submit_custom';

Increase max_allowed_packet

max_allowed_packet is set in mysql config, not on php side


You can see it’s curent value in mysql like this:

SHOW VARIABLES LIKE 'max_allowed_packet'

You can try to change it like this, but it’s unlikely this will work on shared hosting:

SET GLOBAL max_allowed_packet=16777216;

You can read about it here

Copied from Stackexchange

Reset password using drush

This commands will be help you to reset the admin password of your site.

# Provide you a login link
drush uli
# Set the password for any user
drush upwd admin –password=”new password”

One more way :

cd php scripts/ 'drupal'

This will generate a hash for you, copy and paste in below queries.

drush sql-cli
update users set name='admin', pass='Hash generated from above command' where uid=1;

Install Drupal From Command Line

If you are using drupal, you must have heard of drush, if not check it now, its the one of the awesomest thing in drupal.More links

1. Project page on drupal.

2. Documentation : how to install

Now i suppose you have drush installed on your system. So you can install drupal in three easy steps.

1. Drush dl drupal

2. mv drupal-7.x your_site_name && cd your_site_name

3.drush si --db-url=mysql://mysql_username:password@ --account-name=you_choose --account-pass=you_choose --account-email=your_email --locale=pt_br --site-name="Drupal Test"

Overriding the breadcrumb

An easy way to Override the breadcrumb to use hook_breadcrumb in templete.php. In my profile page the user profile name was missing only “home” was getting displayed. i used to following code in templete.php :

function YOUR_THEME_NAME_breadcrumb($variables) {
$breadcrumb = $variables['breadcrumb'];
if(arg(0) == "user") {
$breadcrumb[]= drupal_get_title();
$output = '
<div class="breadcrumb">' . implode('>>', $breadcrumb) . '</div>
return $output;

One more way is : create a breadcrumb.tpl.php file in your theme folder and add following line:
This will only change the default symbol( >>) between breadcrumb string to !.