|
1 | 1 | # Drupal 7: Programmatically Create a Block
|
2 | 2 | How to programmatically create a block for your Drupal 7 web site
|
| 3 | + |
| 4 | +So you want to add a block to your module in Drupal 7. First, define its internal name and human-readable title (for the Blocks UI) with hook_block_info(): |
| 5 | + |
| 6 | +```php |
| 7 | +/** |
| 8 | +* Implements hook_block_info(). |
| 9 | +*/ |
| 10 | +function YOUR-MODULE_block_info() { |
| 11 | + $blocks = array(); |
| 12 | + $blocks['YOUR-BLOCK-NAME'] = array( |
| 13 | + 'info' => t('MY BLOCK TITLE'), |
| 14 | + 'cache' => DRUPAL_NO_CACHE |
| 15 | + ); |
| 16 | + return $blocks; |
| 17 | +} |
| 18 | +``` |
| 19 | + |
| 20 | +Then, give it the permissions needed to view it, a title (to appear for your site visitors), and some content with hook_block_view(): |
| 21 | + |
| 22 | +```php |
| 23 | +/** |
| 24 | +* Implements hook_block_view(). |
| 25 | +*/ |
| 26 | +function YOUR-MODULE_block_view($delta = '') { |
| 27 | + $block = array(); |
| 28 | + switch ($delta) { |
| 29 | + case 'YOUR-BLOCK-NAME': |
| 30 | + if (user_access('access content')) { |
| 31 | + $block['subject'] = t('MY BLOCK TITLE'); |
| 32 | + $block['content'] = variable_get('YOUR-BLOCK-TEXT', ''); |
| 33 | + } |
| 34 | + else { |
| 35 | + $block['content'] = t('No content available.'); |
| 36 | + } |
| 37 | + break; |
| 38 | + } |
| 39 | + return $block; |
| 40 | +} |
| 41 | +``` |
| 42 | + |
| 43 | +If you want to give the block a visual configurator -- the "Configure" link in the Blocks UI -- beyond what's already provided by the Block module (title, description, visibility settings, etc.), use hook_block_configure() and hook_block_save(): |
| 44 | + |
| 45 | +```php |
| 46 | +/** |
| 47 | + * Implements hook_block_configure() |
| 48 | + */ |
| 49 | +function YOUR-MODULE_block_configure($delta = '') { |
| 50 | + $form = array(); |
| 51 | + if ($delta == 'YOUR-BLOCK-NAME') { |
| 52 | + $form['YOUR-BLOCK-NAME-FORM'] = array( |
| 53 | + '#type' => 'textfield', |
| 54 | + '#title' => t('Enter some text to display'), |
| 55 | + '#size' => 128, |
| 56 | + '#maxlength' => 128, |
| 57 | + '#default_value' => variable_get('YOUR-BLOCK-TEXT', ''), |
| 58 | + ); |
| 59 | + } |
| 60 | + return $form; |
| 61 | +} |
| 62 | + |
| 63 | +/** |
| 64 | + * Implements hook_block_save() |
| 65 | + */ |
| 66 | +function YOUR-MODULE_block_save($delta = '', $edit = array()) { |
| 67 | + if ($delta == 'YOUR-BLOCK-NAME') { |
| 68 | + variable_set('YOUR-BLOCK-TEXT', $edit['YOUR-BLOCK-TEXT']); |
| 69 | + } |
| 70 | +} |
| 71 | +``` |
| 72 | + |
| 73 | +By using variable_set() and variable_get(), when you save some text in your custom field, Drupal will write the text into the variables table in its database and retrieve the text whenever the block is displayed. |
0 commit comments