function entity_hierarchy_form_node_form_alter in Entity Reference Hierarchy 8
Implements Adds a vertical tab to the node form allowing a hierarchy parent to be selected or deleted. Here we're doing some permission checking, then presenting the form using the HierarchyManager class. We then use an #entity_builders callback function to save the form data to the node object.
See also
hook_form_BASE_FORM_ID_alter() for node_form().
HierarchyManagerInterface::addHierarchyFormElement
entity_hierarchy_node_builder
File
- ./
entity_hierarchy.module, line 41 - A module to make nodes hierarchical.
Code
function entity_hierarchy_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// TODO: entity_hierarchy_set_breadcrumbs($node, TRUE);
// Load the node object associated with this form
$node = $form_state
->getFormObject()
->getEntity();
$account = \Drupal::currentUser();
/** @var \Drupal\entity_hierarchy\HierarchyManager $hierarchy_manager */
$hierarchy_manager = \Drupal::service('entity_hierarchy.manager');
// If this node type can be a child.
// TODO: Probably should be doing access checking using a class like
// EntityAccessControlHandler::access or more at the route/level
/** @see \Drupal\Core\Entity\EntityAccessControlHandler::access */
if ($hierarchy_manager
->hierarchyCanBeChild($node) || $hierarchy_manager
->hierarchyCanBeParent($node)) {
// if the current user can edit the current node's hierarchy settings (or create new children)
$uid = $node
->getOwnerId();
$can_set_parent = $account
->hasPermission('edit all node parents') || $node
->isNew() && $account
->hasPermission('create child nodes') || $uid == $account
->getAccount()
->id() && $account
->hasPermission('edit own node parents');
// Only show the form is the user has permission
if ($can_set_parent) {
$collapsed = TRUE;
// Todo: fix (check if a parent is already set)
$form = $hierarchy_manager
->addHierarchyFormElement($form, $form_state, $node, $account, $collapsed);
// Form API entity_builders callback; see https://www.drupal.org/node/2420295
$form['#entity_builders'][] = 'entity_hierarchy_node_builder';
}
}
}