You are here

class RedirectImportForm in Path redirect import 8

Class RedirectImportForm.

@package Drupal\path_redirect_import\Form

Hierarchy

Expanded class hierarchy of RedirectImportForm

1 string reference to 'RedirectImportForm'
path_redirect_import.routing.yml in ./path_redirect_import.routing.yml
path_redirect_import.routing.yml

File

src/Form/RedirectImportForm.php, line 17

Namespace

Drupal\path_redirect_import\Form
View source
class RedirectImportForm extends FormBase {

  /**
   * Uploaded file entity.
   *
   * @var \Drupal\file\Entity\File
   */
  protected $file;

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['csv'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Import from .csv or .txt file'),
    ];
    $form['csv']['delimiter'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Delimiter'),
      '#description' => $this
        ->t('Add your delimiter (e.g., comma, pipe)'),
      '#maxlength' => 2,
      '#size' => 4,
      '#default_value' => ',',
    ];
    $form['csv']['no_headers'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('No headers'),
      '#description' => $this
        ->t('If your imported file does not include a header row, make sure that you check this box.'),
    ];
    $form['csv']['override'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Override existing sources'),
      '#description' => $this
        ->t('To override stored redirects, check this box.'),
    ];
    $validators = [
      'file_validate_extensions' => [
        'csv',
      ],
      'file_validate_size' => [
        Environment::getUploadMaxSize(),
      ],
    ];
    $form['csv']['csv_file'] = [
      '#type' => 'file',
      '#title' => $this
        ->t('CSV File'),
      '#description' => [
        '#theme' => 'file_upload_help',
        '#description' => $this
          ->t('The CSV file must include the following columns in this order: "From URL","To URL","Redirect Status","Redirect Language". Defaults for status and language can be set in the advanced options, below. The Language column will be ignored if the language module is not in use.'),
      ],
      '#upload_validators' => $validators,
    ];
    $form['advanced'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Advanced options'),
    ];
    $form['advanced']['status_code'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Redirect status'),
      '#description' => $this
        ->t('Set a default redirect value to use. Values set explicitly in the uploaded file will still take precedence. Find more information about HTTP redirect status codes <a href=":status_codes">here</a>.', [
        ':status_codes' => 'https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection',
      ]),
      '#options' => redirect_status_code_options(),
      '#default_value' => '301',
      '#size' => 5,
    ];
    if (\Drupal::moduleHandler()
      ->moduleExists('language')) {
      $options = [];

      // We always need a language.
      $languages = \Drupal::languageManager()
        ->getLanguages();
      foreach ($languages as $langcode => $language) {
        $options[$langcode] = $language
          ->getName();
      }
      $form['advanced']['language'] = [
        '#type' => 'language_select',
        '#title' => t('Redirect language'),
        '#description' => t('A redirect set for a specific language will always be used when requesting this page in that language, and takes precedence over redirects set for <em>All languages</em>.'),
        '#default_value' => Language::LANGCODE_NOT_SPECIFIED,
        '#options' => [
          Language::LANGCODE_NOT_SPECIFIED => t('Not Specified'),
        ] + $options,
      ];
    }
    $form['advanced']['suppress_messages'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Suppress displaying line-specific messages on screen'),
      '#description' => $this
        ->t('Consider checking this if you are importing a very large amount of redirects. Reporting will still be logged, and general import messages will still print.'),
    ];
    $form['advanced']['allow_nonexistent'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Allow nonexistent paths to be imported'),
      '#description' => $this
        ->t('Consider checking this if you want to have nonexistent paths imported.'),
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Import'),
      '#button_type' => 'primary',
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $this->file = file_save_upload('csv_file', $form['csv']['csv_file']['#upload_validators'], FALSE, 0);

    // Ensure we have the file uploaded.
    if (!$this->file) {
      $form_state
        ->setErrorByName('csv_file', $this
        ->t('You must add a valid file to the form in order to import redirects.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    ini_set('auto_detect_line_endings', TRUE);

    // Don't do anything if no valid file.
    if (!isset($this->file)) {
      $this
        ->messenger()
        ->addWarning($this
        ->t('No valid file was found. No redirects have been imported.'));
      return;
    }
    $options = [
      'status_code' => $form_state
        ->getValue('status_code'),
      'override' => $form_state
        ->getValue('override'),
      'no_headers' => $form_state
        ->getValue('no_headers'),
      'delimiter' => $form_state
        ->getValue('delimiter'),
      'language' => $form_state
        ->getValue('language') ?: Language::LANGCODE_NOT_SPECIFIED,
      'suppress_messages' => $form_state
        ->getValue('suppress_messages'),
      'allow_nonexistent' => $form_state
        ->getValue('allow_nonexistent'),
    ];
    ImporterService::import($this->file, $options);

    // Remove file from Drupal managed files & from filesystem.
    \Drupal::service('entity_type.manager')
      ->getStorage('file')
      ->delete([
      $this->file,
    ]);
  }

}

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::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
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 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.
RedirectImportForm::$file protected property Uploaded file entity.
RedirectImportForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
RedirectImportForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
RedirectImportForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
RedirectImportForm::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.