0

We have a content type with a date range element on our D8 site. I got a request to hide the display of the end date if the content editor decided so.

From testing, the content editor can't delete the end date-- the field fails validation if an end date has already been specified. And anyways, they don't want to delete the end date-- they want to maintain that information-- they only want it not to display to the public audience, in certain circumstances.

I started to approach this by adding a second field to the content type, a boolean checkbox "Hide End Date". I wrote a hook_preprocess_field in our .theme file in order to change the display of the date range value. But after debugging the variables, I realized that the date range field doesn't have any information about the value of the "hide end date" field, of course.

I'm not sure how best to proceed. Is hook_preprocess_node the place where I can look at both field values, and alter the value of the date range field? Will that affect display of the field throughout the site, including views?

1

Add a boolean field as a condition to hide the end-date is a fine solution. For hiding the field you can either check for the boolean in the template:

{% if $node->field_hide_end_date->value %}
    {{ $node->field_range->value|format_date('my_custom_date_format') }}
{% else %}
    {# Original version of the field #}
    {{ $content['field_range'] }}
{% endif %}

Or change the value in a preprocess method

function custom_module_preprocess_node(&$variables) {
  if (array_key_exists('field_period', $variables['elements'])) {
    $node = $variables['elements']['#node'];

    if ($node->field_hide_end_date->value) {
      $variables['elements']['field_period'] = [
        '#markup' => (new DrupalDateTime($node->field_period->value))->format('d-m-Y'),
      ];
    }
    // else: business as usual.
  }
}
| improve this answer | |

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.