You are here

class EntitySubqueueForm in Entityqueue 8

Form controller for the entity subqueue edit forms.

Hierarchy

Expanded class hierarchy of EntitySubqueueForm

File

src/Form/EntitySubqueueForm.php, line 21

Namespace

Drupal\entityqueue\Form
View source
class EntitySubqueueForm extends ContentEntityForm {

  /**
   * The entity being used by this form.
   *
   * @var \Drupal\entityqueue\EntitySubqueueInterface
   */
  protected $entity;

  /**
   * The element info manager.
   *
   * @var \Drupal\Core\Render\ElementInfoManagerInterface
   */
  protected $elementInfo;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('entity.repository'), $container
      ->get('entity_type.bundle.info'), $container
      ->get('datetime.time'), $container
      ->get('element_info'));
  }

  /**
   * Constructs a EntitySubqueueForm.
   *
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
   *   The entity repository service.
   * @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
   *   The entity type bundle service.
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   The time service.
   * @param \Drupal\Core\Render\ElementInfoManagerInterface $element_info
   *   The element info manager.
   */
  public function __construct(EntityRepositoryInterface $entity_repository, EntityTypeBundleInfoInterface $entity_type_bundle_info, TimeInterface $time, ElementInfoManagerInterface $element_info) {
    parent::__construct($entity_repository, $entity_type_bundle_info, $time);
    $this->elementInfo = $element_info;
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);
    $form['#title'] = $this
      ->t('Edit subqueue %label', [
      '%label' => $this->entity
        ->label(),
    ]);

    // Since the form has ajax buttons, the $wrapper_id will change each time
    // one of those buttons is clicked. Therefore the whole form has to be
    // replaced, otherwise the buttons will have the old $wrapper_id and will
    // only work on the first click.
    if ($form_state
      ->has('subqueue_form_wrapper_id')) {
      $wrapper_id = $form_state
        ->get('subqueue_form_wrapper_id');
    }
    else {
      $wrapper_id = Html::getUniqueId($this
        ->getFormId() . '-wrapper');
    }
    $form_state
      ->set('subqueue_form_wrapper_id', $wrapper_id);
    $form['#prefix'] = '<div id="' . $wrapper_id . '">';
    $form['#suffix'] = '</div>';

    // @todo Use the 'Machine name' field widget when
    //   https://www.drupal.org/node/2685749 is committed.
    $element_info = $this->elementInfo
      ->getInfo('machine_name');
    $form['name'] = [
      '#type' => 'machine_name',
      '#default_value' => $this->entity
        ->id(),
      '#source_field' => 'title',
      '#process' => array_merge([
        [
          get_class($this),
          'processMachineNameSource',
        ],
      ], $element_info['#process']),
      '#machine_name' => [
        'exists' => '\\Drupal\\entityqueue\\Entity\\EntitySubqueue::load',
      ],
      '#disabled' => !$this->entity
        ->isNew(),
      '#weight' => -5,
      '#access' => !$this->entity
        ->getQueue()
        ->getHandlerPlugin()
        ->hasAutomatedSubqueues(),
    ];
    return $form;
  }

  /**
   * Form API callback: Sets the 'source' property of a machine_name element.
   *
   * This method is assigned as a #process callback in formElement() method.
   */
  public static function processMachineNameSource($element, FormStateInterface $form_state, $form) {
    $source_field_state = WidgetBase::getWidgetState($form['#parents'], $element['#source_field'], $form_state);

    // Hide the field widget if the source field is not configured properly or
    // if it doesn't exist in the form.
    if (empty($element['#source_field']) || empty($source_field_state['array_parents'])) {
      $element['#access'] = FALSE;
    }
    else {
      $source_field_element = NestedArray::getValue($form_state
        ->getCompleteForm(), $source_field_state['array_parents']);
      $element['#machine_name']['source'] = $source_field_element[0]['value']['#array_parents'];
    }
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  protected function actions(array $form, FormStateInterface $form_state) {
    $actions = parent::actions($form, $form_state);
    $actions['reverse'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Reverse'),
      '#submit' => [
        '::submitAction',
      ],
      '#op' => 'reverse',
      '#ajax' => [
        'callback' => '::subqueueActionAjaxForm',
        'wrapper' => $form_state
          ->get('subqueue_form_wrapper_id'),
      ],
    ];
    $actions['shuffle'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Shuffle'),
      '#submit' => [
        '::submitAction',
      ],
      '#op' => 'shuffle',
      '#ajax' => [
        'callback' => '::subqueueActionAjaxForm',
        'wrapper' => $form_state
          ->get('subqueue_form_wrapper_id'),
      ],
    ];
    $actions['clear'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Clear'),
      '#submit' => [
        '::submitAction',
      ],
      '#op' => 'clear',
      '#ajax' => [
        'callback' => '::subqueueActionAjaxForm',
        'wrapper' => $form_state
          ->get('subqueue_form_wrapper_id'),
      ],
    ];
    return $actions;
  }

  /**
   * Submit callback for the 'reverse', 'shuffle' and 'clear' actions.
   */
  public static function submitAction(array &$form, FormStateInterface $form_state) {
    $trigger = $form_state
      ->getTriggeringElement();
    $op = $trigger['#op'];

    // Check if we have a form element for the 'items' field.
    $path = array_merge($form['#parents'], [
      'items',
    ]);
    $key_exists = NULL;
    NestedArray::getValue($form_state
      ->getValues(), $path, $key_exists);
    if ($key_exists) {

      // Remove any user input for the 'items' element in order to allow the
      // values set below to be applied.
      $user_input = $form_state
        ->getUserInput();
      NestedArray::setValue($user_input, $path, NULL);
      $form_state
        ->setUserInput($user_input);
      $entity = $form_state
        ->getFormObject()
        ->getEntity();
      $items_widget = $form_state
        ->getFormObject()
        ->getFormDisplay($form_state)
        ->getRenderer('items');
      $subqueue_items = $entity
        ->get('items');
      $items_widget
        ->extractFormValues($subqueue_items, $form, $form_state);
      $items_values = $subqueue_items
        ->getValue();
      switch ($op) {
        case 'reverse':
          $subqueue_items
            ->setValue(array_reverse($items_values));
          break;
        case 'shuffle':
          shuffle($items_values);
          $subqueue_items
            ->setValue($items_values);
          break;
        case 'clear':

          // Set the items count to zero.
          $parents = NestedArray::getValue($form, $path)['widget']['#field_parents'];
          $field_state = WidgetBase::getWidgetState($parents, 'items', $form_state);
          $field_state['items_count'] = 0;
          WidgetBase::setWidgetState($parents, 'items', $form_state, $field_state);
          $subqueue_items
            ->setValue(NULL);
          break;
      }

      // Handle 'inline_entity_form' widgets separately because they have a
      // custom form state storage for the current state of the referenced
      // entities.
      if (\Drupal::moduleHandler()
        ->moduleExists('inline_entity_form') && $items_widget instanceof InlineEntityFormBase) {
        $items_form_element = NestedArray::getValue($form, $path);
        $ief_id = $items_form_element['widget']['#ief_id'];
        $entities = $form_state
          ->get([
          'inline_entity_form',
          $ief_id,
          'entities',
        ]);
        if (isset($entities)) {
          $form_state
            ->set([
            'inline_entity_form',
            $ief_id,
            'entities',
          ], []);
          switch ($op) {
            case 'reverse':
              $entities = array_reverse($entities);
              break;
            case 'shuffle':
              shuffle($entities);
              break;
            case 'clear':
              $entities = [];
              break;
          }
          foreach ($entities as $delta => $item) {
            $item['weight'] = $delta;
            $form_state
              ->set([
              'inline_entity_form',
              $ief_id,
              'entities',
              $delta,
            ], $item);
          }
        }
      }

      // Handle 'entity_browser' widgets separately because they have a custom
      // form state storage for the current state of the referenced entities.
      if (\Drupal::moduleHandler()
        ->moduleExists('entity_browser') && $items_widget instanceof EntityReferenceBrowserWidget) {
        $ids = array_column($subqueue_items
          ->getValue(), 'target_id');
        $widget_id = $subqueue_items
          ->getEntity()
          ->uuid() . ':' . $subqueue_items
          ->getFieldDefinition()
          ->getName();
        $form_state
          ->set([
          'entity_browser_widget',
          $widget_id,
        ], $ids);
      }
      $form_state
        ->getFormObject()
        ->setEntity($entity);
      $form_state
        ->setRebuild();
    }
  }

  /**
   * AJAX callback; Returns the entire form element.
   */
  public static function subqueueActionAjaxForm(array &$form, FormStateInterface $form_state) {
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $subqueue = $this->entity;
    $status = $subqueue
      ->save();
    $edit_link = $subqueue
      ->toLink($this
      ->t('Edit'), 'edit-form')
      ->toString();
    if ($status == SAVED_UPDATED) {
      $this
        ->messenger()
        ->addMessage($this
        ->t('The entity subqueue %label has been updated.', [
        '%label' => $subqueue
          ->label(),
      ]));
      $this
        ->logger('entityqueue')
        ->notice('The entity subqueue %label has been updated.', [
        '%label' => $subqueue
          ->label(),
        'link' => $edit_link,
      ]);
    }
    else {
      $this
        ->messenger()
        ->addMessage($this
        ->t('The entity subqueue %label has been added.', [
        '%label' => $subqueue
          ->label(),
      ]));
      $this
        ->logger('entityqueue')
        ->notice('The entity subqueue %label has been added.', [
        '%label' => $subqueue
          ->label(),
        'link' => $edit_link,
      ]);
    }
    $queue = $subqueue
      ->getQueue();
    if ($queue
      ->getHandlerPlugin()
      ->supportsMultipleSubqueues()) {
      $form_state
        ->setRedirectUrl($queue
        ->toUrl('subqueue-list'));
    }
    else {
      $form_state
        ->setRedirectUrl($queue
        ->toUrl('collection'));
    }
  }

}

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 3
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 3
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
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
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::$privateEntityManager private property The entity manager.
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 10
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
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 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
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::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
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
EntityForm::__get public function
EntityForm::__set public function
EntitySubqueueForm::$elementInfo protected property The element info manager.
EntitySubqueueForm::$entity protected property The entity being used by this form. Overrides ContentEntityForm::$entity
EntitySubqueueForm::actions protected function Returns an array of supported actions for the current entity form. Overrides EntityForm::actions
EntitySubqueueForm::create public static function Instantiates a new instance of this class. Overrides ContentEntityForm::create
EntitySubqueueForm::form public function Gets the actual form array to be built. Overrides ContentEntityForm::form
EntitySubqueueForm::processMachineNameSource public static function Form API callback: Sets the 'source' property of a machine_name element.
EntitySubqueueForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
EntitySubqueueForm::submitAction public static function Submit callback for the 'reverse', 'shuffle' and 'clear' actions.
EntitySubqueueForm::subqueueActionAjaxForm public static function AJAX callback; Returns the entire form element.
EntitySubqueueForm::__construct public function Constructs a EntitySubqueueForm. Overrides ContentEntityForm::__construct
FormBase::$configFactory protected property The config factory. 1
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. 1
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. Overrides UrlGeneratorTrait::redirect
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.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
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. 29
MessengerTrait::messenger public function Gets the messenger. 29
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. 1
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.