function _rac_restrict_field_values in Role Access Control 8
Same name and namespace in other branches
- 8.2 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().
2 calls to _rac_restrict_field_values()
- rac_fca_field_widget_field_collection_embed_form_alter in contrib/
rac_fca/ rac_fca.module - Implements hook_field_widget_WIDGET_TYPE_form_alter().
- rac_na_form_node_form_alter in contrib/
rac_na/ rac_na.module - Implements hook_form_FORM_ID_alter().
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;
}
}