You are here

class HierarchyChildrenForm 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

Defines a form for re-ordering children.

Hierarchy

Expanded class hierarchy of HierarchyChildrenForm

1 file declares its use of HierarchyChildrenForm
entity_hierarchy.module in ./entity_hierarchy.module
A module to make entities hierarchical.

File

src/Form/HierarchyChildrenForm.php, line 22

Namespace

Drupal\entity_hierarchy\Form
View source
class HierarchyChildrenForm extends ContentEntityForm {
  const CHILD_ENTITIES_STORAGE = 'child_entities';

  /**
   * The hierarchy being displayed.
   *
   * @var \Drupal\Core\Entity\ContentEntityInterface
   */
  protected $entity;

  /**
   * Nested set storage factory.
   *
   * @var \Drupal\entity_hierarchy\Storage\NestedSetStorageFactory
   */
  protected $nestedSetStorageFactory;

  /**
   * Nested set node key factory.
   *
   * @var \Drupal\entity_hierarchy\Storage\NestedSetNodeKeyFactory
   */
  protected $nodeKeyFactory;

  /**
   * Parent candidate.
   *
   * @var \Drupal\entity_hierarchy\Information\ParentCandidateInterface
   */
  protected $parentCandidate;

  /**
   * Tree node mapper.
   *
   * @var \Drupal\entity_hierarchy\Storage\EntityTreeNodeMapperInterface
   */
  protected $entityTreeNodeMapper;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {

    /** @var self $instance */
    $instance = parent::create($container);
    $instance->nestedSetStorageFactory = $container
      ->get('entity_hierarchy.nested_set_storage_factory');
    $instance->nodeKeyFactory = $container
      ->get('entity_hierarchy.nested_set_node_factory');
    $instance->parentCandidate = $container
      ->get('entity_hierarchy.information.parent_candidate');
    $instance->entityTreeNodeMapper = $container
      ->get('entity_hierarchy.entity_tree_node_mapper');
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public function getBaseFormId() {

    // Don't show a parent form here.
    return NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $cache = (new CacheableMetadata())
      ->addCacheableDependency($this->entity);

    /** @var \Drupal\Core\Field\FieldDefinitionInterface[] $fields */
    $fields = $this->parentCandidate
      ->getCandidateFields($this->entity);
    if (!$fields) {
      throw new NotFoundHttpException();
    }
    $fieldName = $form_state
      ->getValue('fieldname') ?: reset($fields);
    if (count($fields) === 1) {
      $form['fieldname'] = [
        '#type' => 'value',
        '#value' => $fieldName,
      ];
    }
    else {
      $form['select_field'] = [
        '#type' => 'container',
        '#attributes' => [
          'class' => [
            'container-inline',
          ],
        ],
      ];
      $form['select_field']['fieldname'] = [
        '#type' => 'select',
        '#title' => $this
          ->t('Field'),
        '#description' => $this
          ->t('Field to reorder children in.'),
        '#options' => array_map(function ($field_name) {
          return $this->entity
            ->getFieldDefinitions()[$field_name]
            ->getLabel();
        }, $fields),
        '#default_value' => $fieldName,
      ];
      $form['select_field']['update'] = [
        '#type' => 'submit',
        '#value' => $this
          ->t('Update'),
        '#submit' => [
          '::updateField',
        ],
      ];
    }

    /** @var \PNX\NestedSet\Node[] $children */

    /** @var \PNX\NestedSet\NestedSetInterface $storage */
    $storage = $this->nestedSetStorageFactory
      ->get($fieldName, $this->entity
      ->getEntityTypeId());
    $children = $storage
      ->findChildren($this->nodeKeyFactory
      ->fromEntity($this->entity));
    $childEntities = $this->entityTreeNodeMapper
      ->loadAndAccessCheckEntitysForTreeNodes($this->entity
      ->getEntityTypeId(), $children, $cache);
    $form_state
      ->setTemporaryValue(self::CHILD_ENTITIES_STORAGE, $childEntities);
    $form['#attached']['library'][] = 'entity_hierarchy/entity_hierarchy.nodetypeform';
    $form['children'] = [
      '#type' => 'table',
      '#header' => [
        t('Child'),
        t('Type'),
        t('Weight'),
        t('Operations'),
      ],
      '#tabledrag' => [
        [
          'action' => 'order',
          'relationship' => 'sibling',
          'group' => 'children-order-weight',
        ],
      ],
      '#empty' => $this
        ->t('There are no children to reorder'),
    ];
    $bundles = FALSE;
    foreach ($children as $weight => $node) {
      if (!$childEntities
        ->contains($node)) {

        // Doesn't exist or is access hidden.
        continue;
      }

      /** @var \Drupal\Core\Entity\ContentEntityInterface $childEntity */
      $childEntity = $childEntities
        ->offsetGet($node);
      if (!$childEntity
        ->isDefaultRevision()) {

        // We only update default revisions here.
        continue;
      }
      $child = $node
        ->getId();
      $form['children'][$child]['#attributes']['class'][] = 'draggable';
      $form['children'][$child]['#weight'] = $weight;
      $form['children'][$child]['title'] = $childEntity
        ->toLink()
        ->toRenderable();
      if (!$bundles) {
        $bundles = $this->entityTypeBundleInfo
          ->getBundleInfo($childEntity
          ->getEntityTypeId());
      }
      $form['children'][$child]['type'] = [
        '#markup' => $bundles[$childEntity
          ->bundle()]['label'],
      ];
      $form['children'][$child]['weight'] = [
        '#type' => 'weight',
        '#delta' => 50,
        '#title' => t('Weight for @title', [
          '@title' => $childEntity
            ->label(),
        ]),
        '#title_display' => 'invisible',
        '#default_value' => $childEntity->{$fieldName}->weight,
        // Classify the weight element for #tabledrag.
        '#attributes' => [
          'class' => [
            'children-order-weight',
          ],
        ],
      ];

      // Operations column.
      $form['children'][$child]['operations'] = [
        '#type' => 'operations',
        '#links' => [],
      ];
      if ($childEntity
        ->access('update') && $childEntity
        ->hasLinkTemplate('edit-form')) {
        $form['children'][$child]['operations']['#links']['edit'] = [
          'title' => t('Edit'),
          'url' => $childEntity
            ->toUrl('edit-form'),
        ];
      }
      if ($childEntity
        ->access('delete') && $childEntity
        ->hasLinkTemplate('delete-form')) {
        $form['children'][$child]['operations']['#links']['delete'] = [
          'title' => t('Delete'),
          'url' => $childEntity
            ->toUrl('delete-form'),
        ];
      }
    }
    $cache
      ->applyTo($form);
    return $form;
  }

  /**
   * Submit handler for update field button.
   *
   * @param array $form
   *   Form array.
   * @param \Drupal\Core\Form\FormStateInterface $formState
   *   Form state.
   */
  public function updateField(array $form, FormStateInterface $formState) {
    $formState
      ->setRebuild(TRUE);
  }

  /**
   * {@inheritdoc}
   */
  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;
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $children = $form_state
      ->getValue('children');
    $childEntities = $form_state
      ->getTemporaryValue(self::CHILD_ENTITIES_STORAGE);
    $fieldName = $form_state
      ->getValue('fieldname');
    $batch = [
      'title' => new TranslatableMarkup('Reordering children ...'),
      'operations' => [],
      'finished' => [
        static::class,
        'finished',
      ],
    ];
    foreach ($childEntities as $node) {
      $childEntity = $childEntities
        ->offsetGet($node);
      if (!$childEntity
        ->isDefaultRevision()) {

        // We don't operate on other than the default revision.
        continue;
      }
      $batch['operations'][] = [
        [
          static::class,
          'reorder',
        ],
        [
          $fieldName,
          $childEntity,
          $children[$node
            ->getId()]['weight'],
        ],
      ];
    }
    batch_set($batch);
  }

  /**
   * Reorder batch callback.
   *
   * @param string $fieldName
   *   Field name.
   * @param \Drupal\Core\Entity\ContentEntityInterface $childEntity
   *   Child entity being updated.
   * @param int $weight
   *   New weight.
   */
  public static function reorder($fieldName, ContentEntityInterface $childEntity, $weight) {
    $childEntity->{$fieldName}->weight = $weight;
    $childEntity
      ->save();
  }

  /**
   * Batch finished callback.
   */
  public static function finished() {
    \Drupal::messenger()
      ->addMessage(new TranslatableMarkup('Updated child order.'));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ContentEntityForm::$entityRepository protected property The entity repository service.
ContentEntityForm::$entityTypeBundleInfo protected property The entity type bundle info service.
ContentEntityForm::$time protected property The time service.
ContentEntityForm::addRevisionableFormFields protected function Add revision form fields if the entity enabled the UI.
ContentEntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityForm::buildEntity 4
ContentEntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties. Overrides EntityForm::copyFormValuesToEntity
ContentEntityForm::flagViolations protected function Flags violations for the current form. 4
ContentEntityForm::getBundleEntity protected function Returns the bundle entity of the entity, or NULL if there is none.
ContentEntityForm::getEditedFieldNames protected function Gets the names of all fields edited in the form. 4
ContentEntityForm::getFormDisplay public function Gets the form display. Overrides ContentEntityFormInterface::getFormDisplay
ContentEntityForm::getFormLangcode public function Gets the code identifying the active form language. Overrides ContentEntityFormInterface::getFormLangcode
ContentEntityForm::getNewRevisionDefault protected function Should new revisions created on default.
ContentEntityForm::init protected function Initializes the form state and the entity before the first form build. Overrides EntityForm::init 1
ContentEntityForm::initFormLangcodes protected function Initializes form language code values.
ContentEntityForm::isDefaultFormLangcode public function Checks whether the current form language matches the entity one. Overrides ContentEntityFormInterface::isDefaultFormLangcode
ContentEntityForm::prepareEntity protected function Prepares the entity object before the form is built first. Overrides EntityForm::prepareEntity 1
ContentEntityForm::setFormDisplay public function Sets the form display. Overrides ContentEntityFormInterface::setFormDisplay
ContentEntityForm::showRevisionUi protected function Checks whether the revision form fields should be added to the form.
ContentEntityForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides EntityForm::submitForm 4
ContentEntityForm::updateChangedTime public function Updates the changed time of the entity.
ContentEntityForm::updateFormLangcode public function Updates the form language to reflect any change to the entity language.
ContentEntityForm::validateForm public function Button-level validation handlers are highly discouraged for entity forms, as they will prevent entity validation from running. If the entity is going to be saved during the form submission, this method should be manually invoked from the button-level… Overrides FormBase::validateForm 3
ContentEntityForm::__construct public function Constructs a ContentEntityForm object. 9
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 13
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 3
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 12
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
FormBase::$configFactory protected property The config factory. 3
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 3
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route.
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
HierarchyChildrenForm::$entity protected property The hierarchy being displayed. Overrides ContentEntityForm::$entity
HierarchyChildrenForm::$entityTreeNodeMapper protected property Tree node mapper.
HierarchyChildrenForm::$nestedSetStorageFactory protected property Nested set storage factory.
HierarchyChildrenForm::$nodeKeyFactory protected property Nested set node key factory.
HierarchyChildrenForm::$parentCandidate protected property Parent candidate.
HierarchyChildrenForm::actions protected function Returns an array of supported actions for the current entity form. Overrides EntityForm::actions
HierarchyChildrenForm::CHILD_ENTITIES_STORAGE constant
HierarchyChildrenForm::create public static function Instantiates a new instance of this class. Overrides ContentEntityForm::create
HierarchyChildrenForm::finished public static function Batch finished callback.
HierarchyChildrenForm::form public function Gets the actual form array to be built. Overrides ContentEntityForm::form
HierarchyChildrenForm::getBaseFormId public function Returns a string identifying the base form. Overrides EntityForm::getBaseFormId
HierarchyChildrenForm::reorder public static function Reorder batch callback.
HierarchyChildrenForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
HierarchyChildrenForm::updateField public function Submit handler for update field button.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.