Untitled

 avatar
unknown
plain_text
a year ago
1.3 kB
4
Indexable
<?php

use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;

/**
 * Implements hook_entity_field_access().
 */
function profile_privacy_entity_field_access($op, EntityInterface $entity, $field, AccountInterface $account, $items) {
  // Check if the entity is a user and the operation is 'view'.
  if ($entity->getEntityTypeId() === 'user' && $op === 'view') {
    // Check if the field is either 'field_first_name' or 'field_last_name'.
    if (in_array($field->getName(), ['field_first_name', 'field_last_name'])) {
      // Load the user's profile.
      $profile = \Drupal::entityTypeManager()->getStorage('profile')->loadByProperties(['uid' => $entity->id()]);
      $profile = reset($profile);

      // Check if the profile exists and the taxonomy term is set.
      if ($profile && $profile->hasField('field_taxonomy_term')) {
        $terms = $profile->get('field_taxonomy_term')->referencedEntities();

        foreach ($terms as $term) {
          // Assuming the term name to check is 'hide my first name & last name'.
          if ($term->getName() == 'hide my first name & last name') {
            // Deny access to the field.
            return FALSE;
          }
        }
      }
    }
  }

  // Default access.
  return TRUE;
}
Editor is loading...
Leave a Comment