More on displaying images on D7

When we left our story last time, things were in decent shape. But then I noticed that some of my img_assist tags weren't displaying, and had to meddle with the custom img_assist filter some more. I made some progress, and I feel I might as well share.

As it turned out, the problem was that some of the images' image fields have the proper language ('en') set rather than being undefined ('und'). I had hardcoded 'und' into my module and this tripped me up. While I was in there I also implemented link=node so that any img_assist nodes intended to link back to the image node do so, since it was easy. The drupal api documentation needs more examples badly, but as documentation goes, it's all right.

Pattern: /\[img_assist\|(.+?)]/

Replacement text (PHP Code):

$elements = explode('|', $matches[1]);

$result = '(filter error or malformed img_assist tag)';

foreach ($elements as $element) {
  $parts = explode('=', $element);
  if ( $parts[1] != '' ) {
    $values[$parts[0]] = $parts[1];
  }
}

if ( $values[nid] ) {
  $mynode = node_load($values[nid]);
  if (!$mynode) {
    $result = "(cannot load image node)";
  } else {
    if ($mynode->node_image[$mynode->language][0]['uri']) {
      $path = $mynode->node_image[$mynode->language][0]['uri'];
    } else {
      $path = $mynode->node_image['und'][0]['uri'];
    }

    if ( $values[height] && $values[width] ) {
      $result = theme('image_style', array('style_name' => 'large', 'path' => $path, 'getsize' => FALSE, 'alt' => $mynode->title, 'attributes' => array('class' => 'img_assist', 'width' => $values[width], 'height' => $values[height])));
    } else {
      $result = theme('image_style', array('style_name' => 'large', 'path' => $path, 'getsize' => TRUE, 'alt' => $mynode->title, 'attributes' => array('class' => 'img_assist')));
    }
  }
  if ( $values[link] == 'node' ) {
    $result = l($result, 'node/'.$values[nid],array('html' => TRUE));
  }
}

return $result;

This code is the big fundamental change:

    if ($mynode->node_image[$mynode->language][0]['uri']) {
      $path = $mynode->node_image[$mynode->language][0]['uri'];
    } else {
      $path = $mynode->node_image['und'][0]['uri'];
    }

I copied this code into my image filter, too, to address the same issue should it crop up. As mentioned previously, implementing the node link was fairly trivial:

  if ( $values[link] == 'node' ) {
    $result = l($result, 'node/'.$values[nid],array('html' => TRUE));
  }

Clearly, if link is set to node, we wrap the result in a link. Since I broke the arguments to img_assist up into an associative array, it's easy to make decisions based on the contents. I know this is beyond obvious to people who self-identify as programmers, but this is all still nifty to me.