0

In my content type I want to show the main image if the thumbnail field is empty. So I use the Display Suite code field and I enter the following code:

<?php 
dsm($entity);
if(empty($entity->field_thumbnail)){
    print_r('Thumbnail missing');
    // What code to put here to enable or render another image field 
}
?>

When the tumbnail is missing the above code works, but instead of text I want to display another image field, when the thumbnail is missing. I have tried everything I can think of, but the main image dose not show :-(.

1 Answer 1

1

It's because you have nothing in renderable format yet.

Look at function field_view_field

Returns a renderable array for the value of a single field in an entity.

Then change your code like this:

<?php 
dsm($entity);
if(empty($entity->field_thumbnail)){
    $renderable = field_view_field('node',$entity,'field_main_image',array('settings' => array('image_style' => 'thumbnail')));
    print drupal_render($renderable );
}
?>

Note that this is not the only way to get html from field values. You can use theme functions and load that with values you find on $entity object and print that if you wish.

1
  • Thanks a lot! That made my day! I also added 'label' => 'hidden' and that was that. I will dig into field_view_field, another tool in the toolbox :-). Tried to give you an upvote apart from the right answer tick, but apparently my reputation is to modest for that so far. But many thanks again.
    – TBJ
    Mar 4, 2016 at 10:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.