Category Archives: Drupal 7

Permissions and roles in Drupal 7

First of all you need to define ‘access callback’ and ‘access argument’ in hook_menu() for respective uri. like this:
function hook_menu()
{
     $items = array();
     $items[item/list] = array(
          ‘access callback’ => ‘item_access’,
          ‘access arguments’ => array(‘view’),
     );
     return $items;
}
Then you need to create hook_permission method within in the module
function hook_permission()
{
     return array(
          ‘view item’ => array(
               ‘title’ => t(‘View Item’),
               ‘description’ => t(‘User can view Item.’),
               ‘restrict access’ => true,
          )
     );
}
Then you need to define item_access method
 
function item_access($op, $item = null, $account = null)
{
     global $user;
if($account){
     $user = $account;
}
if($op == ‘view’){
     return user_access(‘view item’, $user);
}
return false;
}
Now clear your cache. Donot forget to clear your cache as drupal 7 makes heavy usage of its cache.
 
Now go to /people/permissions page of your admin panel.
 
There you should see ‘View Item’ with little checkboxs, now enable then view of item for any users by selecting on them.

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.