Drupal 7 - add HTML inside #link form type entry?

selfsimilar picture selfsimilar · Feb 27, 2013 · Viewed 7.8k times · Source

I need to add HTML markup to the #title field of a Drupal 7 #type link form element. The output should look roughly like this:

<a href="/saveprogress/nojs/123" id="saveprogress-link" class="ajax-processed">
  <span data-icon="&#61515;" aria-hidden="true" class="mymodule_symbol"></span>
  Save Progress
</a>

Since I'm doing some ajax forms, I can't just use #markup and l() function. Here's an example without the span:

function mymodule_save_progress_link($nid) {
  return array(
    '#type' => 'link',
    '#title' => t('Save Progress'),
    '#href' => 'saveprogress/nojs/' . $nid,
    '#id' => 'saveprogress-link',
    '#ajax' => array(
      'wrapper' => 'level-form',
      'method' => 'html',
    ),
  );
}

function mymodule_print_links($nid=NULL) {
  ctools_include('ajax');
  ctools_include('modal');
  ctools_modal_add_js();

  $build['saveprogress_link'] = mymodule_save_progress_link($nid);

  return '<div id="level-form">' . drupal_render($build) . '</div>';
}

When I add the <span> to the #title field, it's escaped and not interpreted as HTML. How can I insert this span (or other markup) to the tile field of a link type form element. This form element is not well documented on the Drupal site.

Answer

selfsimilar picture selfsimilar · Mar 7, 2013

There's actually a much simpler way than custom-rolling a theme - just tell drupal_render() to treat '#title' as html.

function mymodule_save_progress_link($nid) {
  return array(
    '#type' => 'link',
    '#title' => '<span>unescaped HTML here</span> '.t('Save Progress'),
    '#href' => 'saveprogress/nojs/' . $nid,
    '#id' => 'saveprogress-link',
    '#ajax' => array(
      'wrapper' => 'level-form',
      'method' => 'html',
    ),
    '#options' => array(
      'html' => true,
    )
  );
}

This could be very handy for adding images or other elements to a click-able area.