You are here

function _rac_restore_field_values in Role Access Control 8

Same name and namespace in other branches
  1. 8.2 rac.module \_rac_restore_field_values()

Repopulate the restricted values for a given field.

Parameters

string $fieldName: Fieldname of field being processesed.

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

\Drupal\Core\Form\FormStateInterface $form_state: Optional User to restrict values for, defaults to \Drupal::currentUser().

1 call to _rac_restore_field_values()
_rac_field_validate in ./rac.module
Implements hook_field_validate().

File

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

Code

function _rac_restore_field_values($fieldName, array &$element, FormStateInterface $form_state) {

  // Form values to retrieve stored data.
  $formValues = $form_state
    ->getValues();
  if (!isset($formValues[$fieldName])) {

    // Field value is not set, so we can't restore value.
    return;
  }

  // Get data from request and generated form.
  $was_visibile = (array) json_decode(base64_decode($formValues["_rac_" . $fieldName . "_original"]));
  $current_visible = array_keys($element['widget']["#options"]);
  $restricted_values = $element['widget']["#restricted_value"];

  // Helper function to dereferenced the submitted value.
  $map_target_id = function ($v) {
    return $v["target_id"];
  };

  // Helper function to revert dereferencing.
  $map_target_id_reverse = function ($v) {
    return [
      "target_id" => $v,
    ];
  };

  // Calculate the set of data submitted.
  //
  // We need to take into account that the users access may have changed
  // between form generation and form submission. Thus, use the following
  // alogorythm to recalculate the selected values. where orig is the
  // value when original form was built, and the cur is the default_value
  // the last time the form was regenerated on form submission.
  //
  // Selected = cur.default_value - (cur.vis - (orig.vis - submitted))
  //
  $always_visible = array_intersect($was_visibile, $current_visible);
  $submitted_value = array_map($map_target_id, $formValues[$fieldName]);
  $removed = array_diff($always_visible, $submitted_value);
  $visible_value = array_diff($current_visible, $removed);
  $selected = array_merge($visible_value, $restricted_values);

  // Remap back to original value format and set the form state.
  $remapped = array_map($map_target_id_reverse, $selected);
  $form_state
    ->setValue($fieldName, $remapped);
}