You are here

class TourTipForm in Tour UI 8

Form controller for the tour tip plugin edit forms.

Hierarchy

Expanded class hierarchy of TourTipForm

File

src/Form/TourTipForm.php, line 15

Namespace

Drupal\tour_ui\Form
View source
class TourTipForm extends FormBase {

  /**
   * The Tour tip plugin manager.
   *
   * @var \Drupal\Tour\TipPluginManager
   */
  protected $pluginManager;

  /**
   * The Messenger service.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface
   */
  protected $messenger;

  /**
   * Constructs a new TourTipForm object.
   *
   * @param \Drupal\Tour\TipPluginManager $plugin_manager
   *   The Tour tip plugin manager.
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The Messenger service.
   */
  public function __construct(TipPluginManager $plugin_manager, MessengerInterface $messenger) {
    $this->pluginManager = $plugin_manager;
    $this->messenger = $messenger;
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $storage = $form_state
      ->getStorage();
    $tip = $storage['#tip'];
    $form += $tip
      ->buildConfigurationForm($form, $form_state);

    // Retrieve and add the form actions array.
    $actions = $this
      ->actionsElement($form, $form_state);
    if (!empty($actions)) {
      $form['actions'] = $actions;
    }
    return $form;
  }

  /**
   * Returns the action form element for the current entity form.
   */
  protected function actionsElement(array $form, FormStateInterface $form_state) {
    $element = $this
      ->actions($form, $form_state);
    if (isset($element['delete'])) {

      // Move the delete action as last one, unless weights are explicitly
      // provided.
      $delete = $element['delete'];
      unset($element['delete']);
      $element['delete'] = $delete;
      $element['delete']['#button_type'] = 'danger';
    }
    if (isset($element['submit'])) {

      // Give the primary submit button a #button_type of primary.
      $element['submit']['#button_type'] = 'primary';
    }
    $count = 0;
    foreach (Element::children($element) as $action) {
      $element[$action] += [
        '#weight' => ++$count * 5,
      ];
    }
    if (!empty($element)) {
      $element['#type'] = 'actions';
    }
    return $element;
  }

  /**
   * Returns an array of supported actions for the current entity form.
   */
  protected function actions(array $form, FormStateInterface $form_state) {
    $actions['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save'),
      '#submit' => [
        '::submitForm',
      ],
    ];
    $actions['delete'] = [
      '#type' => 'link',
      '#title' => $this
        ->t('Delete'),
      '#attributes' => [
        'class' => [
          'button',
          'button--danger',
        ],
      ],
    ];
    return $actions;
  }

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

    // Determine if one of our tips already exist.
    $storage = $form_state
      ->getStorage();
    $tour = $storage['#tour'];
    $tips = $tour
      ->getTips();

    // If there are no initial tips then we don't need to check.
    if (empty($tips)) {
      return;
    }
    $tip_ids = array_map(function ($data) {
      return $data
        ->id();
    }, $tips);
    if (in_array($form_state
      ->getValue('id'), $tip_ids) && isset($storage['#new'])) {
      $form_state
        ->setError($form['label'], $this
        ->t('A tip with the same identifier exists.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $storage = $form_state
      ->getStorage();
    $tour = $storage['#tour'];
    $tip = $storage['#tip'];

    // Get available fields from current tip plugin.
    $configuration = $tip
      ->getConfiguration();

    // Build a new tip.
    $new_tip = $tip
      ->getConfiguration();
    foreach ($configuration as $name => $configuration_value) {
      $value = $form_state
        ->getValue($name);
      $new_tip[$name] = is_array($value) ? array_filter($value) : $value;
    }

    // Rebuild the tips.
    $new_tip_list = $tour
      ->getTips();
    $new_tips = [];
    if (!empty($new_tip_list)) {
      foreach ($new_tip_list as $tip) {
        $new_tips[$tip
          ->id()] = $tip
          ->getConfiguration();
      }
    }

    // We have to cleanup the attributes as these are selection dependent.
    // @see \Drupal\tour_ui\Plugin\tour_ui\tip\TipPluginTextExtended::buildConfigurationForm
    $input = $form_state
      ->getUserInput();
    $selected = $input['attributes']['selector_type'];
    $attributes =& $new_tip['attributes'];
    if ($selected !== 'data-id') {
      unset($attributes['data-id']);
    }
    if ($selected !== 'data-class') {
      unset($attributes['data-class']);
    }
    if (!is_array($new_tip['attributes'])) {
      $new_tip['attributes'] = [];
    }

    // Add our tip and save.
    $new_tips[$new_tip['id']] = $new_tip;
    $tour
      ->set('tips', $new_tips);
    $tour
      ->save();
    if (isset($storage['#new'])) {
      $this->messenger
        ->addMessage($this
        ->t('The %tip tip has been created.', [
        '%tip' => $new_tip['label'],
      ]));
    }
    else {
      $this->messenger
        ->addMessage($this
        ->t('Updated the %tip tip.', [
        '%tip' => $new_tip['label'],
      ]));
    }
    $form_state
      ->setRedirect('entity.tour.edit_form', [
      'tour' => $tour
        ->id(),
    ]);
    return $tour;
  }

}

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.
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 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.
TourTipForm::$messenger protected property The Messenger service. Overrides MessengerTrait::$messenger
TourTipForm::$pluginManager protected property The Tour tip plugin manager.
TourTipForm::actions protected function Returns an array of supported actions for the current entity form.
TourTipForm::actionsElement protected function Returns the action form element for the current entity form.
TourTipForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
TourTipForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
TourTipForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
TourTipForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
TourTipForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
TourTipForm::__construct public function Constructs a new TourTipForm object.
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.