How to display a block programmatically in Drupal

December 12, 2013
1K
12K


Category:
Tags:

This tutorial solves the following questions:

  • Placing the contents of a block in any location
  • Best way to programmatically embed the Block
  • Outputting a block programmatically in Drupal
  • How to insert a block programmatically with Drupal
  • Programmatically printing a block
  • How do I programmatically show a view block
  • Create your own custom Drupal block programmatically
  • Programatically output a webform block
  • Calling an instance of a already assign block. Suppose whose online block is already assigned in left sidebar. Now we want another instance of whose online to place in top

There are variety of ways we can create DRUPAL block. Welknown ways are:

  • Using custom/contributed module
  • Using built in system and
  • Using Views

Adding the contents of a block

Block generate by module

To add the contents of a block into a node, a custom block, custom module, or a page template, use the following syntax:

 <?php
//D7
$block module_invoke('module_name''block_view''block_delta');
print 
render($block['content']);
?> 
 <?php
//D6 and earlier
$block module_invoke('module_name''block''view''block_delta');
print 
$block['content'];
?> 

Example: Display who is a new user

<?php
//D7
$block module_invoke('user''block_view''2');
print 
render($block['content']);
?> 
 <?php
//D6 and earlier
$block module_invoke('user''block''view'2);
print 
$block['content'];
?> 

 

Block generate by block

<?php
//D7
$block module_invoke('block''block_view''block_id');
print 
render($block['content']);
?> 
 <?php
//D6 and earlier
$block module_invoke('block''block''view''block_id');
print 
$block['content'];
?> 

Example: Display who is a new user

<?php
//D7
$block module_invoke('block''block_view''2');
print 
render($block['content']);
?> 
 <?php
//D6 and earlier
$block module_invoke('block''block''view''2');
print 
$block['content'];
?> 

 

Block generated by views with arguments

<?php
//D6 and earlier
print views_embed_view($view_name$display_id); // without argument
print views_embed_view($view_name$display_id$argument); // with single argument
print views_embed_view($view_name$display_id, array($arg1,$arg2,$arg3)); // with multiple arguments
?> 

How do i know block id (block delta)?

Go to block page (admin/build/block for drupal 6) or (admin/structure/block for drupal 7), hover your mouse on configure link, you will see a link in status bar. Last part is block id.

Determining drupal6 block id
figure 01: Built in Block create by user module
Determining drupal6 block id
figure 02: Custom block created by site admin (user)
Determining drupal6 block id
figure 03: Block created by view

CATEGORIES