Tokens aren't replaced for private fields when user doesn't have access

Created on 16 August 2024, 10 months ago
Updated 30 August 2024, 9 months ago

Problem/Motivation

We have some private fields that are hidden from anonymous users but have found that these private fields don't get their token values replaced.

We have some custom code that simply loads the node object and generates a message using tokens in order to notify authorized users of the content. But when this code runs anonymously, the tokens aren't replaced due to access when programmatically it is expected they would.

Steps to reproduce

- Create a field on a content type (e.g., "field_private_test")
- Set "Field visibility and permissions" to "Private" on the new field
- Create node and set a value for the private field
- Implement test code that does a token replace on the new node (example depends on devel module's dpm() and anonymous users having permission to see it, also be sure to update node ID with ID to your created node)

/**
 * Implements hook_preprocess_html().
 */
function example_preprocess_html(&$variables) {
  /** @var \Drupal\Core\Utility\Token $token_service */
  $token_service = \Drupal::token();
  $node = Node::load(35284);
  $data = [$node->getEntityTypeId() => $node];
  $result = $token_service->replace('[site:name] [node:nid]: [node:field_private_test]', $data, ['clear' => FALSE]);
  dpm($result);
}

- Load page as anonymous user and note "[node:field_private_test]" did not get replaced

πŸ› Bug report
Status

Active

Version

1.0

Component

Code

Created by

πŸ‡ΊπŸ‡ΈUnited States greenskin

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024