You are here

class DirectoryDeleteForm in Media Directories 2.x

Same name and namespace in other branches
  1. 8 modules/media_directories_ui/src/Form/DirectoryDeleteForm.php \Drupal\media_directories_ui\Form\DirectoryDeleteForm
  2. 3.x modules/media_directories_ui/src/Form/DirectoryDeleteForm.php \Drupal\media_directories_ui\Form\DirectoryDeleteForm

Form to delete a directory.

Hierarchy

Expanded class hierarchy of DirectoryDeleteForm

1 file declares its use of DirectoryDeleteForm
MediaDirectoriesController.php in modules/media_directories_ui/src/Controller/MediaDirectoriesController.php

File

modules/media_directories_ui/src/Form/DirectoryDeleteForm.php, line 16

Namespace

Drupal\media_directories_ui\Form
View source
class DirectoryDeleteForm extends ConfirmFormBase {

  /**
   * The direcory to delete.
   *
   * @var \Drupal\taxonomy\Entity\Term
   */
  protected $directory;

  /**
   * Form context.
   *
   * @var array
   */
  protected $formContext;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * DirectoryDeleteForm constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity type manager.
   */
  public function __construct(EntityTypeManagerInterface $entityTypeManager) {
    $this->entityTypeManager = $entityTypeManager;
  }

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

  /**
   * {@inheritdoc}
   */
  public function getQuestion() {
    return $this
      ->t('Do you want to delete @name?', [
      '@name' => $this->directory
        ->getName(),
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function getCancelUrl() {

    // TODO: Implement getCancelUrl() method.
  }

  /**
   * {@inheritDoc}
   */
  public function getFormId() {
    return 'directory_delete_form';
  }

  /**
   * {@inheritDoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $build_info = $form_state
      ->getBuildInfo();
    if (isset($build_info['args'][0])) {
      $this->formContext = $build_info['args'][0];
      $this->directory = $this->formContext['directory'];
      $form['directory_id'] = [
        '#type' => 'hidden',
        '#value' => $this->directory
          ->id(),
      ];
    }
    if ($this->directory
      ->access('delete')) {
      $form['question']['#markup'] = '<h4>' . $this
        ->getQuestion() . '</h4>';
      $form = parent::buildForm($form, $form_state);
      $form['#attached']['library'][] = 'core/drupal.dialog.ajax';
      $form['actions']['submit']['#ajax'] = [
        'callback' => [
          $this,
          'submitModalAjax',
        ],
        'event' => 'click',
      ];
      $form['actions']['cancel'] = [
        '#type' => 'button',
        '#value' => $this
          ->t('Cancel'),
        '#button_type' => 'secondary',
        '#ajax' => [
          'callback' => [
            $this,
            'closeModalAjax',
          ],
          'event' => 'click',
        ],
      ];
    }
    else {
      $form['permission_info']['#markup'] = $this
        ->t('No permission found to delete this directory.');
    }
    return $form;
  }

  /**
   * Ajax callback when the form is submitted.
   */
  public function submitModalAjax(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    if ($this->directory
      ->access('delete')) {
      $query = $this->entityTypeManager
        ->getStorage('media')
        ->getQuery();
      $query
        ->condition('directory', $this->directory
        ->id());
      $media_ids = $query
        ->execute();

      // If directory has any media items, move them into root (remove value).
      if (!empty($media_ids)) {

        /** @var \Drupal\media\Entity\Media[] $media_items */
        $media_items = $this->entityTypeManager
          ->getStorage('media')
          ->loadMultiple($media_ids);
        foreach ($media_items as $media_item) {
          $media_item
            ->get('directory')
            ->setValue(NULL);
          $media_item
            ->save();
        }
      }
      $parent_id = (int) $this->directory
        ->get('parent')->target_id;

      // We use -1 as root folder tid.
      if ($parent_id === 0) {
        $parent_id = -1;
      }
      $this->directory
        ->delete();
      $response
        ->addCommand(new CloseModalDialogCommand());
      $response
        ->addCommand(new RefreshDirectoryTree($parent_id));

      // $response->addCommand(new AjaxLoadDirectory());
    }
    return $response;
  }

  /**
   * Close modal dialog.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   An AJAX response.
   */
  public function closeModalAjax() {
    $response = new AjaxResponse();
    $response
      ->addCommand(new CloseModalDialogCommand());
    return $response;
  }

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

    // TODO: Implement submitForm() method.
  }

}

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::getConfirmText public function Returns a caption for the button that confirms the action. Overrides ConfirmFormInterface::getConfirmText 22
ConfirmFormBase::getDescription public function Returns additional text to display as a description. Overrides ConfirmFormInterface::getDescription 14
ConfirmFormBase::getFormName public function Returns the internal name used to refer to the confirmation item. Overrides ConfirmFormInterface::getFormName
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
DirectoryDeleteForm::$directory protected property The direcory to delete.
DirectoryDeleteForm::$entityTypeManager protected property The entity type manager.
DirectoryDeleteForm::$formContext protected property Form context.
DirectoryDeleteForm::buildForm public function Form constructor. Overrides ConfirmFormBase::buildForm
DirectoryDeleteForm::closeModalAjax public function Close modal dialog.
DirectoryDeleteForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
DirectoryDeleteForm::getCancelUrl public function Returns the route to go to if the user cancels the action. Overrides ConfirmFormInterface::getCancelUrl
DirectoryDeleteForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
DirectoryDeleteForm::getQuestion public function Returns the question to ask the user. Overrides ConfirmFormInterface::getQuestion
DirectoryDeleteForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
DirectoryDeleteForm::submitModalAjax public function Ajax callback when the form is submitted.
DirectoryDeleteForm::__construct public function DirectoryDeleteForm constructor.
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::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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 72
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.