How to change value and add HTML markup on Drupal Views' field programmatically

There are some instances that we need to alter the value of Views' field and add markup on its rendered output programmatically. The following codes shows how to achieve these tasks using hook_views_pre_render().

  
/**
 * Implements hook_views_pre_render().
 */
function mycustommodule_views_pre_render(&$view) {
  if ($view->current_display == 'front_shoplist_pane') {
    $status = t('(open)');
    $icon   = '<i class="fa fa-check" aria-hidden="true"></i> ';
    if (isset($_GET['type'])) {
      $status = t('(closed)');
      $icon   = '<i class="fa fa-close" aria-hidden="true"></i> ';
    }
    foreach ($view->result as $index => &$result) {
      // Alter the title field value
      $result->node_title .= " $status";
    }
    $view->style_plugin->render_fields($view->result);
    foreach ($view->style_plugin->rendered_fields as $index => &$rendered_result) {
      // Add HTML markup icon on rendered title field
      $rendered_result['title'] = $icon . $rendered_result['title'];
    }
  }
}
  

This is tested on both regular Views and Search API result Views.

Comments

I've been researching and trying to figure out how to do this for 2 days. Something as simple as hiding (unsetting) a view global text field based on the value of another field in the row in a module (not with theming) should not be this difficult.

Because it's a global text field the usual hooks (pre_render, post_execute, etc) are useless. The easy way is to enable the php filter module and use the views_php filter-- but that's not acceptable for all sorts of reasons. Using your code above, i was able to simply unset it in the $rendered_result array-- basically 3 lines of code. brilliant!

Thanks!

Thank you !
I am begginer of Drupal. This is very helpful topic.

I am looking for this kind of code part, since last 4 to 5 days. This is exactly a perfect piece of code. Thank you so much :)

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.