You are here

protected function HierarchyChildrenForm::actions in Entity Reference Hierarchy 3.x

Same name and namespace in other branches
  1. 8.2 src/Form/HierarchyChildrenForm.php \Drupal\entity_hierarchy\Form\HierarchyChildrenForm::actions()

Returns an array of supported actions for the current entity form.

This function generates a list of Form API elements which represent actions supported by the current entity form.

@todo Consider introducing a 'preview' action here, since it is used by many entity types.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Return value

array An array of supported Form API action elements keyed by name.

Overrides EntityForm::actions

File

src/Form/HierarchyChildrenForm.php, line 211

Class

HierarchyChildrenForm
Defines a form for re-ordering children.

Namespace

Drupal\entity_hierarchy\Form

Code

protected function actions(array $form, FormStateInterface $form_state) {
  $actions = parent::actions($form, $form_state);
  $actions['submit']['#value'] = $this
    ->t('Update child order');

  // Don't perform field validation.
  $actions['submit']['#limit_validation_errors'] = [
    [
      'children',
    ],
    [
      'fieldname',
    ],
  ];
  unset($actions['delete']);

  // Don't show the actions links if there are no children.
  if (empty(Element::children($form['children']))) {
    unset($actions['submit']);
  }
  $fields = $this->parentCandidate
    ->getCandidateFields($this->entity);
  $fieldName = $form_state
    ->getValue('fieldname') ?: reset($fields);
  $entityType = $this->entity
    ->getEntityType();
  if ($entityType
    ->hasHandlerClass('entity_hierarchy') && ($childBundles = $this->parentCandidate
    ->getCandidateBundles($this->entity)) && isset($childBundles[$fieldName])) {
    $handlerClass = $entityType
      ->getHandlerClass('entity_hierarchy');

    /** @var \Drupal\entity_hierarchy\Handler\EntityHierarchyHandlerInterface $handler */
    $handler = new $handlerClass();
    $links = [];
    foreach ($childBundles[$fieldName] as $id => $info) {
      $url = $handler
        ->getAddChildUrl($entityType, $this->entity, $id, $fieldName);
      if ($url
        ->access()) {
        $links[$id] = [
          'title' => $this
            ->t('Create new @bundle', [
            '@bundle' => $info['label'],
          ]),
          'url' => $url,
        ];
      }
    }
    if (count($links) > 1) {
      $actions['add_child'] = [
        '#type' => 'dropbutton',
        '#links' => $links,
      ];
    }
    else {
      $link = reset($links);
      $actions['add_child'] = [
        '#type' => 'link',
        '#title' => $link['title'],
        '#url' => $link['url'],
        '#attributes' => [
          'class' => [
            'button',
            'button--primary',
          ],
        ],
        '#weight' => -100,
      ];
    }
  }
  return $actions;
}