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.

Advertisements

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.

<code>

‘required’ => array(
‘:input[name=”save_settings”]’ => array(‘checked’ => TRUE),
),

</code>

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']));
}

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

[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

Idea, just for fun

My workplace is democratic one (Equal opportunity, transparency, open salary and financials etc.). These days lots of discussion were going on regarding the salary, since each of us need to decide their own salary themselves. So a idea strike idea in my head to build a tool where people can find their salary based on some parameters. I presented this idea to nmudgal. We tried to find if there is any similar idea on the web already, and found nothing but yes find a tool which calculate dowry for you. After seeing dowry calculator we also planned to convert it into joke(to some extend) :D. Same day we wrote the algorithm in nearly two hours and the next day we purchased the domain calculatesalary.in and nmudgal put the site live, shared on fb and twitter. Next day within 24 hours we have 160 submissions, good enough. But seriously talking if we gather some more data from user and market, we can tell approx package of a professional (kind of feeling). You can check it here. Don’t forgot to give us feedback, you can comment below. Your feedback will not be that useful for us but still if you want 😀

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/password-hash.sh '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;
quit

Hints are like decoy.

For me Hints never work. It closes all other doors of your thought and point you to only one window. When you don’t uses a hint you had a wider vision of all possible solution. Lets take an example of any maths problem,if you already seen the hint, you will never thought the other way, your mind will stuck at that point. And suppose a condition where you solved a problem by one of the possible method/solution you get in your mind and now get back to the same problem after few days (almost when you didn’t remember the solution) and now again try to solve the problem, most probably as my experience says you will solve it by some other method.This always happened to me, since i forgot things so easily, i always solve the same problem in different ways at different time. Hints may be good if your only aim is solve the problem, but it will hinder your growth.

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@127.0.0.1/db_name --account-name=you_choose --account-pass=you_choose --account-email=your_email --locale=pt_br --site-name="Drupal Test"