1
  • I have a content type event.
  • It has a link field field_event_location_link
  • Both the link text and url are optional

By default Drupal uses the url as the title if there is no title typed in.

I want to show 'Location' if the title is not filled in.

How can I use a preprocess function to see if there is a title, and if not, use my string.

I tried ...

function my_module_preprocess_field(&$variables) {
  if ($variables['field_name'] == 'field_event_location_link') {
    if ($variables['items'][0]['content']['#title'] == '') {
     $variables['items'][0]['content']['#title'] = 'Location';
    }
  }
}

But it doesn't work and I think it's because by the time I get to that point, Drupal has already used the uri for the #title.

Question: Can I catch it before that? Or can I get a variable for the URL and use that variable in the '' above? Should I be checking if something is empty...?

3
  • Have you also tried to check if it not isset? As in if (!isset($variables['items'][0]['content']['#title'])) { ...?
    – leymannx
    Commented Jan 13, 2020 at 17:46
  • Sadly, this produced an error: Fatal error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead). The suggestion of if (null !== ($variables['items'][0]['content']['#title'])) { didn't work either, if statement didn't check out.
    – Sarah C
    Commented Jan 13, 2020 at 18:00
  • Try to dump the value of the field using print_r for example.
    – user72672
    Commented Jan 13, 2020 at 18:32

1 Answer 1

0

If you inspect with $variables['items'][0]['content'] with Devel kint

kint($variables['items'][0]['content']);

enter image description here

But it doesn't work and I think it's because by the time I get to that point, Drupal has already used the uri for the #title.

Correct, so all you gotta do is check if the title is equal to the url utilizing Url::toString.

  if ($variables['field_name'] == 'field_event_location_link') {
    $link_url = $variables['items'][0]['content']['#url']->toString();
    if ($variables['items'][0]['content']['#title'] == $link_url) {
      $variables['items'][0]['content']['#title'] = 'Location';
    }
  }

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.