You are here

function _rac_restrict_field_values in Role Access Control 8.2

Same name and namespace in other branches
  1. 8 rac.module \_rac_restrict_field_values()

Remove options from a field that should not be displayed to the user.

Parameters

string $fieldName: Field name of field being processesed.

array $element: Form element for Role Entity Reference Field.

\Drupal\Core\Session\AccountInterface $user: Optional User to restrict values for, defaults to \Drupal::currentUser().

File

./rac.module, line 185
Module providing role access relations.

Code

function _rac_restrict_field_values($fieldName, array &$element, AccountInterface $user = NULL) {
  if ($user === NULL) {
    $user = \Drupal::currentUser();
  }
  if (isset($element['widget']['#type']) && in_array($element['widget']['#type'], [
    "select",
    "checkboxes",
  ])) {

    // Get original field values.
    $orig_options = $element['widget']["#options"];
    $orig_value = $element['widget']["#default_value"];

    // Helper function to map roles to string ids.
    $mapRoleID = function ($role) {
      return $role
        ->id();
    };

    // Calculate the values the user is allowed to see, and which values
    // should be displayed as selected on the form.
    $allowed_roles = _rac_get_account_roles("update", $user);
    $visible = array_map($mapRoleID, $allowed_roles);

    // Strip any options not visible to the user.
    $allowed_options = array_intersect_key($orig_options, array_flip($visible));

    // Strip any options not visible to the user.
    $allowed_values = array_intersect($orig_value, $visible);
    $restricted_values = array_diff($orig_value, $allowed_values);

    // Restrict the values visible on the form.
    $element['widget']["#options"] = $allowed_options;
    $element['widget']["#default_value"] = $allowed_values;

    // Store $restricted_values for use on submission.
    $element['widget']["#restricted_value"] = $restricted_values;

    // Set list of visible values so we can pass them back on form submission.
    // This is set via default_value as to not override any values coming
    // From the users form submission. Alloed options are encoded in base64 so
    // The data is not easily manipulated by the end user.
    $element["_rac_" . $fieldName . "_original"] = [
      '#type' => "hidden",
      "#default_value" => base64_encode(json_encode(array_keys($allowed_options))),
    ];

    // Setup Validate Call back on the field.
    $element["#element_validate"][] = "_rac_field_validate";
    $element["#field_name"] = $fieldName;
  }
}