DISABLE ADBLOCK

ADBlock is blocking some content on the site

ADBlock errore
Results found: 

Compute values to display on the user profile page based on other user profile field values

drupal.stackexchange https://drupal.stackexchange.com/questions/292817
  •   users  -  8
  •  | 
  •  
  •  | 
  •   ( words)

Question

I've added fields to user profiles:

  • subscriber (yes/no)
  • guest subscriber (yes/no)
  • print subscription expiration date
  • online subscription expiration date

On the user profile page, I want to display things like:

  • Because you are a guest subscriber, your subscription never expires.
  • Your subscription will expire on date1 [the later of the print and online subscription dates]. Please renew by date2 for uninterrupted service.
  • Your subscription expired XX days/XX weeks/XX months ago on date.

These are some examples to give the idea. I need to look at profile field values before the profile is displayed, do some computing, and then add additional, display-only fields to the page or modify the value of existing fields that are displayed on the page.

All I need is a clue about the approach. I already have a custom module, so using something similar to hook_form_alter will do nicely. I've read about 20 posts, but none that seem to match.

Solution

You can make use of hook_entity_extra_field_info() . Below is the following code snippet which you can use in your module:

/**
 * Implements hook_entity_extra_field_info().
 */
function my_module_entity_extra_field_info() {
  $extra = array();

    $extra['your_entity']['your_content_type']['display']['my_own_pseudo_field'] = array(
      'label' => t('My own field'),
      'description' => t('This is my own pseudo-field'),
      'weight' => 100,
      'visible' => TRUE,
    );
  }

  return $extra;
}
And you can use hook_ENTITY_TYPE_view
/**
 * Implements hook_ENTITY_TYPE_view().
 */
function my_module_your_entity_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
  if ($display->getComponent('my_own_pseudo_field')) {
      $build['my_own_pseudo_field'] = [
        '#type' => 'markup',
        '#markup' => 'This is my custom content', 
    ];
  }
}

Please replace the entity and entity type with your requirement. Since it is only for the display this code snippet will work . Clear the cache you will find this field in manage display section .

If you like, leave us your opinion

Was the article helpful and is it translated correctly?

Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange