[Solved] How to use hook_entity_view in drupal7 ?

I work in a team of developers and we separately develop modules in drupal. We are assigned to create entities, and there was time once I need to alter the view which was output of some other entity module. So, I am sharing here my experience how I did that.

Lets say we have two custom entity module
1. product module – creates a product entity
2. customer module – creates a customer entity

I need to alter the output of product entity module from customer module entity. In Drupal6 it was quite easy using node_api and then adding our own content in node->content, once we verified the correct content type. In Drupal7 we do it using the hook_entity_view.

To use hook_entity_view the product module should implement the single line of code highlighted in line 17. More information on hook_entity_view

function product_page_view( $product, $view_mode='full' ) {
// Remove previously built content, if exists.
  $product->content = array();

  if ($view_mode == 'teaser') {
    $product->content['title_en'] = array(
        '#markup' => filter_xss($product->title_en),
        '#weight' => -5,
    );
  }

// Build fields content.
  field_attach_prepare_view(PRODUCT_ENTITY, array($product->pid => $product), $view_mode);

  entity_prepare_view(PRODUCT_ENTITY, array($product->pid => $product));

  module_invoke_all('entity_view', $product, 'product', 'full', $GLOBALS['language_content']->language);

  $product->content += field_attach_view(PRODUCT_ENTITY, $product, $view_mode);

  /*
   * Specify the theme to use and set the #element. Note that the
   * key you use to pass the entity object must match the key you
   * set in in the variables in entity_theme().
   *
   */
  $product->content += array(
      '#theme' => 'product',
      '#element' => $product,
      '#view_mode' => 'full',
      '#language' => NULL,
  );

  return $product->content;
}

After implementating that code in product entity module. There is one more step. We now finally need to use hook_entity_view hook in customer module, which is similar to using other hooks in drupal. i.e. modulename_entity_view().

Below code is roughly a random sample code, that I picked up and altered the variables to depict product and customer relationships.

we might be using the same hook to alter the output of more than one entity module so, I am checking here the $type variable and then depending on the cases, I have used my output logic.

Here I have simply added my own content to the output of product entity module. This is done by the code from line 13-18.

function customer_entity_view( $entity, $type, $view_mode, $langcode ) {
  $t = 0;
  switch ($type) {
    case 'product':
      $productStatus = entity_get_controller(PRODUCT_ENTITY)->getProductStatus($product->pid);

      if ($productStatus == 'yes') {
        $output = drupal_get_form('customer_product_page_form', $product->pid);
        $body = drupal_render($output);

	// Alter the output of product entity module
	// Add your customer output to the output of product entity module
        $entity->content['product'] = array(
            '#prefix' => '<div id="customer_product_info">', // used by javascripts to populate sliders
            '#suffix' => '</div>',
            '#markup' => $body,
            '#weight' => -10,
        );
      }
      break;
    default:break;
  }
}

If there is anything that you don’t understand. Please mention it in the comments. I will try to make them clear as far as possible.

Automatic ajax call using jQuery

Total used files :

  • index.php
  • jquery.js
  • random.php

I am using jQuery’s setInterval() method to automatically make the ajax call in every 2 seconds.

index.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Refresh Page itself</title>
    <script type="text/javascript" src="jquery.js"></script>
    <script>
      $(document).ready(function(){
        var callAjax = function(){
          $.ajax({
            method:'get',
            url:'random.php',
            success:function(data){
              $("#sample").html(data);
            }
          });
        }
        setInterval(callAjax,2000);
      });
    </script>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <body>
    <?php
    print "Below number changes in 2 seconds interval, View-Source of this page to see the usuage of jquery for content refresh.<div id='sample'>100 </div>";
    ?>
  </body>
</html>

In above code, the interesting code is in line 17,

setInterval(callAjax,2000);

which calls the callAjax function in every 2 seconds. Here 2000 is supplied in milliseconds.

line 11 – sets the url to “random.php”

line 13 – replaces the #sample div with the response from the “random.php” file that is the output of

print 5*rand(1,100);

And this is the code for “random.php” that is called by ajax call in every 2 seconds.
random.php

<?php
print 5*rand(1,100);

You can test the demo online at http://www.samundra.com.np/refresh/

[Solved] Add module to admin/config page in Drupal7

We are going to create a following custom block in admin/config page.
Drupal admin/config block - Configure Products

To create a block in admin/config like those ‘People, Content Authoring, Media’ etc. We need to define two menu items as shown below


function products_menu() {
$items = array();
$items['admin/config/products'] = array(
      'title' => 'Configure Products',
      'description' => 'Allows administrators to configure product items',
      'weight' => -30,
      'page callback' => 'drupal_get_form',
      'page arguments' => array('products_admin_settings_form'),
      'access arguments' => array('administer products'),
      'file' => 'products.admin.inc',
  );

  $items['admin/config/products/manage'] = array(
      'title' => 'Manage Products',
      'description' => 'Allows admins to manage products',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('products_admin_settings_form'),
      'access arguments' => array('administer products'),
      'file' => 'products.admin.inc',
      'weight' => -10,
  );

  return $items;
}

admin/config/products – highlighted above line no. 3

Creates a new block with title Configure Products

admin/config/products/manage – highlighted above line no. 13

This menu item is visible under the Configure Products as clickable item. When this link “Manage Products” is clicked, it invokes the ‘products_admin_settings_form’ page callback which eventually displays a form for products configuration.

If there is any confusions please post them on comment.

Earthquake in Nepal (1st Ashoj, 2068)

Earthquake measuring 6.8 Richter scale hits Nepal in NST time, 6:25 PM. The center of earthquake was in Sikkim.

The aftershock was felt in Sikkim only which measured 4.8 Richter scale. There are damages and houses fallen down in Sikkim, roads are blocked, dead phone lines and people are updating the status on Facebook and Twitter.

I was in Kathmandu (Kalimati). I was having cup of tea when earthquake hit the Nepal, luckily I was on the ground floor, escape to the spacious ground (Kalimati Club).

Below are some of the live videos that during earthquakes. These videos were shared in twitter and facebooks, and can also be viewed on youtube directly.

Video footage of earthquake in Lazimpat Departmental Store (Nepal)
httpv://www.youtube.com/watch?v=2ZoZNVFDUHA

Nepal parliament Shakes During earthquake and then the meeting was postponed for 15 minutes by Chairperson Subash Nembang. (Updated on Sep 19, 2011)
httpv://www.youtube.com/watch?v=FEqfxEawioY

Video footage of Sikkim damages (still Images, India)
httpv://www.youtube.com/watch?v=td1Wf0ytOWM

Indian Channel showing detail of Sikkim epiccenter (India)
httpv://www.youtube.com/watch?v=hMqW6EeRRmM

Still Photos

After earthquake on m.g marg. — at sikkim,gantok.
After earthquake on m.g marg. — at sikkim,gantok.

A man in Siliguri points to a crack in the wall of his home after an earthquake hit Sikkim.
A man in Siliguri points to a crack in the wall of his home after an earthquake hit Sikkim.

A local watching a devastated house collapsed by the earthquake in Bhaktapur on Sunday‚ September18‚ 2011. A strong earthquake with a preliminary magnitude of 6.8 hit northeastern India today near the border with Nepal.
A local watching a devastated house collapsed by the earthquake in Bhaktapur on Sunday‚ September18‚ 2011. A strong earthquake with a preliminary magnitude of 6.8 hit northeastern India today near the border with Nepal.

Sources:
- https://www.facebook.com/pages/18-September-2011-I-Survived-the-earthquake/194133360660204
- earthquake.usgs.gov/earthquakes/recenteqsww/Maps/10/90_30.php