You are here

class YamlFormTemplatesController in YAML Form 8

Provides route responses for form templates.

Hierarchy

Expanded class hierarchy of YamlFormTemplatesController

File

modules/yamlform_templates/src/Controller/YamlFormTemplatesController.php, line 21

Namespace

Drupal\yamlform_templates\Controller
View source
class YamlFormTemplatesController extends ControllerBase implements ContainerInjectionInterface {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * The form builder.
   *
   * @var \Drupal\Core\Form\FormBuilderInterface
   */
  protected $formBuilder;

  /**
   * Form storage.
   *
   * @var \Drupal\Core\Config\Entity\ConfigEntityStorageInterface
   */
  protected $yamlformStorage;

  /**
   * Constructs a YamlFormTemplatesController object.
   *
   * @param \Drupal\Core\Session\AccountInterface $current_user
   *   Current user.
   * @param \Drupal\Core\Form\FormBuilderInterface $form_builder
   *   The form builder.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity manager.
   */
  public function __construct(AccountInterface $current_user, FormBuilderInterface $form_builder, EntityTypeManagerInterface $entity_type_manager) {
    $this->currentUser = $current_user;
    $this->formBuilder = $form_builder;
    $this->yamlformStorage = $entity_type_manager
      ->getStorage('yamlform');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('current_user'), $container
      ->get('form_builder'), $container
      ->get('entity_type.manager'));
  }

  /**
   * Returns the form templates index page.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   *
   * @return array|RedirectResponse
   *   A render array representing the form templates index page or redirect
   *   response to a selected form via the filter's autocomplete.
   */
  public function index(Request $request) {
    $keys = $request
      ->get('search');

    // Handler autocomplete redirect.
    if ($keys && preg_match('#\\(([^)]+)\\)$#', $keys, $match)) {
      if ($yamlform = $this->yamlformStorage
        ->load($match[1])) {
        return new RedirectResponse($yamlform
          ->toUrl()
          ->setAbsolute(TRUE)
          ->toString());
      }
    }
    $header = [
      $this
        ->t('Title'),
      [
        'data' => $this
          ->t('Description'),
        'class' => [
          RESPONSIVE_PRIORITY_LOW,
        ],
      ],
      [
        'data' => $this
          ->t('Operations'),
        'colspan' => 2,
      ],
    ];
    $yamlforms = $this
      ->getTemplates($keys);
    $rows = [];
    foreach ($yamlforms as $yamlform) {
      $route_parameters = [
        'yamlform' => $yamlform
          ->id(),
      ];
      $row['title'] = $yamlform
        ->toLink();
      $row['description']['data']['description']['#markup'] = $yamlform
        ->get('description');
      if ($this->currentUser
        ->hasPermission('create yamlform')) {
        $row['select']['data'] = [
          '#type' => 'operations',
          '#links' => [
            'duplicate' => [
              'title' => $this
                ->t('Select'),
              'url' => Url::fromRoute('entity.yamlform.duplicate_form', $route_parameters),
              'attributes' => YamlFormDialogHelper::getModalDialogAttributes(640),
            ],
          ],
        ];
      }
      $row['preview']['data'] = [
        '#type' => 'operations',
        '#links' => [
          'preview' => [
            'title' => $this
              ->t('Preview'),
            'url' => Url::fromRoute('entity.yamlform.preview', $route_parameters),
            'attributes' => YamlFormDialogHelper::getModalDialogAttributes(800),
          ],
        ],
      ];
      $rows[] = $row;
    }
    $build = [];
    $build['filter_form'] = $this->formBuilder
      ->getForm('\\Drupal\\yamlform_templates\\Form\\YamlFormTemplatesFilterForm', $keys);
    $build['table'] = [
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#empty' => $this
        ->t('There are no templates available.'),
      '#cache' => [
        'contexts' => $this->yamlformStorage
          ->getEntityType()
          ->getListCacheContexts(),
        'tags' => $this->yamlformStorage
          ->getEntityType()
          ->getListCacheTags(),
      ],
    ];

    // Must preload libraries required by (modal) dialogs.
    $build['#attached']['library'][] = 'yamlform/yamlform.admin.dialog';
    return $build;
  }

  /**
   * Returns a form to add a new submission to a form.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   * @param \Drupal\yamlform\YamlFormInterface $yamlform
   *   The form this submission will be added to.
   *
   * @return array|NotFoundHttpException
   *   The form submission form.
   */
  public function previewForm(Request $request, YamlFormInterface $yamlform) {
    if (!$yamlform
      ->isTemplate()) {
      return new NotFoundHttpException();
    }
    return $yamlform
      ->getSubmissionForm([], 'preview');
  }

  /**
   * Get form templates.
   *
   * @param string $keys
   *   (optional) Filter templates by key word.
   *
   * @return array|\Drupal\Core\Entity\EntityInterface[]
   *   An array form entity that are used as templates.
   */
  protected function getTemplates($keys = '') {
    $query = $this->yamlformStorage
      ->getQuery();
    $query
      ->condition('template', TRUE);

    // Filter by key(word).
    if ($keys) {
      $or = $query
        ->orConditionGroup()
        ->condition('title', $keys, 'CONTAINS')
        ->condition('description', $keys, 'CONTAINS')
        ->condition('elements', $keys, 'CONTAINS');
      $query
        ->condition($or);
    }
    $query
      ->sort('title');
    $entity_ids = $query
      ->execute();
    if (empty($entity_ids)) {
      return [];
    }

    /* @var $entities \Drupal\yamlform\YamlFormInterface[] */
    $entities = $this->yamlformStorage
      ->loadMultiple($entity_ids);

    // If the user is not a form admin, check view access to each form.
    if (!$this
      ->isAdmin()) {
      foreach ($entities as $entity_id => $entity) {
        if (!$entity
          ->access('view')) {
          unset($entities[$entity_id]);
        }
      }
    }
    return $entities;
  }

  /**
   * Route preview title callback.
   *
   * @param \Drupal\yamlform\YamlFormInterface|null $yamlform
   *   A form.
   *
   * @return string
   *   The form label.
   */
  public function previewTitle(YamlFormInterface $yamlform = NULL) {
    return $this
      ->t('Previewing @title template', [
      '@title' => $yamlform
        ->label(),
    ]);
  }

  /**
   * Is the current user a form administrator.
   *
   * @return bool
   *   TRUE if the current user has 'administer yamlform' or 'edit any yamlform'
   *   permission.
   */
  protected function isAdmin() {
    return $this->currentUser
      ->hasPermission('administer yamlform') || $this->currentUser
      ->hasPermission('edit any yamlform');
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
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::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.
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.
YamlFormTemplatesController::$currentUser protected property The current user. Overrides ControllerBase::$currentUser
YamlFormTemplatesController::$formBuilder protected property The form builder. Overrides ControllerBase::$formBuilder
YamlFormTemplatesController::$yamlformStorage protected property Form storage.
YamlFormTemplatesController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
YamlFormTemplatesController::getTemplates protected function Get form templates.
YamlFormTemplatesController::index public function Returns the form templates index page.
YamlFormTemplatesController::isAdmin protected function Is the current user a form administrator.
YamlFormTemplatesController::previewForm public function Returns a form to add a new submission to a form.
YamlFormTemplatesController::previewTitle public function Route preview title callback.
YamlFormTemplatesController::__construct public function Constructs a YamlFormTemplatesController object.