You are here

public function Menu::alterForm in Workbench Access 8

Alters the selection options provided for an access control field.

Parameters

\Drupal\workbench_access\Entity\AccessSchemeInterface $scheme: Access scheme.

array $form: The content entry form to alter.

\Drupal\Core\Form\FormStateInterface $form_state: Active form state data.

\Drupal\Core\Entity\ContentEntityInterface $entity: The entity object that the form is modifying.

Overrides AccessControlHierarchyBase::alterForm

File

src/Plugin/AccessControlHierarchy/Menu.php, line 140

Class

Menu
Defines a hierarchy based on a Menu.

Namespace

Drupal\workbench_access\Plugin\AccessControlHierarchy

Code

public function alterForm(AccessSchemeInterface $scheme, array &$form, FormStateInterface &$form_state, ContentEntityInterface $entity) {
  if (!isset($form['menu'])) {
    return;
  }
  $element =& $form['menu'];
  $menu_check = [];
  $user_sections = $this->userSectionStorage
    ->getUserSections($scheme);
  foreach ($element['link']['menu_parent']['#options'] as $id => $data) {

    // The menu value here prepends the menu name. Remove that.
    $parts = explode(':', $id);
    $menu = array_shift($parts);

    // If the second element is empty, this is the root element which is
    // checked by menu name.
    if (empty($parts)) {
      $sections = [
        $menu,
      ];
    }
    else {
      $sections = [
        implode(':', $parts),
      ];
    }
    $menu_parent = $menu . ':';

    // Remove unusable elements, except the existing parent.
    // Do not remove top-level menus, we check those separately.
    if (!empty($element['link']['menu_parent']['#default_value']) && $id != $menu_parent && empty(WorkbenchAccessManager::checkTree($scheme, $sections, $user_sections))) {
      unset($element['link']['menu_parent']['#options'][$id]);
      if ($id == $element['link']['menu_parent']['#default_value']) {
        unset($element['link']['menu_parent']['#default_value']);
      }
    }

    // Check for the root menu item.
    if (!isset($menu_check[$menu]) && isset($element['link']['menu_parent']['#options'][$menu . ':'])) {
      if (empty(WorkbenchAccessManager::checkTree($scheme, [
        $menu,
      ], $user_sections))) {
        unset($element['link']['menu_parent']['#options'][$menu . ':']);
      }
      $menu_check[$menu] = TRUE;
    }
  }

  // As long as there are menu options available, check that the default value
  // is still in the options, if not then default to the root item.
  if (!empty($element['link']['menu_parent']['#options']) && empty($element['link']['menu_parent']['#default_value'])) {
    $element['link']['menu_parent']['#default_value'] = current(array_keys($element['link']['menu_parent']['#options']));
  }
}