-2

How do I check to see if a field is being used on a node and if so, perform an action elsewhere on the page, such as moving a block or adding a body class?

1
  • Reasonable question, why the downvotes?
    – Sam
    Feb 5 at 12:46

1 Answer 1

1

How do I check to see if a field is being used on a node?

$node->hasField($field_name)

and if so, perform an action elsewhere on the page, such as moving a block?

Configure multiple regions with different sets of blocks and then in a page template

{% if node.hasfield('field_image') %}
  {{ page.sidebar_second }}
{% endif %}

or adding a body class?

See How do I add body class on specific content_type who have specific field?

In your case use $node->hasField('field_image') if you want to check for the presence of a field even if it is empty.

3
  • Thanks! Could this be modified to work for a paragraph field?
    – Sam
    Feb 5 at 13:49
  • 1
    Yes, something like node.field_paragraph.entity.hasfield('field_in_paragraph')
    – 4uk4
    Feb 5 at 13:57
  • So if my paragraph field was named 'field_image' and the field within it was named "banner" it would be like this? node.field_image.entity.hasfield('banner')
    – Sam
    Feb 5 at 14:03

Your Answer

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

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