You are here

class SimplesitemapCustomLinksForm in Simple XML sitemap 8

SimplesitemapCustomLinksFrom

Hierarchy

Expanded class hierarchy of SimplesitemapCustomLinksForm

1 string reference to 'SimplesitemapCustomLinksForm'
simplesitemap.routing.yml in ./simplesitemap.routing.yml
simplesitemap.routing.yml

File

src/Form/SimplesitemapCustomLinksForm.php, line 17
Contains \Drupal\simplesitemap\Form\SimplesitemapCustomLinksForm.

Namespace

Drupal\simplesitemap\Form
View source
class SimplesitemapCustomLinksForm extends ConfigFormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormID() {
    return 'simplesitemap_custom_links_form';
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'simplesitemap.settings_custom',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $sitemap = new Simplesitemap();
    $setting_string = '';
    foreach ($sitemap
      ->get_config('custom') as $custom_link) {

      // todo: remove this statement after removing the index key from the configuration.
      if (isset($custom_link['index']) && $custom_link['index'] == 0) {
        continue;
      }
      $setting_string .= isset($custom_link['priority']) ? $custom_link['path'] . ' ' . $custom_link['priority'] : $custom_link['path'];
      $setting_string .= "\r\n";
    }
    $form['simplesitemap_custom'] = array(
      '#title' => t('Custom links'),
      '#type' => 'fieldset',
      '#markup' => '<p>' . t('Add custom internal drupal paths and their priorities to the XML sitemap.') . '</p>',
    );
    $form['simplesitemap_custom']['custom_links'] = array(
      '#type' => 'textarea',
      '#title' => t('Relative Drupal paths'),
      '#default_value' => $setting_string,
      '#description' => t("Please specify drupal internal (relative) paths, one per line. Do not forget to prepend the paths with a '/'. You can optionally add a priority (0.0 - 1.0) by appending it to the path after a space. The home page with the highest priority would be <em>/ 1</em>, the contact page with a medium priority would be <em>/contact 0.5</em>."),
    );
    $form['simplesitemap_custom']['simplesitemap_regenerate_now'] = array(
      '#type' => 'checkbox',
      '#title' => t('Regenerate sitemap after hitting Save'),
      '#description' => t('This setting will regenerate the whole sitemap including the above changes.<br/>Otherwise the sitemap will be rebuilt on next cron run.'),
      '#default_value' => FALSE,
    );
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $custom_links_string = str_replace("\r\n", "\n", $form_state
      ->getValue('custom_links'));
    $custom_links = array_filter(explode("\n", $custom_links_string), 'trim');
    foreach ($custom_links as $link_setting) {
      $settings = explode(' ', $link_setting, 2);
      if (!\Drupal::service('path.validator')
        ->isValid($settings[0])) {
        $form_state
          ->setErrorByName('', t("The path <em>{$settings[0]}</em> does not exist."));
      }
      if ($settings[0][0] != '/') {
        $form_state
          ->setErrorByName('', t("The path <em>{$settings[0]}</em> needs to start with an '/'."));
      }
      if (isset($settings[1])) {
        if (!is_numeric($settings[1]) || $settings[1] < 0 || $settings[1] > 1) {
          $form_state
            ->setErrorByName('', t("Priority setting on line <em>{$link_setting}</em> is incorrect. Set priority from 0.0 to 1.0."));
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $sitemap = new Simplesitemap();
    $custom_links_string = str_replace("\r\n", "\n", $form_state
      ->getValue('custom_links'));
    $custom_links_string_lines = array_filter(explode("\n", $custom_links_string), 'trim');
    $custom_link_config = array();
    foreach ($custom_links_string_lines as $line) {
      $line_settings = explode(' ', $line, 2);
      $custom_link_config[]['path'] = $line_settings[0];
      if (isset($line_settings[1])) {
        end($custom_link_config);
        $key = key($custom_link_config);
        $custom_link_config[$key]['priority'] = number_format((double) $line_settings[1], 1, '.', '');
      }
    }
    $sitemap
      ->save_config('custom', $custom_link_config);
    parent::submitForm($form, $form_state);

    // Regenerate sitemaps according to user setting.
    if ($form_state
      ->getValue('simplesitemap_regenerate_now')) {
      $sitemap
        ->generate_sitemap();
      drupal_set_message(t("The <a href='@url' target='_blank'>XML sitemap</a> has been regenerated for all languages.", array(
        '@url' => $GLOBALS['base_url'] . '/sitemap.xml',
      )));
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create 13
ConfigFormBase::__construct public function Constructs a \Drupal\system\ConfigFormBase object. 11
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
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::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
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.
SimplesitemapCustomLinksForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
SimplesitemapCustomLinksForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
SimplesitemapCustomLinksForm::getFormID public function
SimplesitemapCustomLinksForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
SimplesitemapCustomLinksForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
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.