function entity_hierarchy_form_alter in Entity Reference Hierarchy 8.2
Same name and namespace in other branches
- 3.x entity_hierarchy.module \entity_hierarchy_form_alter()
Implements hook_form_alter().
File
- ./
entity_hierarchy.module, line 92 - A module to make entities hierarchical.
Code
function entity_hierarchy_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$formObject = $form_state
->getFormObject();
if ($formObject instanceof ContentEntityDeleteForm) {
if ($children = \Drupal::service('class_resolver')
->getInstanceFromDefinition(ChildEntityWarningBuilder::class)
->buildChildEntityWarnings($formObject
->getEntity())) {
foreach ($children as $ix => $child) {
$form['children'][$ix] = [
'title' => [
'#markup' => $child
->getWarning(),
],
'items' => $child
->getList(),
];
}
return;
}
}
if ($formObject instanceof ContentEntityForm) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $formObject
->getEntity();
$parentFields = \Drupal::service('entity_field.manager')
->getFieldMapByFieldType('entity_reference_hierarchy');
if (isset($parentFields[$entity
->getEntityTypeId()])) {
// We have a parent field.
foreach ($parentFields[$entity
->getEntityTypeId()] as $field_name => $detail) {
if ($entity
->hasField($field_name) && \Drupal::request()->query
->has($field_name) && isset($form[$field_name]['widget'][0]['target_id']['target_id']) && ($target_entity = \Drupal::entityTypeManager()
->getStorage($entity
->getEntityTypeId())
->load(\Drupal::request()->query
->get($field_name))) && $target_entity
->access('view')) {
$form[$field_name]['widget'][0]['target_id']['target_id']['#default_value'] = $target_entity;
}
}
}
}
}