4

How do I alter the rendering of a field in a View?
Where can I access the render array before the html is generated for output?

For example, if I have an image field included in my view, where can I add to the attributes of the image before the image is rendered using theme_image? Assuming that the field is eventually still rendered using theme_image.

I want to add attributes to the image tag and NOT the surrounding divs that Views inserts into the markup.

EDIT based on answer by Jimajamma:

Editing the $view->result as suggested is causing the View to crash. Page doesn't render correctly anymore:

function MYMODULE_views_pre_render(&$view) {  
   if ($view->name=='viewyouarelookingfor') {
      foreach($view->result as $row) {
         $row['field_body'][0]['rendered']['#markupe'] = '<p>Test!</p>'; // causes View to crash
      }
   }   
 }
  • 1
    I'm pretty sure $row above is an object, so it would be $row->.... not $row['...'] – Jimajamma Apr 18 '12 at 15:33
  • You're right! I keep missing the little details. Thanks! – nmc Apr 18 '12 at 15:35
9

I'd take a look at the views_pre_render(&$view); hook. There, in your module, you can do stuff like:

 function MYMODULE_views_pre_render(&$view) {

   if ($view->name=='viewyouarelookingfor') {

      // do whatever you want

   }

 }

and do whatever you want meaning you have access to $view->result which is an array of all the raw data making up each row. Throw in a drupal_set_message('<pre>' . print_r($view->result, true) . '</pre>'); or its equivalent to take a peek at that and you should be able to work all kinds of magic.

If this doesn't work to your needs, you can still render the field any way you like from a view template for that row or field itself.

  • I was digging through the $view object to find what to modify and totally missed the $view->result object. Thanks for pointing it out! But... modifying the $view->result array seems to be crashing my site. I'll keep working on it and see if I can't figure out why. – nmc Apr 18 '12 at 15:04
2

Also, you need to make sure that you use the array key '#markup' and not '#markupe'.

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.