You are here

class MetatagViewsEditForm in Metatag 8

Class MetatagViewsEditForm.

@package Drupal\metatag_views\Form

Hierarchy

Expanded class hierarchy of MetatagViewsEditForm

File

metatag_views/src/Form/MetatagViewsEditForm.php, line 17

Namespace

Drupal\metatag_views\Form
View source
class MetatagViewsEditForm extends FormBase {
  use MetatagViewsValuesCleanerTrait;

  /**
   * Drupal\metatag\MetatagManager definition.
   *
   * @var \Drupal\metatag\MetatagManager
   */
  protected $metatagManager;

  /**
   * The Views manager.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $viewsManager;

  /**
   * Array of display settings from ViewEntityInterface::getDisplay().
   *
   * @var array
   */
  protected $display;

  /**
   * View entity object.
   *
   * @var \Drupal\views\ViewEntityInterface
   */
  protected $view;

  /**
   * {@inheritdoc}
   */
  public function __construct(MetatagManagerInterface $metatag_manager, EntityTypeManagerInterface $entity_type_manager) {
    $this->metatagManager = $metatag_manager;
    $this->viewsManager = $entity_type_manager
      ->getStorage('view');
  }

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

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'metatag_views_edit_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    // Get the parameters from request.
    $view_id = $this
      ->getRequest()
      ->get('view_id');
    $display_id = $this
      ->getRequest()
      ->get('display_id');

    // Get meta tags from the view entity.
    $metatags = [];
    if ($view_id && $display_id) {
      $metatags = metatag_get_view_tags($view_id, $display_id);
    }
    $form['metatags'] = $this->metatagManager
      ->form($metatags, $form, [
      'view',
    ]);
    $form['metatags']['#title'] = $this
      ->t('Metatags');
    $form['metatags']['#type'] = 'fieldset';

    // Need to create that AFTER the $form['metatags'] as the whole form is
    // passed to the $metatagManager->form() which causes duplicated field.
    $form['view'] = [
      '#type' => 'value',
      '#title' => $this
        ->t('View'),
      '#weight' => -100,
      '#default_value' => $view_id . ':' . $display_id,
      '#required' => TRUE,
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Submit'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function form(array $values, array $element, array $token_types = [], array $included_groups = NULL, array $included_tags = NULL, $verbose_help = FALSE) {

    // Add the outer fieldset.
    $element += [
      '#type' => 'details',
    ];
    $element += $this->tokenService
      ->tokenBrowser($token_types, $verbose_help);
    $groups_and_tags = $this
      ->sortedGroupsWithTags();
    $first = TRUE;
    foreach ($groups_and_tags as $group_id => $group) {

      // Only act on groups that have tags and are in the list of included
      // groups (unless that list is null).
      if (isset($group['tags']) && (is_null($included_groups) || in_array($group_id, $included_groups))) {

        // Create the fieldset.
        $element[$group_id]['#type'] = 'details';
        $element[$group_id]['#title'] = $group['label'];
        $element[$group_id]['#description'] = $group['description'];
        $element[$group_id]['#open'] = $first;
        $first = FALSE;
        foreach ($group['tags'] as $tag_id => $tag) {

          // Only act on tags in the included tags list, unless that is null.
          if (is_null($included_tags) || in_array($tag_id, $included_tags)) {

            // Make an instance of the tag.
            $tag = $this->tagPluginManager
              ->createInstance($tag_id);

            // Set the value to the stored value, if any.
            $tag_value = isset($values[$tag_id]) ? $values[$tag_id] : NULL;
            $tag
              ->setValue($tag_value);

            // Create the bit of form for this tag.
            $element[$group_id][$tag_id] = $tag
              ->form($element);
          }
        }
      }
    }
    return $element;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Get the submitted form values.
    $view_name = $form_state
      ->getValue('view');
    list($view_id, $display_id) = explode(':', $view_name);
    $metatags = $form_state
      ->getValues();
    unset($metatags['view']);
    $metatags = $this
      ->clearMetatagViewsDisallowedValues($metatags);

    /** @var \Drupal\views\ViewEntityInterface $view */
    $view = $this->viewsManager
      ->load($view_id);

    // Store the meta tags on the view.
    $config_name = $view
      ->getConfigDependencyName();
    $config_path = 'display.' . $display_id . '.display_options.display_extenders.metatag_display_extender.metatags';

    // Set configuration values based on form submission. This always edits the
    // original language.
    $configuration = $this
      ->configFactory()
      ->getEditable($config_name);
    if (empty($this
      ->removeEmptyTags($metatags))) {
      $configuration
        ->clear($config_path);
    }
    else {
      $configuration
        ->set($config_path, $metatags);
    }
    $configuration
      ->save();

    // Redirect back to the views list.
    $form_state
      ->setRedirect('metatag_views.metatags.list');
    $this
      ->messenger()
      ->addMessage($this
      ->t('Metatags for @view : @display have been saved.', [
      '@view' => $view
        ->label(),
      '@display' => $view
        ->getDisplay($display_id)['display_title'],
    ]));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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
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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
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.
MetatagViewsEditForm::$display protected property Array of display settings from ViewEntityInterface::getDisplay().
MetatagViewsEditForm::$metatagManager protected property Drupal\metatag\MetatagManager definition.
MetatagViewsEditForm::$view protected property View entity object.
MetatagViewsEditForm::$viewsManager protected property The Views manager.
MetatagViewsEditForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 1
MetatagViewsEditForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
MetatagViewsEditForm::form public function
MetatagViewsEditForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 1
MetatagViewsEditForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
MetatagViewsEditForm::__construct public function
MetatagViewsValuesCleanerTrait::clearMetatagViewsDisallowedValues public function Clears the metatag form state values from illegal elements.
MetatagViewsValuesCleanerTrait::removeEmptyTags public function Removes tags that are empty.
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.