You are here

class ReorderFolderForm in Taxonomy File Tree 8

Same name and namespace in other branches
  1. 3.x src/Form/ReorderFolderForm.php \Drupal\tft\Form\ReorderFolderForm

Term reordering form.

Hierarchy

Expanded class hierarchy of ReorderFolderForm

1 string reference to 'ReorderFolderForm'
tft.routing.yml in ./tft.routing.yml
tft.routing.yml

File

src/Form/ReorderFolderForm.php, line 13

Namespace

Drupal\tft\Form
View source
class ReorderFolderForm extends FormBase {

  /**
   * Form helper. Flattens the terms tree and creates the form elements.
   *
   * @param array $tree
   *   The current tree level to be rendered.
   * @param mixed $form
   *   A reference to the form array.
   * @param int $root_depth
   *   The depth of the root term.
   */
  protected function manage_folders_form(array $tree, &$form, $root_depth = 0) {
    foreach ($tree as $data) {
      $data['depth'] = isset($data['tid']) ? _tft_get_depth($data['tid']) - $root_depth : _tft_get_depth($data['parent']) - $root_depth + 1;
      $key = 'term-' . $data['tid'];
      $form['table'][$key] = [];
      $form['table'][$key]['name'] = [
        '#type' => 'textfield',
        '#default_value' => $data['name'],
        '#maxlength' => 255,
        '#required' => TRUE,
        '#size' => '',
      ];
      $form['table'][$key]['parent'] = [
        '#type' => 'textfield',
        '#default_value' => $data['parent'],
        '#size' => 6,
        '#attributes' => [
          'class' => [
            'taxonomy_term_hierarchy-parent',
          ],
        ],
      ];
      $form['table'][$key]['id'] = [
        '#type' => 'hidden',
        '#default_value' => $data['tid'],
        '#attributes' => [
          'class' => [
            'taxonomy_term_hierarchy-tid',
          ],
        ],
      ];
      $form['table'][$key]['type'] = [
        '#type' => 'hidden',
        '#value' => isset($data['type']) ? $data['type'] : 'term',
      ];
      $form['table'][$key]['depth'] = [
        '#type' => 'value',
        '#value' => $data['depth'],
      ];
      $form['table'][$key]['weight'] = [
        '#type' => 'weight',
        '#delta' => 50,
        '#default_value' => $data['weight'],
        '#attributes' => [
          'class' => [
            'taxonomy_term_hierarchy-weight',
          ],
        ],
      ];
      if (isset($data['children'])) {
        $this
          ->manage_folders_form($data['children'], $form, $root_depth);
      }
    }
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, TermInterface $taxonomy_term = NULL) {
    $tid = $taxonomy_term
      ->id();
    $tree = _tft_folder_tree($tid);
    $root_depth = _tft_get_depth($tid) + 1;
    $form['#attributes'] = [
      'id' => 'tft-manage-folders-form',
    ];
    $form['#tid'] = $tid;
    $form['#use_hierarchy'] = TRUE;
    $form['#use_weight'] = TRUE;
    $this
      ->manage_folders_form($tree, $form, $root_depth);
    $data = array_filter($form['table'], function ($item, $key) {
      return is_array($item) && preg_match('/term-[0-9]+/', $key);
    }, ARRAY_FILTER_USE_BOTH);
    $form['table'] = [
      '#type' => 'table',
      '#attributes' => [
        'id' => 'tft-outline',
      ],
      '#header' => [
        $this
          ->t('Name'),
        $this
          ->t('Parent'),
        $this
          ->t('Weight'),
      ],
      '#tabledrag' => [
        [
          'action' => 'match',
          'relationship' => 'parent',
          'group' => 'taxonomy_term_hierarchy-parent',
          'subgroup' => 'taxonomy_term_hierarchy-parent',
          'source' => 'taxonomy_term_hierarchy-tid',
        ],
        [
          'action' => 'order',
          'relationship' => 'sibling',
          'group' => 'taxonomy_term_hierarchy-weight',
        ],
      ],
      '#tree' => TRUE,
      '#weight' => 1,
    ];
    foreach ($data as $key => $item) {
      $form['table'][$key]['#attributes']['class'][] = 'draggable';
      $form['table'][$key]['#weight'] = $item['weight']['#default_value'];
      $form['table'][$key]['name'] = [
        [
          '#theme' => 'indentation',
          '#size' => isset($item['depth']['#value']) ? $item['depth']['#value'] : 0,
        ],
        [
          '#theme' => 'image',
          '#uri' => drupal_get_path('module', 'tft') . '/img/folder.png',
          '#attributes' => [
            'class' => 'tft-admin-folder-content-item',
          ],
        ],
        $item['name'],
      ];
      $form['table'][$key]['parent'] = [
        $item['parent'],
        $item['id'],
        $item['type'],
      ];
      $form['table'][$key]['weight'] = [
        $item['weight'],
      ];
    }
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save changes'),
    ];
    $form[] = [
      // Add CSS and Javascript files.
      '#attached' => [
        'library' => [
          'tft/tft',
        ],
      ],
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    foreach ($form_state
      ->getValue('table') as $key => $item) {
      $name = $item['name'][2];
      $pid = $item['parent'][0];
      $tid = $item['parent'][1];
      $weight = $item['weight'][0];
      $term = Term::load($tid);
      $term
        ->set('parent', [
        'target_id' => $pid,
      ]);
      $term
        ->setName($name);
      $term
        ->setWeight($weight);
      $term
        ->save();
    }
  }

}

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.
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.
ReorderFolderForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
ReorderFolderForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ReorderFolderForm::manage_folders_form protected function Form helper. Flattens the terms tree and creates the form elements.
ReorderFolderForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
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.