Drupal: custom block doesn't appear - php

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;
}

Related

Implementation of hook_block()

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

Drupal 8 custom module not showing up in block layout

I have a custom block module for Drupal 8. It is working on my localhost version of drupal (version 8.7.8). When I upload it to the web server (Version 8.7.11), I can enable the module, but it doesn't show up when I try to place the block on the block layout page. I don't have much control of the web server - files are uploaded via a git repository, but other modules I've added work without issues.
My module is just 2 files:
modules/custom/ischool_section_title_level_two/ischool_section_title_level_two.info.yml
name: iSchool Section Title Level Two
description: Provides a block that shows the Level Two title, or Level One if there is no Level Two.
core: 8.x
package: Custom
dependencies:
- block
type: module
modules/custom/ischool_section_title_level_two/src/plugin/block/iSchoolSectionTitlelevel_two.php
<?php
namespace Drupal\ischool_section_title_level_two\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
* Provides a block that shows the Level Two section title, or Level One title if there is no level Two
*
* #Block(
* id = "ischool_section_title_level_two",
* admin_label = #Translation("iSchool Section Title Level Two"),
* category = #Translation("Custom"),
* context_definitions = {
* "node" = #ContextDefinition("entity:node", label = #Translation("Node"))
* }
* )
*/
//code adapted from http://hussainweb.me/an-easier-way-to-get-the-current-node-in-a-block-plugin-in-drupal-8/
//and https://design.briarmoon.ca/tutorials/drupal-8/getting-the-parent-node-of-a-drupal-8-node
class iSchoolSectionTitlelevel_two extends BlockBase {
public function build() {
$node = $this->getContextValue('node');
if (empty($node)) {
return [
'#markup' => "",
];
}
$L1_Title = $node->getTitle();
$L2_Title = $node->getTitle();
$currentNode = $node;
while (true) {
$parent_node = $this->getParentNode($currentNode);
if (empty($parent_node)){
break;
}
$L2_Title = $L1_Title;
$L1_Title = $parent_node->getTitle();
$currentNode = $parent_node;
}
return [
'#markup' => $L2_Title,
];
}
private function getParentNode($node){
if (empty($node)) return null;
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
$links = $menu_link_manager->loadLinksByRoute('entity.node.canonical', ['node' => $node->id()]);
// Because loadLinksByRoute() returns an array keyed by a complex id
// it is simplest to just get the first result by using array_pop().
/** #var \Drupal\Core\Menu\MenuLinkInterface $link */
$link = array_pop($links);
if (empty($link)) return null;
/** #var \Drupal\Core\Menu\MenuLinkInterface $parent */
if ($link->getParent() && $parent = $menu_link_manager->createInstance($link->getParent())) {
if (!method_exists($parent, "getUrlObject")) return null;
$urlObj = $parent->getUrlObject();
if (is_null($urlObj)) return null;
if (!method_exists($urlObj, "getRouteParameters")) return null;
$route = $urlObj->getRouteParameters();
if (empty($route)) return null;
if (!isset($route['node'])) return null;
$parent_node = \Drupal::entityManager()->getStorage('node')->load($route['node']);
return $parent_node;
}
else return null;
}
// cache this block for a definite time.
public function getCacheMaxAge() {
return 43200;
}
}
This was an issue with the capitalization of the folders.
The 2nd file should have been in the /src/Plugin/Block/ folder but instead was in the /src/plugin/block/ folder (missing the initial caps).
On the local windows machine, this didn't make any difference. On the LAMP stack machine it resulted in the block not showing.

Drupal, where i can find footer file?

I need to put some code into the site on drupal and i need this code to work on every page of my site. How can i do this? I wanted to find the file of footer and put some code inside, but i can't find it.
There are 3 ways to add PHP code in to the footer.
1> Turn on the PHP filter & enter the code into a block that is positioned in the footer left region.
2> Put the code in the appropriate template file in the sub-theme.
3> Make a module that outputs the code to a block; activate and place the block.
Suppose that you want to add following line to footer area :
©<?php print date('Y');?> Your Company Name - Address of your company.
So best way to do it is make small module like this:
copyright_block.info
name = Copyright Block
description = Shows the (incrementing) current year and company information.
package = Other
core = 7.x
files[] = copyright_block.module
copyright_block.module
<?php
/**
* #file
* This module shows the copyright year and company information.
*/
/**
* Implements hook_help().
*/
function copyright_block_help($path, $arg) {
if ($path == 'admin/help#copyright_block') {
return t('Manually edit to change company information');
}
}
/**
* Implements hook_block_info().
*/
function copyright_block_block_info() {
$blocks = array();
$blocks['show_copyright'] = array(
'info' => t('Company Information'),
'cache' => DRUPAL_NO_CACHE,
);
return $blocks;
}
/**
* Implements hook_block_view().
*/
function copyright_block_block_view($block_name = '') {
if ($block_name == 'show_copyright') {
$content = "<p>©" . date('Y') ." Your Company Name - Address of your company</p>";
$block = array(
'subject' => t('Company Information'),
'content' => $content,
);
return $block;
}
}
NOTE: Do not put PHP end tag ?> at the end.

Drupal custom module is not working

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)

drupal 7 custom block changed?

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

Categories