You are here

class WebformTemplatesController in Webform 6.x

Same name and namespace in other branches
  1. 8.5 modules/webform_templates/src/Controller/WebformTemplatesController.php \Drupal\webform_templates\Controller\WebformTemplatesController

Provides route responses for webform templates.

Hierarchy

Expanded class hierarchy of WebformTemplatesController

File

modules/webform_templates/src/Controller/WebformTemplatesController.php, line 19

Namespace

Drupal\webform_templates\Controller
View source
class WebformTemplatesController extends ControllerBase implements ContainerInjectionInterface {
  use WebformEntityStorageTrait;

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

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

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $instance = parent::create($container);
    $instance->currentUser = $container
      ->get('current_user');
    $instance->formBuilder = $container
      ->get('form_builder');
    $instance->entityTypeManager = $container
      ->get('entity_type.manager');
    return $instance;
  }

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

    // Handler autocomplete redirect.
    if ($keys && preg_match('#\\(([^)]+)\\)$#', $keys, $match)) {
      if ($webform = $this
        ->getWebformStorage()
        ->load($match[1])) {
        return new RedirectResponse($webform
          ->toUrl()
          ->setAbsolute(TRUE)
          ->toString());
      }
    }
    $header = [];
    $header['title'] = $this
      ->t('Title');
    $header['description'] = [
      'data' => $this
        ->t('Description'),
      'class' => [
        RESPONSIVE_PRIORITY_LOW,
      ],
    ];
    $header['category'] = [
      'data' => $this
        ->t('Category'),
      'class' => [
        RESPONSIVE_PRIORITY_LOW,
      ],
    ];
    if ($manage) {
      $header['owner'] = [
        'data' => $this
          ->t('Author'),
        'class' => [
          RESPONSIVE_PRIORITY_LOW,
        ],
      ];
    }
    $header['operations'] = [
      'data' => $this
        ->t('Operations'),
    ];
    $webforms = $this
      ->getTemplates($keys, $category);
    $rows = [];
    foreach ($webforms as $webform) {
      $route_parameters = [
        'webform' => $webform
          ->id(),
      ];
      $row['title'] = $webform
        ->toLink();
      $row['description']['data']['#markup'] = $webform
        ->get('description');
      $row['category']['data']['#markup'] = $webform
        ->get('category');
      if ($manage) {
        $row['owner'] = ($owner = $webform
          ->getOwner()) ? $owner
          ->toLink() : '';
        $operations = [];
        if ($webform
          ->access('update')) {
          $operations['edit'] = [
            'title' => $this
              ->t('Build'),
            'url' => $this
              ->ensureDestination($webform
              ->toUrl('edit-form')),
          ];
        }
        if ($webform
          ->access('submission_page')) {
          $operations['view'] = [
            'title' => $this
              ->t('View'),
            'url' => $webform
              ->toUrl('canonical'),
          ];
        }
        if ($webform
          ->access('update')) {
          $operations['settings'] = [
            'title' => $this
              ->t('Settings'),
            'url' => $webform
              ->toUrl('settings'),
          ];
        }
        if ($webform
          ->access('duplicate')) {
          $operations['duplicate'] = [
            'title' => $this
              ->t('Duplicate'),
            'url' => $webform
              ->toUrl('duplicate-form', [
              'query' => [
                'template' => 1,
              ],
            ]),
            'attributes' => WebformDialogHelper::getModalDialogAttributes(WebformDialogHelper::DIALOG_NARROW),
          ];
        }
        if ($webform
          ->access('delete') && $webform
          ->hasLinkTemplate('delete-form')) {
          $operations['delete'] = [
            'title' => $this
              ->t('Delete'),
            'url' => $this
              ->ensureDestination($webform
              ->toUrl('delete-form')),
            'attributes' => WebformDialogHelper::getModalDialogAttributes(WebformDialogHelper::DIALOG_NARROW),
          ];
        }
        $row['operations']['data'] = [
          '#type' => 'operations',
          '#links' => $operations,
          '#prefix' => '<div class="webform-dropbutton">',
          '#suffix' => '</div>',
        ];
      }
      else {
        $row['operations']['data']['select'] = [
          '#type' => 'link',
          '#title' => $this
            ->t('Select'),
          '#url' => Url::fromRoute('entity.webform.duplicate_form', $route_parameters),
          '#attributes' => WebformDialogHelper::getModalDialogAttributes(WebformDialogHelper::DIALOG_NARROW, [
            'button',
            'button--primary',
          ]),
        ];
        $row['operations']['data']['preview'] = [
          '#type' => 'link',
          '#title' => $this
            ->t('Preview'),
          '#url' => Url::fromRoute('entity.webform.preview', $route_parameters),
          '#attributes' => WebformDialogHelper::getModalDialogAttributes(WebformDialogHelper::DIALOG_NORMAL, [
            'button',
          ]),
        ];
      }
      $rows[] = $row;
    }
    $build = [];
    $build['filter_form'] = $this->formBuilder
      ->getForm('\\Drupal\\webform_templates\\Form\\WebformTemplatesFilterForm', $keys);

    // Display info.
    if ($total = count($rows)) {
      $build['info'] = [
        '#markup' => $this
          ->formatPlural($total, '@count template', '@count templates'),
        '#prefix' => '<div>',
        '#suffix' => '</div>',
      ];
    }
    $build['table'] = [
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#sticky' => TRUE,
      '#empty' => $this
        ->t('There are no templates available.'),
      '#cache' => [
        'contexts' => $this
          ->getWebformStorage()
          ->getEntityType()
          ->getListCacheContexts(),
        'tags' => $this
          ->getWebformStorage()
          ->getEntityType()
          ->getListCacheTags(),
      ],
    ];

    // Must preload libraries required by (modal) dialogs.
    WebformDialogHelper::attachLibraries($build);
    return $build;
  }

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

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

    // Filter by key(word).
    if ($keys) {
      $or = $query
        ->orConditionGroup()
        ->condition('title', $keys, 'CONTAINS')
        ->condition('description', $keys, 'CONTAINS')
        ->condition('category', $keys, 'CONTAINS')
        ->condition('elements', $keys, 'CONTAINS');
      $query
        ->condition($or);
    }

    // Filter by category.
    if ($category) {
      $query
        ->condition('category', $category);
    }
    $query
      ->sort('title');
    $entity_ids = $query
      ->execute();
    if (empty($entity_ids)) {
      return [];
    }

    /* @var $entities \Drupal\webform\WebformInterface[] */
    $entities = $this
      ->getWebformStorage()
      ->loadMultiple($entity_ids);

    // If the user is not a webform admin, check view access to each webform.
    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\webform\WebformInterface|null $webform
   *   A webform.
   *
   * @return string
   *   The webform label.
   */
  public function previewTitle(WebformInterface $webform = NULL) {
    return $this
      ->t('Previewing @title template', [
      '@title' => $webform
        ->label(),
    ]);
  }

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

  /**
   * Ensures that a destination is present on the given URL.
   *
   * @param \Drupal\Core\Url $url
   *   The URL object to which the destination should be added.
   *
   * @return \Drupal\Core\Url
   *   The updated URL object.
   */
  protected function ensureDestination(Url $url) {
    return $url
      ->mergeOptions([
      'query' => $this
        ->getRedirectDestination()
        ->getAsArray(),
    ]);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$entityFormBuilder protected property The entity form builder.
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::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.
ControllerBase::state protected function Returns the state storage 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. 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.
WebformEntityStorageTrait::$entityStorageToTypeMappings protected property An associate array of entity type storage aliases.
WebformEntityStorageTrait::$entityTypeManager protected property The entity type manager. 5
WebformEntityStorageTrait::getEntityStorage protected function Retrieves the entity storage.
WebformEntityStorageTrait::getSubmissionStorage protected function Retrieves the webform submission storage.
WebformEntityStorageTrait::getWebformStorage protected function Retrieves the webform storage.
WebformEntityStorageTrait::__get public function Implements the magic __get() method.
WebformTemplatesController::$currentUser protected property The current user. Overrides ControllerBase::$currentUser
WebformTemplatesController::$formBuilder protected property The form builder. Overrides ControllerBase::$formBuilder
WebformTemplatesController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
WebformTemplatesController::ensureDestination protected function Ensures that a destination is present on the given URL.
WebformTemplatesController::getTemplates protected function Get webform templates.
WebformTemplatesController::index public function Returns the webform templates index page.
WebformTemplatesController::isAdmin protected function Is the current user a webform administrator.
WebformTemplatesController::previewForm public function Returns a webform to add a new submission to a webform.
WebformTemplatesController::previewTitle public function Route preview title callback.