Drupal: Check and render image fields
At reclaimyourcity, we have picture and artist nodes and relate them via a node reference. Now some of the artists may have a little profile comprising a picture and a description. When viewing the artist profile and there is no profile picture yet, we want to show the latest submitted picture of the particular artist instead. For this, we first need to check the value of the profile picture field and if it is not set, we need to get and render the latest picture of the artist. The first question is where to perform this check. Fortunately, Drupal offers preprocess functions for content to insert or override variables before they are passed to the template. So in our case, we override the corresponding preprocessor function for the artist node type, here are the changes.
function ryc_preprocess_node_artist(&$variables, $hook) { // we process a node of type artist, check if the profile image is set // if not, get the latest picture the artist is referenced on if(empty($variables['node']->field_teaser_image)) { $artist_nid = $variables['node']->nid; $query = new EntityFieldQuery(); $query->entityCondition('entity_type', 'node') ->entityCondition('bundle', 'picture') // only picture nodes ->propertyCondition('status', 1) // only published content ->fieldCondition('field_artist_ref', 'nid', $variables['node']->nid, '=') // only pictures by our artist ->propertyOrderBy('created', 'DESC') ->range(0, 1); // only one picture needed $result = $query->execute(); if (isset($result['node'])) { $image_style = 'image_sa_edit'; $latest_picture_nid = array_keys($result['node']); $latest_picture = node_load($latest_picture_nid[0]); // load the image $file = file_load($latest_picture->field_sa_image['und'][0]['fid']); $image_link =l('<img src="'. image_style_url($image_style, $file->uri). '" alt="" />', 'node/'. $latest_picture->nid, 'html' => TRUE)); $variables['latest_picture'] = '<div class="artist-teaser-image">'. $image_link .'</div>'; } } }
As a result, if there is no profile picture (which is stored in field_teaser_image) for the artist yet, we have a new variable latest_picture with the rendered latest picture of that artist. Finally, we adjust the template file node–artist.tpl.php for the artist nodes and add the following lines.
if(isset($variables['latest_picture'])) { print $variables['latest_picture']; } else { print(render($content['field_teaser_image'])); }
Now we have a consistent layout when displaying artist nodes.
Leave a Reply