6

For example I have the code:

function contact_block_view($delta = '') {
$block = array();
switch ($delta) {
  case 'contact_block':
  $block['content'] = drupal_get_form('contact_form');
break;  
}
return $block; 
}

How to set inside this block the id or class attributes?

12

You will not be able to add an id or class attribute to the block in your hook_block_view implementation. At this stage you are not yet dealing with the markup of the block itself but only the markup for its content. In order to set the id or class of the block markup, you will need to use hook_preprocess_block() or hook_process_block() to add a usable variables to the block.tpl.php template. Then you will need to actually use the variables in the template itself.

Fortunately, the default block.tpl.php file already provides variables for both the id and class attributes of your block ($block_html_id and $classes). Actually, template_preprocess_block already sets the id to 'block-' . $variables['block']->module . '-' . $variables['block']->delta. So in your case, using the default template, your block will have block-contact-contact-block as id. But it can be changed if needed. In any preprocessor functions, you can add and remove CSS classes by manipulating $classes_array variables. Both are illustrated in the following code.

function MODULE_preprocess_block(&$variables) {
  if ($variables['block']->module == 'contact' && $variables['block']->delta == 'contact_block') {
    $variables['block_html_id'] = drupal_html_id('your-id-here');
    $variables['classes_array'][] = drupal_html_class('your-class-here');
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.