You are here

class FormsStepsController in Forms Steps 8

Class FormsStepsController.

@package Drupal\forms_steps\Controller

Hierarchy

Expanded class hierarchy of FormsStepsController

File

src/Controller/FormsStepsController.php, line 19

Namespace

Drupal\forms_steps\Controller
View source
class FormsStepsController extends ControllerBase {

  /**
   * Display the step form.
   *
   * @param int $forms_steps
   *   Forms Steps id to display step from.
   * @param mixed $step
   *   Step to display.
   * @param null|int $instance_id
   *   Instance id of the forms steps ref to load.
   *
   * @return mixed
   *   Form that match the input parameters.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\forms_steps\Exception\AccessDeniedException
   * @throws \Drupal\forms_steps\Exception\FormsStepsNotFoundException
   */
  public function step($forms_steps, $step, $instance_id = NULL) {
    return self::getForm($forms_steps, $step, $instance_id);
  }

  /**
   * Get a form based on the $step and $nid.
   *
   * If $nid is empty or not existing we provide a create form, we edit
   * otherwise.
   *
   * TODO: De we need to move it in a service?
   *
   * @param int $forms_steps
   *   Forms Steps id to get the form from.
   * @param mixed $step
   *   Step to get the Form from.
   * @param null|int $instance_id
   *   Instance ID of the forms steps reference to load.
   *
   * @return \Drupal\Core\Render\Element\Form
   *   Returns the Form.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\forms_steps\Exception\AccessDeniedException
   * @throws \Drupal\forms_steps\Exception\FormsStepsNotFoundException
   * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
   */
  public static function getForm($forms_steps, $step, $instance_id = NULL) {

    /** @var \Drupal\forms_steps\Entity\FormsSteps $formsSteps */
    $formsSteps = \Drupal::entityTypeManager()
      ->getStorage('forms_steps')
      ->load($forms_steps);
    if (!$formsSteps
      ->hasStep($step)) {

      // TODO: Propose a better error management.
      throw new \InvalidArgumentException("The Step '{$step}' does not exist in forms steps '{$forms_steps}'");
    }
    $step = $formsSteps
      ->getStep($step);
    $entity_key_type = \Drupal::entityTypeManager()
      ->getDefinition($step
      ->entityType())
      ->getKey('bundle');

    // We initialize the entity with its potential last revision.
    $entity = NULL;
    $entities = [];
    if (!is_null($instance_id)) {
      try {
        $entities = \Drupal::entityTypeManager()
          ->getStorage(Workflow::ENTITY_TYPE)
          ->loadByProperties([
          'instance_id' => $instance_id,
        ]);
      } catch (\Exception $ex) {
      }
      if ($entities) {

        // We look for the same entity bundle.
        foreach ($entities as $_entity) {
          if (strcmp($_entity->entity_type->value, $step
            ->entityType()) == 0 && strcmp($_entity->bundle->value, $step
            ->entityBundle()) == 0) {

            // We load the entity.
            $storage = \Drupal::entityTypeManager()
              ->getStorage($_entity->entity_type->value);
            $idKey = $storage
              ->getEntityType()
              ->getKey('id');
            if ($storage
              ->getEntityType()
              ->isRevisionable() == FALSE) {
              $revision = NULL;
            }
            else {
              $revision = $storage
                ->getQuery()
                ->condition($idKey, $_entity->entity_id->value)
                ->latestRevision()
                ->execute();
            }
            if ($revision) {
              $rid = key($revision);
              $entity = $storage
                ->loadRevision($rid);
            }
            else {
              $entity = $storage
                ->load($_entity->entity_id->value);
            }
            break;
          }
        }
      }
    }
    $userRegistrationAccess = FALSE;
    if ($step
      ->entityType() == 'user') {
      $account = User::load(\Drupal::currentUser()
        ->id());

      /** @var  \Drupal\Core\Access\AccessResultInterface $registrationAccess */
      $registrationAccess = \Drupal::service('access_check.user.register')
        ->access($account);
      $userRegistrationAccess = $registrationAccess
        ->isAllowed();
    }

    // If entity not found, this is a new entity to create.
    if (is_null($entity)) {
      $entity = \Drupal::entityTypeManager()
        ->getStorage($step
        ->entityType())
        ->create([
        $entity_key_type => $step
          ->entityBundle(),
      ]);
      if ($entity) {
        if (!empty($instance_id)) {
          if (count($entities) == 0) {

            // No Forms Steps exists with that UUID - Error.
            throw new FormsStepsNotFoundException(t('No multi-step instance found.'));
          }
        }
        else {
          if ($step
            ->entityType() !== 'user' && !$entity
            ->access('create') || $step
            ->entityType() === 'user' && !($userRegistrationAccess || $entity
            ->access('create'))) {
            throw new AccessDeniedHttpException();
          }
          else {
            if ($formsSteps
              ->getFirstStep()
              ->id() != $step
              ->id()) {
              throw new AccessDeniedException(t('First step of the multi-step forms is required.'));
            }
          }
        }
      }
    }
    else {
      if ($step
        ->entityType() !== 'user' && !$entity
        ->access('update') || $step
        ->entityType() === 'user' && !$entity
        ->access('update')) {
        throw new AccessDeniedException(t('First step of the multi-step forms is required.'));
      }
    }
    $formMode = preg_replace("/^{$step->entityType()}\\./", '', $step
      ->formMode());
    try {

      // We load the form.
      $form = \Drupal::service('entity.form_builder')
        ->getForm($entity, $formMode, [
        'form_steps' => TRUE,
      ]);
    } catch (InvalidPluginDefinitionException $e) {
      $entityTypeId = $entity
        ->getEntityTypeId();
      $formModeOptions = \Drupal::service('entity_display.repository')
        ->getFormModeOptions($entityTypeId);
      if (isset($formModeOptions[$formMode])) {
        \Drupal::messenger()
          ->addError("Site's cache must be cleared after adding new form mode:" . $formMode . " on " . $entityTypeId);
      }
      else {
        \Drupal::messenger()
          ->addWarning($e
          ->getMessage() . 'The form class could not be loaded.');
      }
      throw new NotFoundHttpException();
    }

    // Hiding the button following to the configuration.
    if ($step
      ->hideDelete()) {
      unset($form['actions']['delete']);
    }
    elseif ($step
      ->deleteLabel()) {
      $form['actions']['delete']['#title'] = t($step
        ->deleteLabel());
    }

    // Return the form.
    return $form;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 40
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
FormsStepsController::getForm public static function Get a form based on the $step and $nid.
FormsStepsController::step public function Display the step form.
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.