Create a custom block in code

Public

Implements block api to provide block that can be fullly implemented in code

Get raw version
php
  1. <?php
  2. define('PROJECTNAME_BLOCKNAME_MARKUP', 'YOUR_MARKUP_HERE');
  3.  
  4. /**
  5.  * Implements hook_block_info().
  6.  * all examples are for a module named myproject_blocks
  7.  */
  8. function myproject_blocks_block_info() {
  9. $blocks['projectname_blockname'] = array(
  10. 'info' => t('BLOCKNAME'),
  11. 'cache' => DRUPAL_NO_CACHE,
  12. );
  13.  
  14. /** other blocks can be added here **/
  15.  
  16. return $blocks;
  17. }
  18.  
  19. /**
  20.  * Implements hook_block_view().
  21.  * all examples are for a module named myproject_blocks
  22.  */
  23. function myproject_blocks_block_view($delta = '') {
  24. $block = array();
  25.  
  26. switch ($delta) {
  27. case 'projectname_blockname':
  28. $block['content'] = variable_get('projectname_blockname_markup', PROJECTNAME_BLOCKNAME_MARKUP);
  29. break;
  30. }
  31. /** add other cases for additional blocks **/
  32. return $block;
  33. }
  34.  
  35. /**
  36.  * Implements hook_block_configure().
  37.  * all examples are for a module named myproject_blocks
  38.  */
  39.  
  40. function myproject_blocks_block_configure($delta = '') {
  41. $form = array();
  42.  
  43. switch ($delta) {
  44. case 'projectname_blockname':
  45. $form['content'] = array(
  46. '#type' => 'text_format',
  47. '#title' => t('Body'),
  48. '#format' => 'full_html',
  49. '#default_value' => variable_get('projectname_blockname_markup', PROJECTNAME_BLOCKNAME_MARKUP),
  50. );
  51. break;
  52. }
  53. /** add other cases for additional blocks **/
  54. return $form;
  55. }
  56.  
  57. /**
  58.  * Implements hook_block_save($delta = '', $edit = array().
  59.  * all examples are for a module named myproject_blocks
  60.  */
  61. function myproject_blocks_block_save($delta = '', $edit = array()) {
  62. switch ($delta) {
  63. case 'projectname_blockname':
  64. variable_set('projectname_blockname_markup', $edit['content']['value']);
  65. break;
  66. }
  67. /** It's best to create on module per block so that you can turn on/off blocks 1 by 1. But this will also work if you combine blocks together in one module. **/
  68. }

Comments

VVS's picture

additions:
'#format' => 'full_html', -> '#format' => NULL, - set to default format, but 'full_html' is maybe renamed.
text_format is save value as array:

  1. $blockvalue = variable_get('projectname_blockname_markup', array('value' => ''));
  2. ....
  3. '#default_value' => $blockvalue['value'],