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

[your-site.]aliases.drushrc.php

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 @my-site.dev status    // Dev env

drush @my-site.prod 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.

Examples:

drush @my-site.dev sql-dump > dbdump.sql

drush rsync @my-site.dev:sites/default/files/ sites/default/files/
Advertisements

My Stay in Banglore so far :)

It has been nearly one and a half year since I came to Banglore. So far my stay has been awesome.

From travel point of view, it has been more amazing. Most of the trips being Bike rides + a small one day trek mostly 100-200 kms from Banglore. Few trips were outside Karnataka but mostly within Karnatka.

One trip which I was not able to complete as I had dislocated my shoulder during a bike ride and had to undergo a surgery which gives me almost 3 months in bed. This also gave me some time to think and
I made my first switch after working in Srijan for more than 5 yrs.

Listing down my most awesome trips, few places I have visited twice 🙂

#1 First trip was Alapuzza and wayanad (Kerela). Spent a night in a boat house, that was awesome.

allapuzza-10th-july-16

10th July 2106

#2. Shivsamudra/Mysore : 14th Aug 2016, Bike Trip, 150kms

Shivsamudram is over hyped, not that awesome. Itinerary was like banglore-> shivsamudra->mysore->banglore.

mysore-14-aug-2016

14th Aug 2016

#3. Ooty: Went by bus, didn’t like ooty much, it is very much commercialized.

ooty-20-aug-2016

20th aug 2016

#4. Mandaragiri Hills / Basadi Betta: 28th Aug 2016, Bike Trip + a small trek

Very relaxing, you can either go ealry morning or in the evening and sit there and relax.

Mandargiri-28-aug-2106

28th Aug 2016

#5 . Sakandgiri: 5th sep 2016, Bike trip+ a small trek, 75 kms

Night trek is closed now. There are chances of you getting lost, better go with a guide, happened with us 😀

sakandgiri-5-sep-2016

5th sep 2016

#6.Nandi Hills: 22 sep 2016, Bike, 70 kms

If you visited banglore, then you have to go to nandi hills otherwise it will be a sin 😀 I myself went their twice.

Nandi-hills-22-sep-2017

22 sep 2016

#7. Netravali/Amboli/Goa: 9 oct 2016

I was in goa for some office work, there we did a bike trip to amboli which was just awesome. Trek to netravali and lot more in Goa. Spent almost a month there.

Netravali-9-oct-2016

Netravali, 9th oct 2016

#8. Avellabetta: 23 oct 2016, Bike trip, Almost 100kms from banglore,

Images that you see on internet and actual place are all together different , do not get fascinated 😀

avellabetta-23-oct-2106.jpg

Avellabeta, 23rd oct 2016

#9.Kunti Betta: 5th nov 2016 , bike trip+ a small trek, 150kms

kunti-betta-5-nov-2016.JPG

Kunti Betta 5th Nov 2016

#10. Bilikal Ranga Swamy Betta: 23rd Nov 2016, Bike Trip, 80 kms.

If you are lucky, you can encounter elephants. We were lucky enough to here the sound 😛

bilikal-rangaswamy-betta-23-nov-2016

Billikla ranga swamy Betta, 23rd Nov 2016

#11. Lepakshi: 11 dec 2016, Bike trip, 130kms

It was a good trip

leepakshi-11dec-2016

Leepakshi 11th dec 2016

#12. Makali Durga: 25th Dec 2016, Bike trip + a small trek , 70 kms.

Remember to carry water and some food.

makali-durga-25-dec-2016

Makali Durga, 25th Dec 2016

#13. Pondicherry: 31st dec 2016, We went by train

pondy-31-dec-2016

Pondicherry: 31st dec 2016

#14. Menchebeele/ big banyan tree: 7th jan 2017, Bike trip , 50kms

Try to go to early morning. This is the picture of Sunset 😀

manchanabele-7-jan-2017

Menchebeele/ big banyan tree: 7th jan 2017

#15. Hampi: 27th jan 2017, Bus

Aweosme trip, Need to go there again, find a place bit outside hampi and rent a bicycle.

hampi-27-jan-2017

Hampi: 27th jan 2017

#15.5 This is when i dislocated my Shoulder: Bike trip , 0kms

Actually i was going to Thattekere Lake

#16. Coorg: 24th June 2017, Car trip,Approx 250 kms

Medikeri was too awesome.

coorg-24-june-2107

Coorg: 24th June 2017

#17. Savandurga: 19th Aug 2017,Bike+ a small trek, 120 kms

This is when i started riding my bike again 😀

savandurga-19-aug-2017

Savandurga: 19th Aug 2017

#18. Gokarna: 26th Aug 2017, Train

This is the place which you go by train(Konkan Railway) from banglore, otherwise its a waste. Around 50 tunnels, waterfalls and awesome sceneries.

gokarna-murudeswar-26-aug-2017

Gokarna: 26th Aug 2017

#19. Kudremukh Trek: 30th sep 2017, Bus+ moderate trek

Best time to go is in monsoon, i guess.

kudremukh-30-sep-2017

Kudremukh Trek: 30th sep 2017

#20. Talakadu/ Somanathpura: 18th Nov 2017, Bike Trip, 150kms

talakadu-18-Nov-2017

Talakadu/ Somanathpura: 18th Nov 2017

#21Udupi/ manglore: 24th dec 2017, Car tripLiked the Trashi Beach, Highway runs parallel to the Sea, its awesome

udupi-manglore-24-dec-2017

Udupi/ manglore: 24th dec 2017

 

All my del.icio.us stuff in my pocket.

Exported all my Del.icio.us bookmark to Pocket.

I used to like delicious because of its simplicity and i wanted to continue using it, but i don’t see this as a stable product, also we don’t have a mobile app for this. From the very beginning  it is been acquired by different company (Joshua Schachter ->yahoo->AVOS Systems->Science Inc->Pinboard) and now it is discontinued by pinboard because they have their paid services.

Now since pocket comes by default for firefox and also this has a mobile app, Pocket looks promising to me. It is available on wide range of platforms ( macOS, Windows, iOS, Android, Windows Phone, BlackBerry, Kobo eReaders, and web browsers). Pocket also denied its acquisition by Evernote because it was suspected that they might shutdown the service.

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()
->getViewBuilder('block')
->view($block);
// 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 %}
{{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

https://maxchadwick.xyz/blog/stripping-a-query-parameter-from-a-url-in-php

2. Using preg_replce

https://davidwalsh.name/php-remove-variable

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.

1. http://drupalwatchdog.com/volume-4/issue-1/something-borrowed-something-drupal

2. https://www.acquia.com/resources/podcasts/acquia-podcast-132-drupal-symfony-what-open-source-is-about

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.

  1. https://www.drupal.org/update/modules/7/8

  2. https://drupalize.me/blog/201412/adventures-porting-d7-form-module-drupal-8

  3. http://drupalwatchdog.com/volume-4/issue-1/upgrading-your-modules

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 i7san.net 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 : https://api.drupal.org/api/examples/form_example%21form_example_states.inc/function/form_example_states_form/7

https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_process_states/7#comment-16909

Todo.txt , an awesome extension for gnome.

For today’s todo stuff i used to make a file named todo.txt on my desktop and write down the stuff which i need to complete today and deleted the stuff which is done, which i was comfortable using it. I was looking for some extension on extensions.gnome.org , i came through this awesome app, which i think was first released in 2006 on lifehacker. But i came through this few days back. What this app actually does is create two text files on your system name todo and done, and store all your task their and show those stuff graphically. I really like this idea. For today todo i use this app and for every thing else i use google keep, which also very nice app. Both the app are available for mobile also  but keep is free and for todo.txt you need to few bucks.

Resources:

1. https://extensions.gnome.org/extension/570/todotxt/

2. http://todotxt.com/

3. http://www.google.com/keep/

Copy files or folder from remote server to local machine.

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

$ scp your_username@remotehost.edu:foobar.txt /some/local/directory

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

$ scp foobar.txt your_username@remotehost.edu:/some/remote/directory

For Copying the folder use  “-r”

$ scp -r user@your.server.example.com:/path/to/foo /home/user/Desktop/
 
Reference : http://www.hypexr.org/linux_scp_help.php

Schedule your future tweets.

http://dev-scheduleatweets.pantheonsite.io/  This application schedule tweet and post on your behalf. This web application is made with Drupal. There are few application which already exist with this feature, but this must be the first one made with drupal 😉 . This small application does only one thing schedule your future tweet and keep them in queue, cron runs every minute to check if there is any tweet in the queue. If yes it simply post in on your behalf when you are busy enjoying new year or birthday or taking nap :). Here is one screenshot to show how things work :
tweet
This is the page in action, this page where you schedule your post, as you can see Contains only two field one for your tweet and other one for the time in future. That’s it !!!

You can also view your “tweets in the queue” and “tweets which are already delivered”. Then there is a page called “Page 51” where resided everything else ;). I also don’t know why the page is called page 51 😀 . And yes one more thing, it just took two days to build it and deploy , power of drupal 🙂 .

So if you have any queries or feedback, please comment below (if its a postive feedback) or mail me (if its a negative one ) . hahahah 😀

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

<?php
/**
* Implements hook_node_view_alter()
*/
function flag_alter_node_view_alter(&$build) {
//print_r($build[‘links’][‘flag’][‘#links’][‘flag-like’][‘title’]);
if (isset($build[‘links’][‘flag’][‘#links’][‘flag-like’])) {
//find out the number of bookmarks for this node
$node_id = $build[‘body’][‘#object’]->nid;
//todo
// 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())));
return;
}
$uid= $form_state['values']['uid'];
$result = db_select('twitter_account' , 't')
->fields('t')
->condition('uid',$uid, '=')
->execute()
->fetchAssoc();
if($result){
db_delete('twitter_account')
->condition('uid', $uid, '=')
->execute();
}
twitter_account_save($account, TRUE, user_load($form_state['values']['uid']));
twitter_cron();
}

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())));
return;
}
$uid= $form_state['values']['uid'];
$result = db_select('twitter_account' , 't')
->fields('t')
->condition('uid',$uid, '=')
->execute()
->fetchAssoc();
if($result){
db_delete('twitter_account')
->condition('uid', $uid, '=')
->execute();
}
twitter_account_save($account, TRUE, user_load($form_state['values']['uid']));
}
</code>

Now i have to add submit handler to the hook_form_alter. i just need to add a extra submit handler the $form[#sumit][]= ' '; .
<code>
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

[mysqld]
max_allowed_packet=16M 

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 http://dev.mysql.com/doc/refman/5.1/en/packet-too-large.html

Copied from Stackexchange