You are here

class FileDeleteForm in Ubercart 8.4

Performs delete file action.

Hierarchy

Expanded class hierarchy of FileDeleteForm

1 string reference to 'FileDeleteForm'
uc_file.routing.yml in uc_file/uc_file.routing.yml
uc_file/uc_file.routing.yml

File

uc_file/src/Form/FileDeleteForm.php, line 13

Namespace

Drupal\uc_file\Form
View source
class FileDeleteForm extends ConfirmFormBase {

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    return $this
      ->t('Delete file(s)?');
  }

  /**
   * {@inheritdoc}
   */
  public function getDescription() {
    return $this
      ->t('Deleting a file will remove all its associated file downloads and product features. Removing a directory will remove any files it contains and their associated file downloads and product features.');
  }

  /**
   * {@inheritdoc}
   */
  public function getConfirmText() {
    return $this
      ->t('Yes');
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelText() {
    return $this
      ->t('No');
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {
    return Url::fromRoute('uc_file.downloads');
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $file_ids = array_filter($form_state
      ->getValue('file_select'));
    $form['file_ids'] = [
      '#type' => 'value',
      '#value' => $file_ids,
    ];
    $form['action'] = [
      '#type' => 'value',
      '#value' => $form_state
        ->getValue([
        'uc_file_action',
        'action',
      ]),
    ];
    $file_ids = _uc_file_sort_names(_uc_file_get_dir_file_ids($file_ids, FALSE));
    $affected_list = $this
      ->buildJsFileDisplay($file_ids);
    $has_directory = FALSE;
    foreach ($file_ids as $file_id) {

      // Gather a list of user-selected filenames.
      $file = uc_file_get_by_id($file_id);
      $filename = $file->filename;
      $file_list[] = substr($filename, -1) == '/' ? $filename . ' (' . $this
        ->t('directory') . ')' : $filename;

      // Determine if there are any directories in this list.
      $path = uc_file_qualify_file($filename);
      if (is_dir($path)) {
        $has_directory = TRUE;
      }
    }

    // Base files/dirs the user selected.
    $form['selected_files'] = [
      '#theme' => 'item_list',
      '#items' => $file_list,
      '#attributes' => [
        'class' => [
          'selected-file-name',
        ],
      ],
    ];

    // Don't even show the recursion checkbox unless we have any directories.
    if ($has_directory && $affected_list[TRUE] !== FALSE) {
      $form['recurse_directories'] = [
        '#type' => 'checkbox',
        '#title' => $this
          ->t('Delete selected directories and their sub directories'),
      ];

      // Default to FALSE. Although we have the JS behavior to update with the
      // state of the checkbox on load, this should improve the experience of
      // users who don't have JS enabled over not defaulting to any info.
      $form['affected_files'] = [
        '#theme' => 'item_list',
        '#items' => $affected_list[FALSE],
        '#title' => $this
          ->t('Affected files'),
        '#attributes' => [
          'class' => [
            'affected-file-name',
          ],
        ],
      ];
    }
    return parent::buildForm($form, $form_state);
  }

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

    // File deletion status.
    $status = TRUE;

    // Delete the selected file(s), with recursion if selected.
    $status = uc_file_remove_by_id($form_state
      ->getValue('file_ids'), !$form_state
      ->isValueEmpty('recurse_directories')) && $status;
    if ($status) {
      $this
        ->messenger()
        ->addMessage($this
        ->t('The selected file(s) have been deleted.'));
    }
    else {
      $this
        ->messenger()
        ->addWarning($this
        ->t('One or more files could not be deleted.'));
    }
    $form_state
      ->setRedirectUrl($this
      ->getCancelUrl());
  }

  /**
   * @todo Replace with == operator?
   */
  protected function displayArraysEquivalent($recur, $no_recur) {

    // Different sizes.
    if (count($recur) != count($no_recur)) {
      return FALSE;
    }

    // Check the elements.
    for ($i = 0; $i < count($recur); $i++) {
      if ($recur[$i] != $no_recur[$i]) {
        return FALSE;
      }
    }
    return TRUE;
  }

  /**
   * Shows all possible files in selectable list.
   */
  protected function buildJsFileDisplay($file_ids) {

    // Gather the files if recursion IS selected.
    // Get 'em all ready to be punched into the file list.
    $recursion_file_ids = _uc_file_sort_names(_uc_file_get_dir_file_ids($file_ids, TRUE));
    foreach ($recursion_file_ids as $file_id) {
      $file = uc_file_get_by_id($file_id);
      $recursion[] = '<li>' . $file->filename . '</li>';
    }

    // Gather the files if recursion ISN'T selected.
    // Get 'em all ready to be punched into the file list.
    $no_recursion_file_ids = $file_ids;
    foreach ($no_recursion_file_ids as $file_id) {
      $file = uc_file_get_by_id($file_id);
      $no_recursion[] = '<li>' . $file->filename . '</li>';
    }

    // We'll disable the recursion checkbox if they're equal.
    $equivalent = $this
      ->displayArraysEquivalent($recursion_file_ids, $no_recursion_file_ids);

    // The list to show if the recursion checkbox is $key.
    $result[TRUE] = $equivalent ? FALSE : $recursion;
    $result[FALSE] = $no_recursion;

    // Set up some JS to dynamically update the list based on the
    // recursion checkbox state.
    drupal_add_js('uc_file_list[false] = ' . Json::encode('<li>' . implode('</li><li>', $no_recursion) . '</li>') . ';', 'inline');
    drupal_add_js('uc_file_list[true] = ' . Json::encode('<li>' . implode('</li><li>', $recursion) . '</li>') . ';', 'inline');
    return $result;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfirmFormBase::getFormName public function Returns the internal name used to refer to the confirmation item. Overrides ConfirmFormInterface::getFormName
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
FileDeleteForm::buildForm public function Form constructor. Overrides ConfirmFormBase::buildForm
FileDeleteForm::buildJsFileDisplay protected function Shows all possible files in selectable list.
FileDeleteForm::displayArraysEquivalent protected function @todo Replace with == operator?
FileDeleteForm::getCancelText public function Returns a caption for the link which cancels the action. Overrides ConfirmFormBase::getCancelText
FileDeleteForm::getCancelUrl public function Returns the route to go to if the user cancels the action. Overrides ConfirmFormInterface::getCancelUrl
FileDeleteForm::getConfirmText public function Returns a caption for the button that confirms the action. Overrides ConfirmFormBase::getConfirmText
FileDeleteForm::getDescription public function Returns additional text to display as a description. Overrides ConfirmFormBase::getDescription
FileDeleteForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
FileDeleteForm::getQuestion public function Returns the question to ask the user. Overrides ConfirmFormInterface::getQuestion
FileDeleteForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
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.
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.
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.