Friday 28 April 2017

Drupal 8 Metatag

To make website popular and to increase the SEO of website, Metatag play the very important in it.
In D7 it installation is very easy.We just have to install module and have to configure as per our requirement.
If you have remember, in D7 when we install the module and after configuration it is created a field for entity types and because of that field we were able to set metatag for each entity.

Step to set up metatag in D8

  1. Install the module.
  2. You can setup common metatag for site by visiting this url (admin/config/search/metatag).
  3. If you want to add different metatag for each node or term than create a field of type metatag in any content type or in entity type for which you want to setup.
  4. Now create a node and on node edit page you can see metatag tab,  in which you can add metatag for your single node ot you can use tokens.
  5. Now your metatag is ready for that entity type.
  6. If you created field in one content type then you only able to setup metatag for that entity type entities only.
  7. In D8, You can't reuse of field of one entity type to another entity type.So for each entity you have to create different field of metatag type.
So by following above steps you can easily setup metatags for your site.

Thursday 27 April 2017

Drupal 8 Create a menu and add menu link in admin menu

In drupal 7 it is a very simple task because hook_menu provides the straightforward implementation but in drupal 8 its implementation is very different. In drupal 8 we create the YAML files. Hook menu is converted into routing file.
So let us take an example to understand this. We want to add a link under the admin -> configuration -> search and metadata.
So for this first, we have to create a menu link(In D8 routing)

Create a file  (My_Module.routing.yml) under your module directory.

My_Module.MY-MENU:
  path: '/admin/config/search/MY-PATH'
  defaults:
    _form: 'Drupal\My_Module\Forms\MYMENU'
    _title: 'MY MENU'
  requirements:
    _permission: 'administer site configuration'

Here My_Module.MY-MENU it is unique machine name. For more detail click here

So above code just registers your menu in the menu configuration. After clearing cache you will be able to visit  URL directly. It works fine if you haven't made any mistake in defining controllers. To listing  this URL into admin menu we have to implement following code
Create another file in the same directory (My_Module.links.menu.yml)

My_Module.MY-MENU:
  title: 'MY MENU NAME'
  parent: system.admin_config_search
  description: 'Add MY path'
  route_name: My_Module.MY-MENU:
  weight: -1

Here My_Module.MY-MENU this can be different but for our convenience, we provide the same routing machine name.
 parent : For parent, we need to search routing machine name of parent menu (In our case parent menu is admin -> configuration -> search and metadata ). Mostly you can find these paths into routing.yml files.

Thursday 20 April 2017

Drupal 8 Get the list of all voacbs

To get the list of all vocabs, Drupal 7 provides us a function "taxonomy_vocabulary_get_names()" which return a list of all vocabs with their machine name.
In D8 for some time this function will exist, but in future, this will be deprecated and in Drupal 9 this will be removed.
So if you are using this function then this will work but any update of Drupal 8 will deprecate this function.So to avoiding this problem use following code:

Just include this class
use Drupal\taxonomy\Entity\Vocabulary;

then write this line, which returen an array of menu objects.
$vocabs_types = Vocabulary::loadMultiple();

For only get list of vocabs, you can use this

  $vocabs = array();
    $vocabs_types = Vocabulary::loadMultiple();

    if (!empty($vocabs_types)) {
      foreach ($vocabs_types as $vocab_name => $vocab) {
        $vocabs[$vocab_name] = $vocab->label();
      }
      asort($vocabs);
    }

Drupal 8 Get list of all menus

To get the list of all menus, Drupal 7 provides us a function "menu_get_menus()" which return a list of all menus with their machine name.
In D8 for some time this function will exist, but in future, this will be deprecated and in Drupal 9 this will be removed.
So if you are using this function then this will work but any update of Drupal 8 will deprecate this function.So to avoiding this problem use following code:

Just include this class
use Drupal\system\Entity\Menu;

then write this line, which returen an array of menu objects.
$menus = Menu::loadMultiple();

For only get list of menus, you can use this

    $menus = array();
    $menu_types = Menu::loadMultiple();

    if (!empty($menu_types)) {
      foreach ($menu_types as $menu_name => $menu) {
        $menus[$menu_name] = $menu->label();
      }
      asort($menus);
    }

Drupal 8 Get all content types

To get the list of all content type, Drupal 7 provides us a function "node_type_get_types()" which return a list of all content type with their machine name.
In D8 for some time this function will exist, but in future, this will be deprecated and in Drupal 9 this will be removed.
So if you are using this function then this will work but any update of Drupal 8 will deprecate this function.So to avoiding this problem use following code:

Just include this class
use Drupal\node\Entity\NodeType;

then write this line, which returen an array of content type objects.
$content_types = NodeType::loadMultiple();

For only get list of content type, you can use this

    $types = array();
    if (!empty($content_types)) {
      foreach ($content_types as $type => $details) {
        $types[$details->id()] = $details->label();
      }
      asort($types);
    }

Drupal 8 ValidUrl

Drupal 7 provide us a valid_url() function to check the Url validation.In drupal 7  we can call it directly because it was written in the module file.But in D8 we can't.
In D8 we have to use UrlHelper class and the help of this class we can use this function.
In D8 valid_url() is converted into isValid(), so for using this function,

  1. First, include class namespace
    use Drupal\Component\Utility\UrlHelper;
  2. then use this function, No need to create the object because it is a static function so we can call it by its class name
    UrlHelper::isValid($url, $absolute = FALSE);

    Parameters : -
    $url : -The URL to verify
    bool $absolute: Whether the URL is absolute

Wednesday 12 April 2017

Drupal 7 Block Regions and Hidden Block Regions

HI,
  I think you have created blocks and placed that block in any regions. Sometimes we need to create some new block regions.
So first, how to create new block regions. It is very simple in drupal, 
Just go to your theme.info file and add the following line of code
  regions[REGION_MACHINE_NAME] = REGION NAME

So in this way, we can create many regions as our requirement.Now by adding these line and after clear the cache, we can see these region at block structure page and we able to assign blocks to these region but we can't see blocks on the page.Why????????
Because we haven't specified block region variable in page.tpl.php file. We have to print the region variable into page template file.
Just go to page.tpl.php file and just write the following code into template file, you need to keep in mind where are you witing this line.
<?php print render($page['REGION_MACHINE_NAME']); ?>


Hidden Regions

 Sometimes we need to create such block regions which are not allowed to a user place any block in it. we don't want to show these regions on block structure page or in simple words we can say that we don't want to allow the user to change the specific block placing on the page. What is the solution for this ???????
Yes, Hidden regions are there for helping us.
Hidden regions are not different functionality, it is similar to simple block regions.When we make a region as a hidden region then we can't see that region at block structure page.
Hidden regions are behaving same as simple regions except rendering on block structure page.

How to create hidden region, there are tow methods 

1. By theme.info file
regions_hidden[] = the_region_name
    Just writing this line into your theme.info file


2. By hook_system_info_alter()

We can make any region, hidden region by the help of this hook.

Just show your theme.info file there are two regions page_top and page_bottom, now see your block structure page, here you are able to see all block regions except both page_top and  page_bottom.
Why????

Just get the answer of this question, it will help you to understand the concept of hidden block regions.


If have any questions, please feel free to ask in comments.

Get Blogs from blogger using Blogger Api

Many times our requirements are to be fetched blogger's blog via Rest API. Thankful to google for providing  us an API for this.
So, what we have to do for this, we have to follow simple following steps.


  1. I hope you have an account on blogger and have some posts there. If not then first you have to create an account.Click here to signup.
  2. Now, signup for google api console.
  3. Create a project and select blogger API and get the api_key.
  4. Now you can get posts from your blogger account.
  5. There are many APIs like
    To get all posts
    GET https://www.googleapis.com/blogger/v3/blogs/BLOGGER_ID/posts?key=YOUR-API-KEY

    To get specific post
  6. GET https://www.googleapis.com/blogger/v3/blogs/BLOGGER_ID/posts/POST_ID?key=YOUR-API-KEY
  7. Similarly, you can apply many filters to access your blogs according to your requirements like recent 5 blogs, blogs with comments etc.For eg.
    GET https://www.googleapis.com/blogger/v3/blogs/BLOGGER_ID/posts/POST_ID?
  8. key=YOUR-API-KEY&maxResults=2&order=date
  9. For more detail visit https://developers.google.com/blogger/docs/3.0/using

Tuesday 11 April 2017

Get Social feeds (FB, Twitter, Youtube).

Getting Youtube video id using php curl For getting videos from youtube channel 1. Create an youtube api on https://console.developers.google.com 2. Get your account KEY. 3. Now goes to any youtube channel and inspect element and search out for "data-channel-external-id" value of this variable is your CHHANELID. 4. Now your arguments list is $option = array( 'part' => 'snippet,id', 'channelId' => CHHANELID, 'key' => KEY, 'order' => 'date', 'maxResults' => 2 ); Here you can change maxresult values as your requirements 5. Now make php curl request $url = "https://www.googleapis.com/youtube/v3/search?" . http_build_query($option, 'a', '&'); $curl = curl_init($url); curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, TRUE); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $json_response = curl_exec($curl); curl_close($curl); $responseobj = json_decode($json_response); Now get your data from $responseobj. You can more explore at https://developers.google.com/youtube/v3/getting-started#partial Getting data from facebook page 1. Get fb PAGEID Go to facebook page, right click on cover photo, copy link address and paste in url and extract pageid from here for eg. https://www.facebook.com/MaxHealthcareHospitals/photos/a.10150717461986834.457095.93226131833/10154143692526834/?type=3 Now here 93226131833 is page id. 2. Get your ACCESS TOKEN After that you have to make curl request $url = "https://graph.facebook.com/" . FBPAGEID . "/feed?fields=picture,message,id,created_time,link&limit=2&access_token=" . ACCESS_TOKEN . ""; Now, here in url you can define fields parameter whatever you want and you can set limit how many content you want. $curl = curl_init($url); curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, TRUE); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $json_response = curl_exec($curl); curl_close($curl); $responseobj = json_decode($json_response); now you can get your data from $responseobj. Getting data from twitter 1. Create an api on twitter https://apps.twitter.com/app/new 2. Get your OAUTH_ACCESS_TOKEN OAUTH_ACCESS_TOKEN_SECRET COUNSMER COUNSMER_SECRET SCREEN_NAME Screen name is the name of twitter handle for which you want to get data 3. $url = "https://api.twitter.com/1.1/statuses/user_timeline.json"; $oauth = array( 'screen_name' => SCREEN_NAME, 'count' => 2, 'oauth_consumer_key' => COUNSMER, 'oauth_nonce' => time(), 'oauth_signature_method' => 'HMAC-SHA1', 'oauth_token' => OAUTH_ACCESS_TOKEN, 'oauth_timestamp' => time(), 'oauth_version' => '1.0', ); $base_info = twt_build_base_string($url, 'GET', $oauth); function max_custom_block_build_base_string($baseuri, $method, $params) { $r = array(); ksort($params); foreach ($params as $key => $value) { $r[] = "$key=" . rawurlencode($value); } $base_url = $method . "&" . rawurlencode($baseuri) . '&' . rawurlencode(implode('&', $r)); return $base_url; } $composite_key = rawurlencode(COUNSMER_SECRET) . '&' . rawurlencode(OAUTH_ACCESS_TOKEN_SECRET); $oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, TRUE)); $oauth['oauth_signature'] = $oauth_signature; $header = array(twt_build_authorization_header($oauth), 'Expect:'); $options = array( CURLOPT_HTTPHEADER => $header, // CURLOPT_POSTFIELDS => $postfields. CURLOPT_HEADER => FALSE, CURLOPT_URL => $url . '?screen_name=' . SCREEN_NAME . '&count=2' , CURLOPT_RETURNTRANSFER => TRUE, CURLOPT_SSL_VERIFYPEER => FALSE ); $feed = curl_init(); curl_setopt_array($feed, $options); $json = curl_exec($feed); curl_close($feed); $twitter_data = json_decode($json); You can define limit of data in count field. function max_custom_block_build_authorization_header($oauth) { $r = 'Authorization: OAuth '; $values = array(); foreach ($oauth as $key => $value) { $values[] = "$key=\"" . rawurlencode($value) . "\""; } $r .= implode(', ', $values); return $r; }

Exploring your site usage via Google Analytics

Everyone wants to know how their website is performing, how many visitors they have on their site, etc. Google Analytics is one of the most stable solutions to achieve this. It lets you easily gauge at all stats of your website from the visitor perspective and provides you with useful data that can let you improve your website.

So how to use google analytics :
1.  Sign up for a Google Analytics account by following the link- http://www.google.com/analytics/
2.  On successful sign-up, you will be taken to a page that allows you to create a new account.
3.  You will have to enter some data in the form.
4.  After that you will get a tracking id in the format UA-XXXXXXXX-Y.
5.  Now there is option for js code so you will get js code from there and paste this snippet into your
pages which you want to track. There are many options providing by  google 'https://developers.google.com/analytics/devguides/collection/analyticsjs/'

<!-- Google Analytics -->
  <script>
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-XXXXX-Y', 'auto');
    ga('send', 'pageview');
  </script>
<!-- End Google Analytics -->

6. For configure this js snippet according your requirement please visit this
  'https://developers.google.com/analytics/devguides/collection/analyticsjs/how-analyticsjs-works'


In above js snippet there is ga() function which is used to send the data to google analytics. ga() function have the many arguments on the basis of that you can track your site as your requirement.
First argument is 'send' which means you have sending something and it is fixed argument.
Second argument may be 'pageview' or 'event' = On the every page there are many blocks and if we want to track each and every block seperataly then we have to use 'event' and if we want to track only page means how much time page is visited and form which pages to visited and how many users visited so we have to use 'pageview' .

Page view:-
In the pageview google track your whole page means how many time this page is visited, form which page you have to redirect to this page and how many users visited this page.There is snippet of js provided by google analytics which is to be placed in that page which you want to track.
This is function for pageview
'ga('send', 'pageview', location.pathname)'.
ga is fucntion which is send the page data to the google analytics.
send and pageview are the fixed parameter but you can change locaio.pathname by page url, page title.
for more detail 'https://developers.google.com/analytics/devguides/collection/analyticsjs/pages'

Event Tracking:-

Now on our site there are many block on a single page and we want to categorized them so we can analysis them in better way, for that we have to categorized them and have to write event tracking code for each and every event.
We want to track an activity on page without reload the page. Downloads, mobile ad clicks, gadgets, Flash elements, AJAX embedded elements, and video plays are all examples of actions you might want to track as Events.
For this you have to use event tracking method
'ga('send', 'event', [eventCategory], [eventAction], [eventLabel], [eventValue], [fieldsObject])'

Send and event are fixed parameter.
We take a condition like there is social share a block which have social share icons like (fb, twitter, linkedin), now,
[eventCategory](REQUIRED) = category name(You have to categorized the events like there is event category name is "SOCIAL SHARES" )
[eventAction](REQUIRED) = "CLICK"
[eventLabel] = "ICON TITLE(LIKE FACEBOOK, TWITTER) OR LINK"
[eventValue] = "ANY NUMERIC VALUE"
[fieldsObject] = In some cases you might want to send an event as a non-interaction event then set the value true.
(https://support.google.com/analytics/answer/1033068#NonInteractionEvents)

For more detail 'https://developers.google.com/analytics/devguides/collection/analyticsjs/events'

Google analytics for Drupal sites.
1. Install the module google_analytics(https://www.drupal.org/project/google_analytics)
2. Configure it and set the tracking id.
3. There are some options available you can configure according your requirement.
4. This module is sufficient for tracking page views.
5. If you want to tracking event theve to  you hacinstall google_analytics_et module (https://www.drupal.org/project/google_analytics_et).
6. Now write a custom module and write a hook 'hook_google_analytics_et_api()'
7. It returns a array which has some keys like
  'event', 'selector' ,'category' 'action', 'label', 'value', 'noninteraction'

  For example:-
  $selectors = array(
    array(
      'event' => 'mousedown',
      'selector' => '.menu-block-wrapper.menu-name-menu-call-to-action li a',
      'category' => 'CTA',
      'action' => 'click',
      'label' => '!href',
      'value' => 0,
      'noninteraction' => TRUE,
    ),
    array(
      'event' => 'mousedown',
      'selector' => '#block-follow-site .follow-links a',
      'category' => 'Social icons',
      'action' => 'click',
      'label' => '!href',
      'value' => 0,
      'noninteraction' => TRUE,
    ),
  )


For label there are some option
!text
 This is what would be returned from the jQuery .text() method.
!href
 The value of the href attribute (handy with anchor tags).
!currentPage
 The URL of the current page (this is taken with the code window.location.href

8. Now GA is ready for your drupal site.