Drupal 7 load a view from module

You can load a view from drupal 7 through hook_theme.
For that first of all you need to define function in hook_menu like this
function hook_menu()
{
  $items = array();
  $items[item/view/%] = array(
        ‘title’ => t(‘Item View’),
  ‘page callback’ => ‘item_view’,
  ‘page arguments’ => array(2),
  ‘access arguments’ => array(‘access content’),
  );
  return $items;
}
Now you need to define ‘item_view’ method in your module
function item_view($item_id = null)
{
  // DO DB QUERY, HERE I HAVE ATTACHED DEMO
      return theme(‘item_view’, array(
          ‘vars’ => array(
          ‘name’ => ‘Item’,
          ‘description’ => ‘Description’
      )
  ));
}
Now time to implement hook_theme api
 
function item_theme($existing, $type, $theme, $path)
{
       return array(
             ‘item_view’ => array(
                 ‘variables’ => array(‘vars’ => null),
                 ‘template’ => ‘item-view’,
                 ‘path’ => drupal_get_path(‘module’, ‘item’) . ‘/view’
             )
       );
}
Now time to load view and create a tpl.php file under your module directory.
Create a ‘item-view.tpl.php’ file under views folder in your module.
<b>Item Name:</b> <?php echo $vars[‘name’]; ?>
<br />
<b>Item Description: </b> <?php echo $vars[‘description’]; ?>
<br />
You have now created a view and theme in drupal 7. 😃

Copyright © 2020. Powered by WordPress & Romangie Theme.