You are here

abstract class TamperFormBase in Feeds Tamper 8.2

The base class for add/edit tamper forms.

@package Drupal\feeds_tamper\Form

Hierarchy

Expanded class hierarchy of TamperFormBase

File

src/Form/TamperFormBase.php, line 17

Namespace

Drupal\feeds_tamper\Form
View source
abstract class TamperFormBase extends FormBase {
  use TamperFormTrait;

  // Form fields.
  const VAR_TAMPER_ID = 'tamper_id';
  const VAR_TAMPER_LABEL = 'label';
  const VAR_PLUGIN_CONFIGURATION = 'plugin_configuration';
  const VAR_WEIGHT = 'weight';

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {

    /** @var self $form */
    $form = parent::create($container);
    $form
      ->setTamperManager($container
      ->get('plugin.manager.tamper'));
    $form
      ->setTamperMetaManager($container
      ->get('feeds_tamper.feed_type_tamper_manager'));
    return $form;
  }

  /**
   * Page title callback.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route match.
   *
   * @return \Drupal\Core\StringTranslation\TranslatableMarkup|null
   *   Translated string to use as the title.
   */
  public function tamperTitle(RouteMatchInterface $route_match) {

    /** @var \Drupal\feeds\Entity\FeedType $feed_type */
    $feed_type = $route_match
      ->getParameter('feeds_feed_type');
    $source_field = $route_match
      ->getParameter('source_field');
    $tamper_uuid = $route_match
      ->getParameter('tamper_uuid');
    if ($source_field) {
      return $this
        ->t('Add a tamper plugin to @label : @source', [
        '@label' => $feed_type
          ->label(),
        '@source' => $source_field,
      ]);
    }
    elseif ($tamper_uuid) {
      $tamper_meta = $this->feedTypeTamperManager
        ->getTamperMeta($feed_type);
      $tamper = $tamper_meta
        ->getTamper($tamper_uuid);
      return $this
        ->t('Edit @label', [
        '@label' => $tamper
          ->getPluginDefinition()['label'],
      ]);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form[self::VAR_TAMPER_ID] = [
      '#type' => 'select',
      '#title' => $this
        ->t('The plugin to add'),
      '#options' => $this
        ->getPluginOptions(),
      '#required' => TRUE,
      '#default_value' => $this->plugin ? $this->plugin
        ->getPluginDefinition()['id'] : NULL,
      '#ajax' => [
        'callback' => '::getPluginForm',
        'wrapper' => 'plugin-config',
      ],
    ];
    $form[self::VAR_PLUGIN_CONFIGURATION] = [
      '#type' => 'container',
      '#tree' => TRUE,
      '#attributes' => [
        'id' => [
          'plugin-config',
        ],
      ],
    ];
    if ($this->plugin) {
      $form[self::VAR_PLUGIN_CONFIGURATION][self::VAR_TAMPER_LABEL] = [
        '#type' => 'textfield',
        '#title' => $this
          ->t('Label'),
        '#maxlength' => '255',
        '#description' => $this
          ->t('A useful description of what this plugin is doing.'),
        '#required' => TRUE,
        '#default_value' => $this->plugin
          ->getSetting(self::VAR_TAMPER_LABEL) ? $this->plugin
          ->getSetting(self::VAR_TAMPER_LABEL) : $this->plugin
          ->getPluginDefinition()['label'],
      ];
      $form[self::VAR_PLUGIN_CONFIGURATION]['description'] = [
        '#markup' => $this->plugin
          ->getPluginDefinition()['description'],
      ];
      $subform_state = SubformState::createForSubform($form[self::VAR_PLUGIN_CONFIGURATION], $form, $form_state);
      $form[self::VAR_PLUGIN_CONFIGURATION] = $this->plugin
        ->buildConfigurationForm($form[self::VAR_PLUGIN_CONFIGURATION], $subform_state);
    }
    $form[self::VAR_WEIGHT] = [
      '#type' => 'hidden',
      '#value' => $this
        ->getWeight(),
    ];
    $cancel_url = Url::fromRoute('entity.feeds_feed_type.tamper', [
      'feeds_feed_type' => $this->feedsFeedType
        ->id(),
    ]);
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Submit'),
      '#button_type' => 'primary',
    ];
    $form['actions']['cancel'] = [
      '#type' => 'link',
      '#title' => $this
        ->t('Cancel'),
      '#attributes' => [
        'class' => [
          'button',
        ],
      ],
      '#url' => $cancel_url,
    ];
    return $form;
  }

  /**
   * Ajax callback.
   *
   * Returns the plugin configuration form from an ajax request.
   *
   * @param array $form
   *   Drupal form array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form state interface.
   *
   * @return array
   *   Plugin form.
   */
  public function getPluginForm(array $form, FormStateInterface $form_state) {

    // Update label when selecting an other plugin.
    if (!$this->plugin || !$this->plugin
      ->getSetting(self::VAR_TAMPER_LABEL)) {
      $form[self::VAR_PLUGIN_CONFIGURATION][self::VAR_TAMPER_LABEL]['#value'] = $form[self::VAR_PLUGIN_CONFIGURATION][self::VAR_TAMPER_LABEL]['#default_value'];
    }
    return $form[self::VAR_PLUGIN_CONFIGURATION];
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    if (!empty($this->plugin)) {
      $subform_state = SubformState::createForSubform($form[self::VAR_PLUGIN_CONFIGURATION], $form, $form_state);
      $this->plugin
        ->validateConfigurationForm($form[self::VAR_PLUGIN_CONFIGURATION], $subform_state);
    }
  }

  /**
   * Get the tamper plugin options.
   *
   * @return array
   *   List of tamper plugin groups, keyed by group, where the value is another
   *   array of plugin labels keyed by plugin id.
   */
  protected function getPluginOptions() {

    // @todo Move this logic to the tamper manager interface?
    $plugin_options = array_map(function ($grouped_plugins) {
      $group_options = [];
      foreach ($grouped_plugins as $id => $plugin_definition) {
        $group_options[$id] = $plugin_definition['label'];
      }
      return $group_options;
    }, $this->tamperManager
      ->getGroupedDefinitions());
    return $plugin_options;
  }

  /**
   * Prepares a configuration array.
   *
   * @param string $source
   *   The source.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   *
   * @return array
   *   The configuration array.
   */
  protected function prepareConfig($source, FormStateInterface $form_state) {
    $config = [
      'plugin' => $this->plugin
        ->getPluginId(),
      'source' => $source,
      'weight' => $form_state
        ->getValue(self::VAR_WEIGHT),
      'label' => $form_state
        ->getValue([
        self::VAR_PLUGIN_CONFIGURATION,
        self::VAR_TAMPER_LABEL,
      ]),
    ];
    $plugin_config = $form_state
      ->getValue(self::VAR_PLUGIN_CONFIGURATION);
    if ($plugin_config) {
      $config += $plugin_config;
    }
    return $config;
  }

  /**
   * Gets the weight to use for the plugin.
   *
   * @return int
   *   The plugin's weight.
   */
  protected function getWeight() {
    $request = $this
      ->getRequest();
    if ($request->query
      ->has(self::VAR_WEIGHT)) {
      return (int) $request->query
        ->get(self::VAR_WEIGHT);
    }
    if ($this->plugin) {
      return (int) $this->plugin
        ->getSetting(self::VAR_WEIGHT);
    }
    return 0;
  }

}

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.
FormInterface::getFormId public function Returns a unique string identifying the form. 236
FormInterface::submitForm public function Form submission handler. 192
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.
TamperFormBase::buildForm public function Form constructor. Overrides FormInterface::buildForm 2
TamperFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create
TamperFormBase::getPluginForm public function Ajax callback.
TamperFormBase::getPluginOptions protected function Get the tamper plugin options.
TamperFormBase::getWeight protected function Gets the weight to use for the plugin.
TamperFormBase::prepareConfig protected function Prepares a configuration array.
TamperFormBase::tamperTitle public function Page title callback.
TamperFormBase::validateForm public function Form validation handler. Overrides FormBase::validateForm
TamperFormBase::VAR_PLUGIN_CONFIGURATION constant
TamperFormBase::VAR_TAMPER_ID constant
TamperFormBase::VAR_TAMPER_LABEL constant
TamperFormBase::VAR_WEIGHT constant
TamperFormTrait::$feedsFeedType protected property The feed item we are adding a tamper plugin to.
TamperFormTrait::$feedTypeTamperManager protected property The feeds tamper metadata manager.
TamperFormTrait::$plugin protected property The tamper plugin instance.
TamperFormTrait::$tamperManager protected property The tamper plugin manager.
TamperFormTrait::assertTamper protected function Makes sure that the tamper exists.
TamperFormTrait::checkAccess public function Checks access for the form page.
TamperFormTrait::setTamperManager public function Sets the tamper manager.
TamperFormTrait::setTamperMetaManager public function Sets the feed type tamper manager.
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.