2

I have an image field inside the content type 'Article'. I have two view mode: "teaser" and "full". I have a view page ('Homepage') showing all 'Article' nodes using "teaser" view mode.

  • In the 'Homepage' view, I'd like to display a default image if the image field is not setted.
  • In the "full" view mode I'd like to hide image field if is not set.

It's possible to do that?

3 Answers 3

0

Here is what I would do.

Do not set a default image for your image field.

In views, instead of using a content: teaser use content: fields. Then in No Results Behaviour of your image field you put <img src="/link/to/image.png">

Then you create a "full" version using content: fields, which you don't do a No Results Behaviour.

0

I would create a preprocessor or add to existing one for node and check the view mode. If it is 'full', check to see if the image field has values/fid. If it does not, unset it from $content - which takes it out of the render array. You could also provide a .tpl file with a condition to render the specific field based on whether or not it has a value.

On the image field itself, you can upload a default image, which is what will display if no value is provided. That should solve the Homepage View display, Drupal should show the image when rendering if one is not provided by the user.

You can still construct Views with view modes, and in my opinion is far easier to work with than Views with fields.

0

If you are comfortable with twig, you can also make a custom template for your node teaser and use syntax like this:

{% if content.field_image.0 %}
   {{ content.field_image.0 }}
{% else %}
  <img src="/path/to/default/image.jpg" alt="Default image">
{% endif %}

The field name and path would need to be customized for your instance.

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.