How to disable account related e-mails in Drupal 7

Drupal 7 provides 8 basic email templates for registering, cancellation & password recovery. These settings we can find at ‘admin/config/people/accounts’ page.

account-seting-mail

In these templates, some of following templates has option to disable( checkbox above subject field ).

  • Account activation
  • Account blocked
  • Account canceled

But other templates by default enabled & those cannot be disabled through UI. So incase we don’t want these template then we can do it through programmatically by using hook_mail_alter(). 

In one of case we didn’t wanted to send default “Welcome (no approval required)” email template as we were using Rules to send custom email with some attachment. There is no option to send attachment in default email.

Now let’s look into the simple code how we can disable that. And later I will explain how we can disable for other default templates too. We have created module called no_emails.

/**
 * Implements hook_mail_alter().
 */
function no_emails_mail_alter(&$message) {
  if ($message['key'] == 'register_no_approval_required') {
    $message['send'] = FALSE;
  }
}

Here register_no_approval_required is the message key for ‘Welcome (no approval required)’ template, Following are other message keys in case if you want to disable them.

  • register_admin_created: Welcome message for user created by the admin.
  • register_no_approval_required: Welcome message when user self-registers.
  • register_pending_approval: Welcome message, user pending admin approval.
  • password_reset: Password recovery request.
  • status_activated: Account activated.
  • status_blocked: Account blocked.
  • cancel_confirm: Account cancellation request.
  • status_canceled: Account canceled.

Similarly we can disable Welcome (new user created by administrator) email template using below snippet.

/**
 * Implements hook_mail_alter().
 */
function no_emails_mail_alter(&$message) {
  if ($message['key'] == 'register_admin_created') {
    $message['send'] = FALSE;
  }
}

We have learned how can we disable Welcome (no approval required) template & Welcome (new user created by administrator) templates. You can use above mentioned message keys to disable other default email templates also.

How to get dynamic or Custom page titles in Drupal 7

Recently I was working in a project where we needed to show page title in format of [ node count associated with taxonomy term] [taxonomy term page is associated with] | [site name]. By default drupal 7 provides page title “term name | site name” for term pages. Our requirement was to get page title 125 vegetable recipe blog | my site name. Here 125 is node count of vegetable recipe tag. This is how we have  achieved this using  hook_preprocess_html().

Let’s create module called custom_title & create function custom_title_preprocess_html as follows in custom_title.module file.

/**
 * Implements hook_preprocess_html().
 */
function custom_title_preprocess_html(&$variables) {
  // Make sure current page is taxonomy/term/tid
  // In case if you use alias then you can use these way
  // Let’s say your term page is vegetables/tomato then use like
  // if( arg(0) = 'vegetables' && count(arg()) == 2 ){
  // and alternatively change loading term from name to tid
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    //loading term by tid
    $term = taxonomy_term_load(arg(2));

    //get node count by replacing token value
    $term_node_count = token_replace('[term:node-count]', array('term' => $term));

    //get site name
    $site_name = token_replace('[site:name]');
    $head_title = $term_node_count . " " . $term->name." blogs | " . $site_name;

    //add title
    $variables['head_title'] = $head_title;
  }
}

Now just enable this module and clear your Drupal cache. You should see  your page title like “ 125 vegetable blogs | site name ”. 

Similar to above example you can change page title like “Page Title | Krishna blog” using hook_preprocess_html(). In this case Krishna is node author. Custom or dynamic page title for node pages:

/**
 * Implements hook_preprocess_html().
 */
function custom_title_preprocess_html(&$variables) {
  // Make sure current page is node/nid
  // It will even if use aliases.
  if(arg(0) == 'node' && is_numeric(arg(1)) && count(arg()) ==2){
    //load node from nid
    $node = node_load(arg(1));
    //load user from uid
    $user = user_load($node->uid);
    //add title
    $head_title = $node->title . " | " . $user->name . " blog";
    $variables['head_title'] = $head_title;
  }
}

The way we have customized node page title & term page titles, similarly we can use hook_preprocess_html() hook to customize other page titles like user pages, search page titles or any custom pages.

Customizing node access in drupal 7

Drupal 7 provides accessing of nodes by roles & its permissions, The permissions can be set to different roles & based on permission nodes can be accessible for different operations like view, delete, create & update.

Let’s say we have content type ‘article’ & we have roles  HOD, CR, Student. And we have permissions set to Student role as can ‘view the published article’. CR role has permission that ‘can view published article & can edit own article’.

But in case of we need custom permission scenarios, lets discuss some examples -

  • If student is author then student can edit own article when it is in unpublished state
  • CR role wants to edit own article & Students articles (For unpublished state)

These are some scenarios where permissions will not give options to do these.

We came across some hooks in drupal 7 & found hook_node_access($node, $op, $account). Let’s discuss how we can achieve above scenarios. Create a module called custom_node_access.

Scenario 1 : If student is author then student can edit article when it is in unpublished state

/**
 * Implementation of hook_node_access().
 * 
 * Scenario 1 : If student is author then student can edit article when it is in unpublished state
 */
function custom_title_node_access($node, $op, $account) {
  // get type of node.
  $type = is_string($node) ? $node : $node->type;
  // Check content type is article
  if ($type == 'article') {
    // Check node object is loaded
    // Check node status is unpublished
    if (isset($node->nid) && $node->status  ==  0) {
      // Check operation is update
      if ($op == 'update') {
        // Check user is student
        // Here 2 is student role id
        if (array_key_exists(2, $account->roles)) {
          // Check node author & logged in user are same
          if($node->uid == $account->uid){
            // Access student to update these node
            return NODE_ACCESS_ALLOW;
          }
        }
      }
    }
  }
}

Scenario 2 : CR role wants to edit own article & Students articles (For unpublished state)

/**
 * Implementation of hook_node_access().
 * 
 * Scenario 1 : CR role wants to edit own article & Students articles (For unpublished state) 
*/
function custom_title_node_access($node, $op, $account) {
  // get type of node.
  $type = is_string($node) ? $node : $node->type;
  // Check content type is article
  if ($type == 'article') {
    // Check node object is loaded
    // Check node status is unpublished
    if (isset($node->nid) && $node->status == 0) {
      // Check operation is update
      if ($op == 'update') {
        // Check user is CR
        // Here 3 is CR role id
        if (array_key_exists(3, $account->roles)) {
          // load node author's user object
          $node_author = user_load($node->uid);

          // Check node author & logged in user are same
          // or node author is student (Here 2 is student role id)
          if($node->uid == $account->uid || array_key_exists(2, $node_author->roles)){
            // Access student to update these node
            return NODE_ACCESS_ALLOW;
          }
        }
      }
    }
  }
}

My First Tryst with creating a Drupal 8 Module 'Demo'

I spent the whole day trying to do something that I've been wanting to for quite some time now. I went through the changelog for Drupal 8 to see if I could build an initial level of custom modules in D8 and I would love to share what I have learned so far. Let us take a look at this simple D8 module (that really does nothing other than printing a 'Hello World' ) called 'demo'.Here I have listed out the steps involved while creating the Module with some inline explanation.

Step 1:

Create a Custom folder inside  /modules/custom/. Under Custom we have to create .info.yml (holds basic information about module). & .routing.yml (holds menu link and permission access). And then you need to create Controller.

Drupal 8 uses the Symfony HTTP Kernel, a system which gets the request and asks other systems to produce the requested output (a response object) and sends the response back to the client. The output is generated by a piece of code called the controller. In theory the controller can be either a pure PHP 4 function, a method on an object or even an anonymous function.

The second part of creating a page that outputs our content is to put the page controller in place. This could be a PHP 4 style function, but best practice in Drupal 8 is to use a controller class. This class is in a file named exactly after the controller provided in the routing file, ExampleController.php

For the above router the class needs to be placed in example/src/Controller directory and with name ExampleController.php. So the full path will look like, example/src/Controller/ExampleController.php.

Syntax: use src/ & Controller/ folder inside module directory(As per PSR-4 standard).

The .info file has been converted to YAML. This is the Symfony YAML component. So, the new file extension is .info.yml

For assignment = changed to :

For dependencies, use following format:

dependencies:
- block

For comment # changed to ;   

type key is required with values,indicate the extension.(e.g: module/theme).

name: demo
description: 'Demo module for Drupal 8'
type: module
core: 8.x

routing.yml is used to define routes and for handling the callback function.

Line 1:

Line 2: Path you want to register

Line 3: having Default page _title and _content refers to DemoController with method name demo

Line 4 : provide Permission.


 

Step 2:

The second part of creating a page that outputs our content is to put the page controller in place. This could be a PHP 4 style function, but best practice in Drupal 8 is to use a controller class. This class is in a file named exactly after the controller provided in the routing file, ExampleController.php

Create controller DemoController with a method demo( )

Create src/ & Controller/ folder inside module directory.(src/ is a PSR-4 standard).

Controller/ is a place to store controller. Create DemoController.php


On top, I have specified the class namespace.

Inside Controller class , we have demo( ) method. Which is rendering array.

To view the output all we need to do is clear the cache and navigate to mysite-name/demo

Download module using Github:  git@github-name:xaiwant/drupal8.git

We at Valuebound are committed to furthering your business initiatives with our Enterprise level web solutions. For further information on our service offerings, please Contact us.

Optimize your Email Marketing Campaigns : Five Automation Tools that Drupal Integrates With

We have seen the digital age unfold at a rapid pace in the last decade with newer technologies taking over the evolving digital marketplace. Marketing campaigns today are spearheaded by tools that range from basic email marketing software to sophisticated cross channel campaign tools/marketing platforms. While investing in an Email marketing software it is crucial that you have already analysed its features, drawbacks and price points. Here we have a look at some popular email marketing solutions that you can integrate your Drupal website with.

Wildfire Email Marketing Platform

wildfire

 

An easy to use email marketing system, the Wildfire Email Marketing Platform readily integrates with a website to let you send bulk emails to the subscribers. The client module for the Wildfire platform runs as a part of your Drupal website and provides you with multiple features like mail template, list management and job tracking tools. The entire mail creation process is automated as Wildfire creates mails for you based on the choice of stories/articles that you want to include in your mail. A verification system ensures that the Wildfire broadcasts are sent to the correct email addresses.

Mailchimp

Mailchimp

 

This email marketing application lets you choose from around 400 templates along with a drag and drop editor for easy to frame, aesthetic email layouts. The additional advantages of using the Mailchimp email templates is that they are optimized and responsive for mobile devices. You can easily code your email directly with the help of HTML and inline CSS. The fact that Mailchimp uses an open API makes it easier for other softwares and platforms to integrate with it quite easily.

The Mailchimp Modulelets the Drupal based website users to manage and control the email list that they want to be included in. It lets you generate and send Mailchimp email Campaigns from a Drupal based website. The core module provides all of the API integration functionality with the option to add your MailChimp API key and get the settings right.

Campaign Monitor

monitor

 

Another email marketing tool that is easy to use and quite efficient in keeping the data well organized, Campaign Monitor also lets you exercise creativity while crafting presentable emails. It offers you the options of using preset templates and customizing the template designs. The option of using the HTML code while formatting. It comes equipped with a great user interface, reliable mail delivery and various integration options.

Campaign Monitor integrates easily with Marketing Automation tools like Salesforce. Other interesting features include the option of sending a split test to gauge the reactions of people to different content/ topics and senders. An email can be previewed to see what it will look like on a different device and to ensure that the mail is delivered in accordance with the specific preferences of your audience. Your Drupal based website can be integrated with the Campaign Monitor API to provide the users with the option of subscribing and unsubscribing from an email list with the help of the Campaign Monitor Module.

Interspire Email Marketer

intersprise

 

A comprehensive email marketing solution, Interspire lets you create and send mails letting you create and send mails while tracking the entire process along with the ROI from the email marketing initiative. It automates the entire process and also uses autoresponders to send personalized messages to your leads during different stages of lead nurturing. You have the option of removing inactive leads from the mailing list as the list management is an entirely automated process that ensures. This automation tool ensures that your prospects are kept in the loop and are sent follow up email after they have clicked open their first mail. There are multiple features like bounce processing and tracking feedback with customized surveys and feedback forms.

The EMF Interspire module is a valuable extension to the Email Marketing Framework Module and is meant to support the Interspire Email Marketer mass mailing platform. There is also a plugin available for Interspire Email Marketer (IEM).

Addemar Email Marketing Software

a_email

 

This email marketing application is equipped with an exceptional user friendly interface and handy templates to create quality emails. It has unlimited options for customization like image personalization and “purls” or personalized URLs. Addemar can be used to send mails with dynamic content to a segmented list of recipients with options to evaluate the results. You can further customize the mails with automation features wherein emails can be generated with reminders to help in tracking the feedback for them. It also issues an Interactivity Report and a deliverability report to measure the effectiveness of your email messages.

The EMF Addemar Plugin lets you integrate your Drupal website with the Addemar Email Marketing software.

Emma's Drupal email marketing integration

mail

 

In case you have a host of events lined up every now and then, that you would like to communicate about to your subscribers on a regular basis, Emma’s Email Marketing integration is the perfect solution for you. The special templates have been designed to send emails to the contacts informing them of the upcoming and important events.

Emma’s Drupal email marketing integration lets you add Emma subscription forms to your Drupal Website in order to This tool is specifically meant for start-ups and small businesses and integrates easily with Google Analytics and other social media sites. It makes it an effortless task to interpret response reports from an email marketing campaign to help transform them into usable insights and actions.

With a wide range of email Marketing APIs to choose from, it gives you the freedom of extending the functionality of your applications by integrating the email marketing components for a seamless performance of the procceses. It would be good thinking to choose an email marketing application that is flexible enough to grow in sync with your organizational goals, accommodating a growing subscriber list and intermittent mass mail campaigns.

We at Valuebound understand your unique business needs to come up with custom enterprise level web solutions. For further information on our service offerings, please Contact Us.

Content Marketing Metrics : Ways to measure the KPIs of your Content Efforts

Gone are the days when you would keep your intel guarded only to reveal it to the right prospect or to a frequent customer. Content Marketing lets you flaunt your industry specific knowledge in the form of content efforts directed towards a target audience. The ultimate aim of investing in a Content Marketing initiative is to come up with solutions that cater to your organizational goals. Once you have identified the objective for content creation/curation and delivered on the commitment to solve your audience’s pain points, what follows is the evaluation of your content’s performance.

The KPIs (Key Performance Indicators) for a Content Marketing initiative help you measure or rather evaluate the reach and impact of your content. The best content decisions are based on the information sourced from the feedback provided by the evaluation of relevant content metrics. Here we have a look at some of the major performance indicators that come in handy while measuring your content’s performance across the entire sales funnel.

Consumption Metrics : Know how your Content is being Consumed

When you repurpose your content in different formats to get traction on multiple channels, the focus of your efforts must lie on generating more page views and engaging unique visitors. Infographics, downloadable PDF files, expert interviews, whitepapers, infographics, videos and podcasts are content assets that are searched for and widely consumed by a web audience. While page view analytics lets you know the exact web-pages that are generating more web traffic, the unique visitor analytics gives you an idea about the visitors who return to your web properties for more engaging content.   

Then there is the Average time on page analytics that gives an insight into the number of people who are actively consuming your content. You can also study the browsing behaviour of your audience, that is if they are really reading through your article or just hopping across the web pages. If you want to identify the behaviour patterns and preferences of your audience, mining the analytics for the same would be the best way to get a hold of the kind of content that drives in the traffic.

Your content may be gated wherein it is locked behind a subscription/registration form. This helps you measure form completions and the frequency of registration forms being filled out with valid contact information. Meanwhile content assets that are indexed separately from a landing page become directly accessible from a browser’s search results, making it ungated.

Engagement Metrics: Engagement Rates for your Content Assets & Social Media Posts

Does your content engage your audience enough for them to pay heed to a call of action? Bounce rate, social shares, comments and the average time spent on the site are all indicators of the level of engagement you have with your readers. The feedback from your audience in the form of social media shares, clickthroughs for content sent via mail, comments and fan mail, clearly shows how engaged your audience is with your content. The more they want to connect with you through different social media platforms and communication channels, signifies the level of positivity they have for your content assets.

Google Analytics has a feature called Average session duration that lets you measure the "engagement hits" or the length of time a visitor spends on your site browsing through multiple pages.The sharing metrics let you identify the content pieces that are being actively shared along with the specific audience that is sharing it.  

Lead Generation Metrics : Generating Leads through Content Marketing

What defines the success of a content marketing campaign is the number of qualified leads that it generates during this “middle of the funnel activity”. There may be certain pieces of content that can be used in sync with a marketing automation tool to generate leads online. The qualified leads generated are then passed onto the sales team. According to Dharmesh Shah, CTO, Hubspot, the quality of leads generated through content efforts are much higher and the costs associated are minimal as opposed to lead generation through the paid channels.

An investment in content creation has become an indispensable part of the inbound marketing process as organizations today are increasingly deviating towards content marketing to pass on the messages to their audience. Google Analytics has a Goal Tracking option that lets you configure goals while tracking multiple conversion types with the help of metrics that helps you break them down based on their level of sales readiness.

Sales Metrics : How your content affects the bottom of the Funnel

You need to assign a context to the metrics for them to make sense. There is nothing like a combination of a well documented content strategy and some clearly measurable goals to spearhead a content marketing campaign. One of the best metrics to evaluate the content efforts are the sales metrics, as a content strategy is developed with the pivotal aim of driving sales success. The Sales Metrics help you measure the impact of your content on the sales pipeline. It lets you track how the consumption of your content influenced a content marketing campaign, ultimately leading to sales success.

Retention Metrics : Evaluating the levels of Audience Engagement

Retention Metrics let you track your content’s ability to hold onto your audience’s attention after an initial visit to your web properties. A comparison of the consumption and the retention metrics gives a clear indication of whether your content is effective enough in inspiring an audience to connect with your brand. It also tracks your web audience that keeps returning to your content, along with the frequency of these return visits and their willingness to subscribe to receive your content in future.

Operational Metrics: Metrics that really matter( Production and ROI)

A Report by Content Marketing Institute and  MarketingProfs indicates that a list of key challenges faced by Content Marketers include  a lack of time(69%), inadequate production of content(55%) and difficulty in generating engaging content(47%). Employee participation is a key operational metric which can be used in the early stages of a content marketing campaign to measure its rate of progress. The Production metrics provide an internal assessment of your content operations like adherence to editorial calendardeadlines and goals along with the performance of your content marketing team. Meanwhile the cost metrics help you in calculating the ROI for your content marketing efforts. It lets you assess the costs involved in producing, distributing and promoting the content assets like blog posts,whitepapers and newsletters etc.

While navigating through a content marketing journey you would have to track the KPIs to make sure that your content efforts are on the right track. KPIs are instrumental in letting you assess your current capabilities that include content generation skills, the ability to integrate third party tools and the use of advanced technologies to further a content marketing campaign in the right direction.

We at Valuebound keep a tab on the latest B2B content marketing trends and developments to provide you with Enterprise level web solutions to boost your digital marketing initiatives. For more information on our service offerings, please Contact Us.

How to use node api hooks in drupal 7

A hook is a PHP function that has a defined set of parameters and a specified result type. When you are implementing a hook in a module you are allowing it to interact with Drupal core. Drupal’s module system is based on the concept of hooks and the Node API in Drupal has a vast collection of hooks to help you work with nodes to add data or custom content. You can also extend node structures to include new fields or even establish new node types.

Underlying Concepts in Drupal API

The concepts in Drupal API are largely interdependent as one ceases to exist without the other. The Entity API is instrumental in creating lightweight and flexible Drupal solutions.

# Entity Type

The field system comes into play in Drupal 7 as you get to add fields to entity types like Nodes(content), Comment, User Profiles & Taxonomy Terms.

# Bundle

A subtype of an entity type, bundles are an implementation of the entity type to which you can attach the fields. But not all entity types have bundles, for instance Taxonomy does not have separate bundles(subtypes). Although many entity types do not allow bundles by default, you can still create bundles and with the help of the Field system add different fields to each bundle.

# Entity

An instance of a particular entity type like a taxonomy term or a bundle , you can load any entity using entity_load. The Entity API module lets you save or delete a function as there are options like entity_create(), entity_save(), entity_delete(), entity_view() and entity_access().

# Fields

A field is a primitive data type that can be added to entity types or bundles to help organize the content. It has custom validators and widgets for editing content and formatters to alter the display.

You can invoke several sets of hooks during the node operations based on the create, update, view and delete options. These hooks allow the modules to modify the base node operation and can be categorized into the following types :

# Node-type specific hooks
# All module hooks
# Field hooks
# Entity hooks

# Creating

  1. Function hook_node_presave
    You can invoke this hook from node_save() before the node is saved in the database. This hook is invoked when a node is being inserted or updated.
    /**
    *
    * Implements hook_node_presave()
    *
    * Create Page @ node/add/page, Page title will be saved with date extension.
    *
    * Act on a node being inserted or updated.
    *
    * This hook is invoked from node_save() before the node is saved to the
    * database.
    *
    * @param $node
    * The node that is being inserted or updated.
    *
    * @ingroup node_api_hooks
    */
    function hook_node_presave($node) {
      dpm($node);
      if ($node->type =='page' && $node->is_new) {
        // Alter title, add time stamp at the end of title:
        $node->title = $node->title.' '.date('M j Y h:i A');
        }
        // Remove $node->is_new to call at node updation time
    }
    
  2. Function hook_node_insert
    You can invoke this hook from node_save() after the database query meant to insert the node into the node table has been scheduled for execution. Before invoking this hook you will have to invoke type-specific hook_insert and call the field_attach_insert().

    You need to note that the write/update database queries executed from this hook are not committed immediately as you should not be relying on the data in the database when a transaction is still in process. If you want to trigger a mail or create any other event, you can use hook_node_insert for the same.

    /**
    *
    * Implements hook_node_insert()
    *
    * Act on a node being inserted.
    *
    *
    * @param $node
    * The node that is being inserted.
    *
    * @ingroup node_api_hooks
    */
    function node_api_node_insert($node) {
      dpm($node);
      if ($node->type =='page' && $node->is_new) {
        // after creating a new node the message is displayed with node id:
        drupal_set_message("Thanks for creating a page, your node id is" . $node->nid);
      }
      // Remove $node->is_new to call at node updation time
    }
    

# Updating

  1. Function hook_node_presave
    This hook acts on a node when it is being inserted or updated.  You can invoke the hook from  node_save() before saving the node to the database.
    /**
    *
    * Implements hook_node_presave()
    *
    * Create Page @ node/add/page, Page title will be saved with date extension.
    *
    * Act on a node being inserted or updated.
    *
    * This hook is invoked from node_save() before the node is saved to the
    * database.
    *
    * @param $node
    * The node that is being inserted or updated.
    *
    * @ingroup node_api_hooks
    */
    function node_api_node_presave($node) {
      dpm($node);
      if ($node->type =='page') {
        // Alter title, add time stamp at the end of title:
        $node->title = $node->title.' '.date('M j Y h:i A');
      }
      // Remove $node->is_new to call at node updation time
    }
    
  2. Function hook_node_update
    You can invoke this node from node_save() after invoking the type-specific hook_update() and calling the field_attach_update().
    /**
    *
    * Implements hook_node_update()
    *
    * Update Page @ node/nid/edit , Page title will be saved with  current date extension.
    *
    * Act on a node being inserted or updated.
    *
    * This hook is invoked from node_save() before the node is saved to the
    * database.
    *
    * @param $node
    * The node that is being updated.
    *
    * @ingroup node_api_hooks
    */
    function node_api_node_update($node) {
      dpm($node);
      if ($node->type =='page') {
        // Alter title, add time stamp at the end of title:
        $node->title = $node->title.' '.date('M j Y h:i A');
      }
      // In this node title with Updated date time extension 
    }
    

# View

  1. Function hook_node_view This hook acts on a node that is being assembled before being rendered.
    /**
    *
    * Implements hook_node_view()
    *
    * When View Page, Image style  will be change.
    *
    * Act on a node being viewed.
    *
    * @param $node
    * The node that is being view.
    *
    * @param $view_mode
    * The view mode of node.
    *
    * @param $langcode
    * The language of node.
    *
    * @ingroup node_api_hooks
    */
    function hook_node_view($node, $view_mode, $langcode) { 
      if($view_mode == 'teaser') {
    	$node->content['field_image'][0]['#image_style'] = 'demo_image';
      }
    
  2. Function hook_node_view_alter
    You can call this hook after assembling the content in a structured array. This hook may be useful to carry out the processing part that requires you to complete building the entire node content structure. You can add a post_render callback using this hook if you want a module to act on the rendered HTML of the node instead of a structured content array.
    /**
    *
    * Implements hook_node_view_alter()
    *
    * when view page altering the weight.
    *
    * Act on a node being viewed.
    *
    * @param &$build
    * The node that is being view.
    * @ingroup node_api_hooks
    */
    function hook_node_view_alter(&$build) { 
      if ($build ['#view_mode'] == 'full' && isset($build ['field_image'])) {
        // Change its weight.
        $build ['field_image']['#weight'] = -10;
      }
    

# Delete

Function hook_node_delete

This hook is invoked from node_delete_multiple() after you have invoked the type specific hook_delete(). You need to invoke this hook prior to calling hook_entity_date and field_attach_delete() and before you remove the node from the node table in the database.

/**
*
* Implements hook_node_delete()
*
* Act on a node being delete.
*
*
* @param $node
* The node that is being delete.
*
* @ingroup node_api_hooks
*/
function hook_node_delete($node) {
  // after deleting a node the message is displayed.
  drupal_set_message(“Node Deleted Successfully”);
}

# Prepare

Function hook_node_prepare

This hook acts on a node object about to be shown on the add/edit form. After you have invoked the type specific hook_prepare() you can follow it up by invoking this hook from the node_object_prepare().

/**
*
* Implements hook_node_prepare()
*
* when view page altering the weight.
*
* Act on a node being insert or update.
*
* @param $node
* The node that is being insert or update.
* @ingroup node_api_hooks
*/

function hook_node_prepare($node) {
  if (!isset($node->comment)) {
    $node->comment = variable_get("comment_$node->type", COMMENT_NODE_OPEN);
  }
}

# Validate

  1. Function hook_node_validate
    This hook performs node validation before the creation or updation of a node. It is invoked from node validate after you have finished editing the node before previewing or submitting it. The standard validation steps are followed by the invocation of the type specific hook_validate() after which the node_validate is invoked.
    /**
    *
    * Implements hook_node_validate()
    *
    * When node is being inserted.
    *
    * Act on a node being inserted.
    *
    * @param $node
    * The node that is being inserted.
    *
    * @param $form
    * The node form.
    *
    * @param $form_state
    * The node form_state.
    *
    * @ingroup node_api_hooks
    */
    function hook_node_validate($node, $form, &$form_state) {
      if (isset($node->field_date_end) && isset($node->field_date_start)) {
        if ($node->field_date_start > $node->field_date_end) {
          form_set_error('time', t('An event may not end before it starts.'));
        }
      }
    }
    /**
     *  Implements hook_node_load
    */
    function hook_node_load($nodes, $types) {
    global $user
    // check to see if the person viewing the node is the author, if not then hide the
    // annotation
    }
    
  2. Function hook_node_load
    This hook is used to add information that is not in the node/node revisions table. Although it adds information to the node object, it does not replace the information in the node tables which could interfere with the entity cache.
    /**
     *  Implements hook_node_load
    */
    function hook_node_load($nodes, $types) {
    global $user
    // check to see if the person viewing the node is the author, if not then hide the
    // annotation
     foreach ($nodes as $node) {
        if ($user->uid != $node->uid) {
           unset($node->article);
        }
     }
    

P.S.- In the examples above replace “hook’ with your module’s name.

Reference:
https://www.drupal.org/node/1261744
https://api.drupal.org/api/drupal/modules!node!node.api.php/group/node_api_hooks/7

A Step by Step Guide to Drupal 7 Custom Theme Development

A Drupal theme is a collection of files that provides a presentation layer for a Drupal website. In my opinion the user experience and the user interface when combined with theming are as important as the backend architecture. It does not mean only writing the style.css files with random HTML markups. You can create a basic theme for your website quite effortlessly as all you need is a .info file and a css file. The files can be added to the theme, based on your requirements to have a better control while executing what you want your end user to see.

Here I am sharing my first experience at creating a Drupal theme which I hope will be useful for budding web developers.

The Theme Folder Structure

The first thing that you should be aware of is the folder structure in Drupal 7. The core themes that come shipped with the Drupal installation are placed in the themes directory of root folder. It is advisable to place all the extra themes in sites/all/themes directory. Meanwhile it is a good practice to place all the downloaded themes called themes in a separate folder called along with the custom themes in a folder called custom.

This is what a typical folder structure will look like :

..
..
sites
..all
….themes
…...contrib
……..bluemarine
……..omega
…...custom
……..blue
……..blue_admin

Drupal theme structure explained

A basic pictorial representation of the Bartik theme.

Source: https://www.drupal.org/node/171194

Overview of Theme Files>

The files associated with creating a theme are a mix of “one” text file (that is the .info file), PHP script, Javascript and Cascading Style Sheet file i.e CSS file.

Of all these files, the one you require is the .info file which tells Drupal about your theme. Though a CSS file is also necessary without which theme will look like a bunch of black text and images thrown in a webpage. All the other files are to make the theme more gripping and to customize the UI according to the palette. Below is the list of files that a theme can contain:

  • .info — A required file which provides information about the theme.
  • html.tpl.php—It displays the basic html structure of a single Drupal page.
  • page.tpl.php — The main template that defines the content on most of the pages.
  • style.css — The CSS file that sets the CSS rules for the template.
  • node.tpl.php — This file defines the content of the nodes.
  • block.tpl.php — It defines the content in the blocks.
  • comment.tpl.php — It defines the content in the comments.
  • template.php—It can be used to hold preprocessors for generating variables before they are merged with the markup inside .tpl.php files.
  • theme-settings.php—You can modify the entire theme settings form.
  • logo.png — Your logo, if you are using one.
  • screenshot.png — This is a screenshot of your theme that is used in the admin panel and in the user account settings if you have enabled more than one theme so that visitors can choose which theme they want to use.

...And this is how we do it

Now that you have got some idea about the files,let’s get started by creating a basic theme with custom regions, a CSS3 slider and a superfish dropdown menu. I am going to walk you through the process step by step based on how I went about it the first time.

Step I : Creating the .info file

The .info file is a static text file wherein you can provide information about the theme and specify CSS and javascripts that you would like to include. You can also specify features and toggle settings although it is a completely optional. This is how a .info file will look like :

name = Blue
description = A Custom Drupal 7 Theme
core = 7.x
regions[header] = Header
regions[banner] = Banner
regions[content] = Content
regions[sidebar] = Sidebar
regions[footer] = Footer

You may note that only the name and core is needed while everything else is optional. So, create a text file, enter the above lines and save as YOUR_THEME_NAME.info. Now your theme will appear under the theme list. Enable and set default to use the theme.

Lets have a look at the layout of the theme.

Custom Drupal Theme

P.S. : You won’t get the exact same result as you have not applied any CSS to the regions.

Step II : Creating page.tpl file

page.tpl is all about how a drupal page would look and where and how do you want to render the contents and the regions.

This is how you get it started :

IFrame

As you can see in the code, I have printed by main-menu using php in the header. Make sure you have created your main menu and added links to it. You can also create some content and blocks and assign them to regions.

Step III : Creating style.css

name = Blue
description = A Drupal 7 Theme for practice
core = 7.x
stylesheets[all][] = css/style.css
regions[header] = Header
regions[banner] = Banner
regions[content] = Content
regions[sidebar] = Sidebar
regions[footer] = Footer

To add a  CSS file to your theme,you must include the line

stylesheets[all][] = css/style.css.

You should make sure that you have given the right path.You can do the styling of your theme according to your design. Here’s how I have written my CSS :

IFrame

Step IV : Adding Javascript

name = Blue
description = A Drupal 7 Theme for practice
core = 7.x
stylesheets[all][] = css/style.css
scripts[] = js/theme.js
regions[header] = Header
regions[banner] = Banner
regions[content] = Content
regions[sidebar] = Sidebar
regions[footer] = Footer

scripts[] = js/theme.js

You have to use Javascript and CSS in order to make your drop menu function properly.There are a number of Javascript plugins to choose from. For my theme I chose superfish js plugin. You can implement the js library in two ways, one is by adding the js library from web within a

TIL – Access Object Properties via Variable

I have been struggling hard since morning as I try to figure out something that was pretty simple in the end . The goal was to create a node object by adding the node field object properties dynamically. Everything looked fine but still it was not adding up.

After burning nearly 4 hours I figured out what was wrong and now it seriously makes me feel like a noob :(

So lets say we have an object $obj which has a property test. So basically to put in data in the object we can access it like this and put in the value.

$obj->test = "Blah Blah!!"

But in my case I needed to insert the data accessing the property via a variable. I was trying to go about it like :

$obj->test = "Blah Blah!!"

And was getting error of illegal string offset.

After having tried to make it work in innumerable ways that went in vain, I finally got the solution.

What I had to do was to wrap the variable to make it accessible by the object.

So the proper working way came around as this:

$obj->{$test} = "Blah Blah!!"

Again, feeling like a noob in PHP programming after this. But it feels great because there is always something to learn everyday. #FeelingOptimistic :)

Reference :
http://stackoverflow.com/questions/3515861/how-can-i-access-an-object-property-named-as-a-variable-in-php
https://imalabya.wordpress.com/2015/04/10/til-access-object-properties-via-variable

Do your Content Marketing Efforts measure up with your User Engagement Goals?

If you are looking to rev up a content marketing campaign to improve your user engagement metrics, you might as well put in some thought into tweaking your Content Engagement Strategy. Successful content strategies center around the preferences of your target audience wherein the communication is focused on what they are interested in. Online content that caters to your target audience can be dished out in different formats(infographics, e-books, brochures, videos, podcasts) to involve them in spontaneous conversations which can be a real-time feedback for your content marketing efforts.

Let’s have a look at the ways in which you can reach out to your target audience with some value-adding content marketing efforts.

# Create a Content Engagement Strategy

Once you have established yourself as a thought leader, the next immediate task would be to engage your audience’s attention on a consistent basis. While developing an engagement strategy you are obligated to put in efforts to create content themes and topics based on an in-depth research. Your content should be of value to your audience as you continue progressing through different stages of your content marketing program. Quality matters, so don’t end up mass producing content instead of focusing on its uniqueness quotient.

# Define Your Customer Segments

One of the key elements in content marketing is maintaining a sharp focus on your customer segment. Although digital marketing affords you the luxury of reaching out to a much larger audience, a sound content marketing strategy would be to concentrate your efforts on driving home the message to a single customer segment. The task of aligning your content marketing strategy with targeted pitching will help you identify your target buyer persona in the long run.

# Establish a Connect Between the Content & Your Audience

Content is an effective medium to build some online credibility. The engagement factor in content marketing can be a measure of your performance as a thought leader. According to a study by Aol & Nielson approximately 27,000,000 pieces of content are shared across the web space each day. Your audience plays the dual role of an influencer and a curator while sharing your content across different social media platforms. This makes it an imperative to deliver the message convincingly with a certain knack for creativity as the audiences today have a built-in BS detector that can tell apart a genuine approach from an exaggerated attempt at connecting.

# Fine Tune Your Content : Know what Your Audience is Looking For

Good content delivers value while boosting the growth of your business.The availability of multiple content marketing platforms has made it easier for content marketers to create and share customer-centric content. As a content marketer it is important that you keep an ear out for what your niche audience, competitors and industry experts are talking about. While crafting a content strategy for your audience, make sure that you add a valid call to action so as to engage them in meaningful conversations and  faster conversions.

# Ensure Consistency : Deliver Reliable Content in a Timely Fashion

Consistent content creation and dispersal through blog posts, newsletters, online brochure pages, social media updates and press releases let you deliver the marketing messages for an unparalleled impact. The key to maintaining consistency lies in sticking to an Editorial Calendar with an itinerary for all the content that needs to be published in sync with a marketing campaign.

Post sales queries, FAQs, Post sales informational content can come in handy while keeping your customers enticed and loyal to the brand. In a nutshell, avoid self serving messages and promotional content while opting for value adding content that solves the pain points of your audience and fills in the content gaps.

# Track Your Social Engagement Metrics

Social media engagement helps promote the growth in brand awareness while impacting the overall traffic to a website. Conversation, Amplification, applause and economic value are some social media metrics that let you evaluate the performance of your content. The conversations and interactions happening on social media platforms like Twitter, Facebook or LinkedIn indicate how findable your content is. Meanwhile the the shareability quotient of your content is reflected in the retweets, re-shares and repins on the popular social media platforms. The more your content gets shared the better is the amplification rate for it.

# Engagement Marketing

Traditional marketing has given way to a more customer centric version of it where behaviour driven marketing and multi-channel engagement lead improved interaction with your audiences. Targeted media relations are basically built around the theme of customer engagement. Studies have revealed that consumers feel more engaged when a brand tends to reach out to them through personalized messages. A consumer today is not just a passive recipient of your marketing messages. Brands indulge in engagement marketing to reach out to their audience with informative and thought provoking content.

As a Content Contributor or a content strategist you must realize that the scope of content marketing is not just limited to creating better user engagement. Value adding content ultimately creates enhanced user experiences for your niche segment that keeps coming back to you for that "go-to-expertise" to get their product/service related issues resolved.

Download the Drupal Guide
Enter your email address to receive the guide.
get in touch