function readonly_field_widget_form_alter in Read-only Field Widget 8
Implements hook_form_alter().
File
- ./
readonly_field_widget.module, line 30 - Contains readonly_field_widget.module..
Code
function readonly_field_widget_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// Check that this is an entity form.
$form_object = $form_state
->getFormObject();
if ($form_object instanceof EntityFormInterface) {
$entity = $form_object
->getEntity();
// Set access to readonly widget items based on their view access.
$storage = $form_state
->getStorage();
if ($entity instanceof FieldableEntityInterface && isset($storage['form_display'])) {
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
$form_display = $storage['form_display'];
}
else {
return;
}
foreach ($form_display
->getComponents() as $name => $options) {
$widget = $form_display
->getRenderer($name);
if ($widget instanceof ReadonlyFieldWidget) {
$items = $entity
->get($name);
$items
->filterEmptyItems();
$form[$name]['#access'] = $items
->access('view');
}
}
}
}