I found this code online and I would like to implement it. However, I have never worked with hook functions.
My question is when I put this code into a brand new php file ex: uc_microcartTest.php .
How do I call this new php file and get the results to show like this?
/**
* Implementation of hook_block().
*/
function uc_microcart_block($op = 'list', $delta = 0, $edit = array()) {
switch ($op) {
case 'list':
$blocks[0] = array(
'info' => t('Micro-sized cart block for page header.'),
// This block cannot be cached, because anonymous
// sessions can have differing cart contents.
// To improve this, see drupal.org/project/uc_ajax_cart
'cache' => BLOCK_NO_CACHE,
);
return $blocks;
case 'view':
if ($item_count = uc_cart_get_total_qty()) {
$block = array();
$block['subject'] = '';
$block['content'] = theme('image',
drupal_get_path('module', 'uc_cart') .'/images/cart-full.png');
$block['content'] .= format_plural($item_count,
'My cart: 1 item', 'My cart: #count items');
$block['content'] = l($block['content'], 'cart', array('html' => TRUE));
return $block;
}
break;
}
}
Although it is possible to call the functions from external PHP files but I recommend you follow the "Drupal way":
Create your own custom module
Implement hook functions in <your_module_name>.module file.
Enable your module
You should also read more about how hooks work in Drupal here
Related
I am new at Drupal 7 and I'm creating a Block by code, following this tutorial.
So I create a new module folder at drupal/sites/all/modules and created two files:
block_square_menu.info: it has the info of the module:
name = Block Square Menu
description = Module that create a Block for Square menu, menu shown only in home page
core = 7.x
package = custom
block_square_menu.module: it contains the PHP code:
<?php
/**
* Implements hook_block_info().
*/
function block_square_block_info() {
$blocks = array();
$blocks['block_square'] = array(
'info' => t('Block Square'),
'cache' => DRUPAL_CACHE_PER_ROLE,
);
return $blocks;
}
/**
* Implements hook_block_view().
*/
function block_square_block_view($delta = '') {
$block = array();
switch ($delta) {
case 'block_square':
$block['subject'] = t('block Title');
$block['content'] = t('Hello World!');
break;
}
return $block;
}
After save the files, I go to Admin/Modules, I activate the new module and save the configuration. Now I go to Structure/Blocks and it should list my new Block, but it doesn't do.
I have followed all the tutorial steps and I cleaned Drupal cache, but I'm still having the problem.
First solve your mistake: change the function name where you implemented hook_block_view(), you need to change it as function blocks_square_block_view()
/**
* Implements hook_block_view().
*/
function blocks_square_block_view($delta = '') {
$block = array();
......
After also if not solve then remove 'cache' attribute from hook_block_info() it is optional.
Then follow 2 steps if you missed.
1) Clear all cache (/admin/config/development/performance).
2) Enable your custom module (/admin/modules).
After trying again, your block should appear in (/admin/structure/block).
Solved, the problem was the name of the functions. So the names started with "block_square" which it have the word "block" and it causes some trouble so I changed the all the names with menu_square.
So the functions are now:
menu_square_block_info()
menu_square_block_view($delta = '')
And the files are:
menu_square.info
menu_square.module
The code of the files are:
info:
name = Menu Square
description = Module that create a Block for Square menu, menu shown only in home page
core = 7.x
package = custom
module:
<?php
/**
* Implements hook_block_info().
*/
function menu_square_block_info() {
$blocks['menu_square'] = array(
'info' => t('Block Square'),
//'cache' => DRUPAL_CACHE_PER_ROLE,
);
return $blocks;
}
/**
* Implements hook_block_view().
*/
function menu_square_block_view($delta = '') {
$block = array();
switch ($delta) {
case 'menu_square':
$block['subject'] = t('block Title');
$block['content'] = t('Hello World!');
break;
}
return $block;
}
Here is my custom.info
name = Custom
description = Custom module
core = 7.x
package = Own
and custom.module
<?php
/**
* #file
* An example custom module for selecting, updating and deleting query
*/
/**
* Implementation of hook_block_info()
*/
echo 'Today: \n';
echo date('m/d/Y');
function custom_block_info() {
$block['custom'] = array('info' => t('Custom block'))
return $block;
}
/**
* Implements hook_block_view.
*/
function custom_block_view($delta = '') {
global $user;
$block['content'] = t('Hello #user from IP #host',array(
'#user' => format_username($user),
'#host' => $user->hostname`enter code here`
));
$result = db_select('node','a')
->fields('a', array('title'))
->execute();
foreach($result as $node) {
$items[] = array(
'data' => t($node->title)
);
}
$block['content'] .= theme('item_list', array(
'items' => $items
));
return $block;
}
But this custom module is not displaying data in the sidebar where had i put the block. i have place the echo statement above the code it's not even displaying that echo statement in block can any one tell me how to resolve this????
P.S. I have installed drupal i ve changed nothing in database!
Check if your module is active in the modules list (admin/modules) if so try to put your echo statements in a hook_init like this:
function custom_init(){
echo 'Today: \n';
echo date('m/d/Y');
}
then clear all drupal cache Configuration > Performance > Clear alla caches (admin/config/development/performance)
In the Header.tpl file there is a hook {$HOOK_TOP} which contains all the header part including menu, search etc... You can check that in this URL
In the FrontController it shows... 'HOOK_TOP' => Hook::exec('displayTop'),
it means in the Hook page there is a function called exec(). But I cannot understand the code properly in the exec() call.
It tells it Execute modules for specified hook. When I searched for "displayTop" I got a module name called blocktopmenu.php.
Execution only goes through 2 functions:
public function hookDisplayTop($param)
{
$this->user_groups = ($this->context->customer->isLogged() ? $this->context->customer->getGroups() : array(Configuration::get('PS_UNIDENTIFIED_GROUP')));
$this->page_name = Dispatcher::getInstance()->getController();
if (!$this->isCached('blocktopmenu.tpl', $this->getCacheId()))
{
$this->makeMenu();
$this->smarty->assign('MENU_SEARCH', Configuration::get('MOD_BLOCKTOPMENU_SEARCH'));
$this->smarty->assign('MENU', $this->_menu);
$this->smarty->assign('this_path', $this->_path);
}
$this->context->controller->addJS($this->_path.'js/hoverIntent.js');
$this->context->controller->addJS($this->_path.'js/superfish-modified.js');
$this->context->controller->addCSS($this->_path.'css/superfish-modified.css');
$html = $this->display(__FILE__, 'blocktopmenu.tpl', $this->getCacheId());
//print_r($html);//exit;
return $html;
}
and
protected function getCacheId($name = null)
{//echo"asdasdsad";exit;
parent::getCacheId($name);
$page_name = in_array($this->page_name, array('category', 'supplier', 'manufacturer', 'cms', 'product')) ? $this->page_name : 'index';
return 'blocktopmenu|'.(int)Tools::usingSecureMode().'|'.$page_name.'|'.(int)$this->context->shop->id.'|'.implode(', ',$this->user_groups).'|'.(int)$this->context->language->id.'|'.(int)Tools::getValue('id_category').'|'.(int)Tools::getValue('id_manufacturer').'|'.(int)Tools::getValue('id_supplier').'|'.(int)Tools::getValue('id_cms').'|'.(int)Tools::getValue('id_product');
}
But this public function hookDisplayTop($param) never gets called in the whole folder anywhere. I searched it but never found it in any file.
The exec() function shows below
public static function exec($hook_name, $hook_args = array(), $id_module = null, $array_return = false, $check_exceptions = true)
{
// Check arguments validity
if (($id_module && !is_numeric($id_module)) || !Validate::isHookName($hook_name))
throw new PrestaShopException('Invalid id_module or hook_name');
// If no modules associated to hook_name or recompatible hook name, we stop the function
if (!$module_list = Hook::getHookModuleExecList($hook_name))
return '';
// Check if hook exists
if (!$id_hook = Hook::getIdByName($hook_name))
return false;
// Store list of executed hooks on this page
Hook::$executed_hooks[$id_hook] = $hook_name;
// print_r(Hook::$executed_hooks);exit;
$live_edit = false;
$context = Context::getContext();
if (!isset($hook_args['cookie']) || !$hook_args['cookie'])
$hook_args['cookie'] = $context->cookie;
if (!isset($hook_args['cart']) || !$hook_args['cart'])
$hook_args['cart'] = $context->cart;
$retro_hook_name = Hook::getRetroHookName($hook_name);
//print_r($hook_name);exit;
// Look on modules list
$altern = 0;
$output = '';
foreach ($module_list as $array)
{
// Check errors
if ($id_module && $id_module != $array['id_module'])
continue;
if (!($moduleInstance = Module::getInstanceByName($array['module'])))
continue;
// Check permissions
if ($check_exceptions)
{
$exceptions = $moduleInstance->getExceptions($array['id_hook']);
$controller = Dispatcher::getInstance()->getController();
if (in_array($controller, $exceptions))
continue;
//retro compat of controller names
$matching_name = array(
'authentication' => 'auth',
'compare' => 'products-comparison',
);
if (isset($matching_name[$controller]) && in_array($matching_name[$controller], $exceptions))
continue;
if (Validate::isLoadedObject($context->employee) && !$moduleInstance->getPermission('view', $context->employee))
continue;
}
// Check which / if method is callable
$hook_callable = is_callable(array($moduleInstance, 'hook'.$hook_name));
$hook_retro_callable = is_callable(array($moduleInstance, 'hook'.$retro_hook_name));
if (($hook_callable || $hook_retro_callable) && Module::preCall($moduleInstance->name))
{
$hook_args['altern'] = ++$altern;
// Call hook method
if ($hook_callable)
$display = $moduleInstance->{'hook'.$hook_name}($hook_args);
else if ($hook_retro_callable)
$display = $moduleInstance->{'hook'.$retro_hook_name}($hook_args);
// Live edit
if (!$array_return && $array['live_edit'] && Tools::isSubmit('live_edit') && Tools::getValue('ad') && Tools::getValue('liveToken') == Tools::getAdminToken('AdminModulesPositions'.(int)Tab::getIdFromClassName('AdminModulesPositions').(int)Tools::getValue('id_employee')))
{
$live_edit = true;
$output .= self::wrapLiveEdit($display, $moduleInstance, $array['id_hook']);
}
else if ($array_return)
$output[] = $display;
else
$output .= $display;
}
}
if ($array_return)
return $output;
else
return ($live_edit ? '<script type="text/javascript">hooks_list.push(\''.$hook_name.'\'); </script>
<div id="'.$hook_name.'" class="dndHook" style="min-height:50px">' : '').$output.($live_edit ? '</div>' : '');// Return html string
}
I am not going to explain you the code line by line here, but i will explain you what the exec static member do.
When ever you call
Hook::exec("HookName");
It performs the following processes for you.
1) First it checks whether the hook is available or not? If it is not available return false;
2) Second it gets the module list for that hook from database. Also narrow down the list by exceptions for the modules for the hooks for the current page.
3) After it gets all the module(s) for the hook called for the current loaded (or called page) page, it calls the hooks function in the module. If you check modules for a specific hook you will find public function for that hook. Lets consider the Top hook. In modules you will have public functions like
public function hookTop // or public function hookDisplayTop for compatibility reasons
Please not that PS performs some other operations also there.
The above details are just giving you the idea that how hooks and modules work in PS.
Also taking the above theory, i implemented the same operations in Codeigniter and Zend Framework for my own projects, and it works like a charm ;) .
If you still have any other questions, let me know and i will provide you as much details as i can.
Thank you
Lines who call the HookDiplayTop are :
// Call hook method
if ($hook_callable)
$display = $moduleInstance->{'hook'.$hook_name}($hook_args);
else if ($hook_retro_callable)
$display = $moduleInstance->{'hook'.$retro_hook_name}($hook_args);
Is the hook_block has been changed? the following is drupal 6 example i have found on internet(http://eureka.ykyuen.info/2010/11/10/drupal-create-a-block/), there is no block shown in admin/structure/block,
* Implementation of hook_block().
*/
function custom_block($op = 'list', $delta = 0, $edit = array()) {
switch ($op) {
//Define the block
case 'list':
$blocks[0]['info'] = t('Block Info');
$blocks[0]['cache'] = BLOCK_NO_CACHE;
return $blocks;
case 'configure':
//TODO: block configurable parameters
$form = array();
return $form;
case 'save':
//TODO: save new configuration
return;
//Display the block
case 'view':
$block['subject'] = t('Block Subject');
$block['content'] = 'Block Content';
return $block;
}
}
it seems that, hook_block in drupal 7 has been changed, how to rewrite about code? anyone can provide hints/direction to me? thank you very much.
In Drupal 7, your implementation of hook_block() would be changed to:
/**
* Implements hook_block_info().
*/
function custom_block_info() {
$blocks = array();
$blocks['list'] = array(
'info' => t('Block Info'),
'cache' => DRUPAL_NO_CACHE,
);
return $blocks;
}
/**
* Implements hook_block_view().
*/
function custom_block_view($delta = '') {
$block = array();
switch ($delta) {
case 'list':
if (user_access('access content')) {
$block['subject'] = t('Block Subject');
$block['content'] = 'Block Content';
}
break;
}
return $block;
}
Your code works for Drupal 6.The implementation of hook_block is changed in Drupal 7.
In Drupal 7 there are different hooks that should be used to serve your purpose.
hook_block_configure
hook_block_info
hook_block_save
hook_block_view
Check more about hook_block here
The following code is a Drupal block made in php.
1) How can I implement more then one item? now i have test1 but i want test1, test2, test3 and test5.
2) how can i link a title for example test1 to my admin/settings/ menu? I want to link an item to node_import in Drupal.
function planning_block($op='list', $delta=0, $edit=array()) {
switch ($op) {
case 'list':
$blocks[0]['info'] = t('Stage administration block');
return $blocks;
case 'view':
$blocks['subject'] = t('Stage administratie');
$blocks['content'] = 'test';
return $blocks;
}
}
If you refer to the documentation of hook_block, you can declare several block inside one hook.
The $delta argument is here to help you differenciate which block your are rendering.
About your links in the title, just use the l() function when you are setting the $block['subject'] value.
Example:
function planning_block($op='list', $delta=0, $edit=array()) {
switch ($op) {
case 'list':
$blocks[0]['info'] = t('Stage administration block 1');
$blocks[1]['info'] = t('Stage administration block 2');
return $blocks;
case 'view':
switch ($delta) {
case 0:
$blocks['subject'] = t('Stage administratie');
$items = array(
l('Item 1', 'admin/settings/1'),
l('Item 2', 'admin/settings/2'),
);
$blocks['content'] = theme_item_list($items);
return $blocks;
case 1:
$blocks['subject'] = l('admin/settings/2', t('Stage administratie 2'));
$blocks['content'] = 'test 2';
return $blocks;
}
}
}
You can either create multiple blocks as shown in Artusamak's answer, or you can simply add more content to $blocks['content'] if you want it in a single block.
$blocks['content'] = l('admin/settings/1', 'test 1') . ' ' . l('admin/settings/2', 'test 2');
Note, if you just want a list of fixed links, you can do that by creating a menu and adding links to it. Every menu is automatically exposed as a block. No custom code required.