I have an image field on a node, which will not always be populated. In the case where the field is empty (no image), I want to alter the markup to display a random image which always exists in a specified directory of the files dir. The second part isn't a problem, but I am struggling with the alter part. I am trying to find the correct hook or theme function to test if the image field is empty and then render some markup in it's place. I am lead towards a theme function. Any ideas?


2 Answers 2


use hook_node_view_alter. Check over there that if images is empty then fetch image from your whatever custom directory and print it. For printing an image use theme_image.

  • Hi Deepak, hook_node_view_alter provides a render array to alter, how will this hook help if I need to 'print' the image using theme_image? Thanks
    – davewilly
    Jun 30, 2014 at 9:20
  • hey @davewilly If you got the array, into that you will get the image. check there if any image is there or not, then do your logic. Jun 30, 2014 at 9:36
  • Yes but I will then need to provide a full render array for the image. I just want to provide the markup at a theme level.
    – davewilly
    Jun 30, 2014 at 9:39

I have achieved this by providing a default image for the field, and then using theme_preprocess_field to alter the uri. I'm not currently sure what adverse effects this may have.

function mytheme_preprocess_field(&$variables) {
  if($variables['element']['#field_name'] == 'field_myfield_image') {
    $variables['items'][0]['#item']['uri'] = 'public://path_to_img/my_new_image.jpg';

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.