TermForm::form

public TermForm::form(array $form, FormStateInterface $form_state)

Gets the actual form array to be built.

Overrides ContentEntityForm::form

See also

\Drupal\Core\Entity\EntityForm::processForm()

\Drupal\Core\Entity\EntityForm::afterBuild()

File

core/modules/taxonomy/src/TermForm.php, line 16

Class

TermForm
Base for handler for taxonomy term edit forms.

Namespace

Drupal\taxonomy

Code

public function form(array $form, FormStateInterface $form_state) {
  $term = $this->entity;
  $vocab_storage = $this->entityManager->getStorage('taxonomy_vocabulary');
  $taxonomy_storage = $this->entityManager->getStorage('taxonomy_term');
  $vocabulary = $vocab_storage->load($term->bundle());

  $parent = array_keys($taxonomy_storage->loadParents($term->id()));
  $form_state->set(['taxonomy', 'parent'], $parent);
  $form_state->set(['taxonomy', 'vocabulary'], $vocabulary);

  $form['relations'] = array(
    '#type' => 'details',
    '#title' => $this->t('Relations'),
    '#open' => $vocabulary->getHierarchy() == VocabularyInterface::HIERARCHY_MULTIPLE,
    '#weight' => 10,
  );

  // \Drupal\taxonomy\TermStorageInterface::loadTree() and
  // \Drupal\taxonomy\TermStorageInterface::loadParents() may contain large
  // numbers of items so we check for taxonomy.settings:override_selector
  // before loading the full vocabulary. Contrib modules can then intercept
  // before hook_form_alter to provide scalable alternatives.
  if (!$this->config('taxonomy.settings')->get('override_selector')) {
    $parent = array_keys($taxonomy_storage->loadParents($term->id()));
    $children = $taxonomy_storage->loadTree($vocabulary->id(), $term->id());

    // A term can't be the child of itself, nor of its children.
    foreach ($children as $child) {
      $exclude[] = $child->tid;
    }
    $exclude[] = $term->id();

    $tree = $taxonomy_storage->loadTree($vocabulary->id());
    $options = array('<' . $this->t('root') . '>');
    if (empty($parent)) {
      $parent = array(0);
    }

    foreach ($tree as $item) {
      if (!in_array($item->tid, $exclude)) {
        $options[$item->tid] = str_repeat('-', $item->depth) . $item->name;
      }
    }

    $form['relations']['parent'] = array(
      '#type' => 'select',
      '#title' => $this->t('Parent terms'),
      '#options' => $options,
      '#default_value' => $parent,
      '#multiple' => TRUE,
    );
  }

  $form['relations']['weight'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Weight'),
    '#size' => 6,
    '#default_value' => $term->getWeight(),
    '#description' => $this->t('Terms are displayed in ascending order by weight.'),
    '#required' => TRUE,
  );

  $form['vid'] = array(
    '#type' => 'value',
    '#value' => $vocabulary->id(),
  );

  $form['tid'] = array(
    '#type' => 'value',
    '#value' => $term->id(),
  );

  return parent::form($form, $form_state, $term);
}
doc_Drupal
2016-10-29 09:47:12
Comments
Leave a Comment

Please login to continue.