You are here

class DeleteForm in Filebrowser 3.x

Same name and namespace in other branches
  1. 8.2 src/Form/DeleteForm.php \Drupal\filebrowser\Form\DeleteForm

Hierarchy

Expanded class hierarchy of DeleteForm

File

src/Form/DeleteForm.php, line 17

Namespace

Drupal\filebrowser\Form
View source
class DeleteForm extends ConfirmFormBase {

  /**
   * @var int
   */
  protected $queryFid;

  /**
   * @var \Drupal\node\NodeInterface
   */
  protected $node;

  /**
   * Common methods
   * @var \Drupal\filebrowser\Services\Common
   */
  protected $common;

  /**
   * Validator methods
   *
   * @var \Drupal\filebrowser\Services\FilebrowserValidator
   */
  protected $validator;

  /**
   * Filebrowser object holds specific data
   *
   * @var \Drupal\filebrowser\Filebrowser
   */
  protected $filebrowser;

  /**
   * @var array
   * Array of fid of files to delete
   */
  protected $itemsToDelete;

  /**
   * The file system.
   *
   * @var \Drupal\Core\File\FileSystemInterface
   */
  protected $fileSystem;

  /**
   * ConfirmForm constructor.
   */
  public function __construct() {
    $this->validator = \Drupal::service('filebrowser.validator');
    $this->common = \Drupal::service('filebrowser.common');
    $this->fileSystem = \Drupal::service('file_system');
    $this->itemsToDelete = null;
  }
  public function getFormId() {
    return 'filebrowser_delete_form';
  }
  public function buildForm(array $form, FormStateInterface $form_state, $nid = null, $query_fid = 0, $fids_str = null, $ajax = null) {
    $this->node = Node::load($nid);
    $this->queryFid = $query_fid;
    $this->filebrowser = $this->node->filebrowser;
    $fids = explode(',', $fids_str);

    // $this->error = false;
    // This flag indicates that a folder has been selected for deletion.
    $folder_selected = false;
    $files = $this->common
      ->nodeContentLoadMultiple($fids);
    foreach ($files as $fid => $file) {

      // Additional data.
      $file['type'] = unserialize($file['file_data'])->type;
      $file['full_path'] = $this->validator
        ->encodingToFs($this->filebrowser->encoding, $this->validator
        ->getNodeRoot($this->filebrowser->folderPath . $file['path']));
      $file['display_name'] = $this->validator
        ->safeBaseName($file['full_path']);

      // Store item data.
      $this->itemsToDelete[$fid] = $file;
    }

    // Compose the list of files being deleted.
    $list = '<ul>';
    foreach ($this->itemsToDelete as $item) {
      $list .= '<li>';
      if ($item['type'] == 'dir') {
        $folder_selected = true;
        $list .= '<b>' . $item['display_name'] . '</b>';
      }
      else {
        $list .= $item['display_name'];
      }
      $list .= '</li>';
    }
    $list .= '</ul>';
    if ($ajax) {
      $form['#attributes'] = [
        'class' => [
          'form-in-slide-down',
        ],
      ];

      // Add a close slide-down-form button
      $form['close_button'] = $this->common
        ->closeButtonMarkup();
    }
    $form['items'] = [
      '#type' => 'item',
      '#title' => $this
        ->t('Items being deleted'),
      '#markup' => $list,
    ];

    // If at least a folder has been selected, add a confirmation checkbox.
    if ($folder_selected) {
      $form['confirmation'] = [
        '#type' => 'checkbox',
        '#title' => $this
          ->t('Confirm deletion of selected <b>folders</b> and all of their content.'),
        '#default_value' => false,
      ];
    }
    else {

      // No confirmation needed, we'll add a "fake" field.
      $form['confirmation'] = [
        '#type' => 'value',
        '#value' => TRUE,
      ];
    }
    $form = parent::buildForm($form, $form_state);
    $form['actions']['cancel']['#attributes']['class'][] = 'button btn btn-default';
    if ($ajax) {
      $form['actions']['submit']['#attributes']['class'][] = 'use-ajax-submit';
      $this->ajax = true;
    }
    return $form;
  }
  public function getQuestion() {
    return $this
      ->t('Are you sure you want to delete the following items?');
  }
  public function getCancelUrl() {
    return $this->node
      ->toUrl();
  }
  public function getDescription() {
    return $this
      ->t('this action can not be undone.');
  }
  public function getConfirmText() {
    return $this
      ->t('Delete');
  }

  /**
   * @param array $form
   * @param FormStateInterface $form_state
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    if ($this->error) {

      // Create an AjaxResponse.
      $response = new AjaxResponse();

      // Remove old events
      $response
        ->addCommand(new RemoveCommand('#filebrowser-form-action-error'));
      $response
        ->addCommand(new RemoveCommand('.form-in-slide-down'));

      // Insert event details after event.
      $response
        ->addCommand(new AfterCommand('#form-action-actions-wrapper', $form));

      // $response->addCommand(new AfterCommand('#form-action-actions-wrapper', $html));
      $response
        ->addCommand(new AlertCommand($this
        ->t('You must confirm deletion of selected folders.')));
      $form_state
        ->setResponse($response);
    }
    else {
      foreach ($this->itemsToDelete as $item) {
        $data = unserialize($item['file_data']);
        $success = $this->fileSystem
          ->deleteRecursive($data->uri);
        if ($success) {

          // invalidate the cache for this node
          Cache::invalidateTags([
            'filebrowser:node:' . $this->node
              ->id(),
          ]);
        }
        else {
          \Drupal::messenger()
            ->addWarning($this
            ->t('Unable to delete @file', [
            '@file' => $data->uri,
          ]));
        }
      }
      $route = $this->common
        ->redirectRoute($this->queryFid, $this->node
        ->id());
      if ($this->ajax) {
        $response_url = Url::fromRoute($route['name'], $route['node'], $route['query']);
        $response = new AjaxResponse();
        $response
          ->addCommand(new RedirectCommand($response_url
          ->toString()));
        $form_state
          ->setResponse($response);
      }
      else {
        $form_state
          ->setRedirect($route['name'], $route['node'], $route['query']);
      }
    }
  }
  public function validateForm(array &$form, FormStateInterface $form_state) {

    // Check if the confirmation checkbox has been checked.
    if (empty($form_state
      ->getValue('confirmation'))) {

      // commented out original code below
      // https://www.drupal.org/project/filebrowser/issues/2955654
      //  $this->common->debugToConsole('validate');
      //  $form_state->setErrorByName('confirmation', $this->t('You must confirm deletion of selected folders.'));
      $this->error = true;
    }

    // Check if the confirmation checkbox has been checked.
    parent::validateForm($form, $form_state);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfirmFormBase::getCancelText public function Returns a caption for the link which cancels the action. Overrides ConfirmFormInterface::getCancelText 2
ConfirmFormBase::getFormName public function Returns the internal name used to refer to the confirmation item. Overrides ConfirmFormInterface::getFormName
DeleteForm::$common protected property Common methods
DeleteForm::$filebrowser protected property Filebrowser object holds specific data
DeleteForm::$fileSystem protected property The file system.
DeleteForm::$itemsToDelete protected property Array of fid of files to delete
DeleteForm::$node protected property
DeleteForm::$queryFid protected property
DeleteForm::$validator protected property Validator methods
DeleteForm::buildForm public function Form constructor. Overrides ConfirmFormBase::buildForm
DeleteForm::getCancelUrl public function Returns the route to go to if the user cancels the action. Overrides ConfirmFormInterface::getCancelUrl
DeleteForm::getConfirmText public function Returns a caption for the button that confirms the action. Overrides ConfirmFormBase::getConfirmText
DeleteForm::getDescription public function Returns additional text to display as a description. Overrides ConfirmFormBase::getDescription
DeleteForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
DeleteForm::getQuestion public function Returns the question to ask the user. Overrides ConfirmFormInterface::getQuestion
DeleteForm::submitForm public function Overrides FormInterface::submitForm
DeleteForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
DeleteForm::__construct public function ConfirmForm constructor.
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 3
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. 3
FormBase::container private function Returns the service container.
FormBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 105
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.
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.
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. 27
MessengerTrait::messenger public function Gets the messenger. 27
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. 4
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.