"Fossies" - the Fresh Open Source Software Archive

Member "drupal-9.1.0-rc1/core/modules/taxonomy/src/TermForm.php" (18 Nov 2020, 5987 Bytes) of package /linux/www/drupal-9.1.0-rc1.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) PHP source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file. For more information about "TermForm.php" see the Fossies "Dox" file reference documentation.

    1 <?php
    2 
    3 namespace Drupal\taxonomy;
    4 
    5 use Drupal\Core\Entity\ContentEntityForm;
    6 use Drupal\Core\Entity\EntityConstraintViolationListInterface;
    7 use Drupal\Core\Form\FormStateInterface;
    8 
    9 /**
   10  * Base for handler for taxonomy term edit forms.
   11  *
   12  * @internal
   13  */
   14 class TermForm extends ContentEntityForm {
   15 
   16   /**
   17    * {@inheritdoc}
   18    */
   19   public function form(array $form, FormStateInterface $form_state) {
   20     $term = $this->entity;
   21     $vocab_storage = $this->entityTypeManager->getStorage('taxonomy_vocabulary');
   22     /** @var \Drupal\taxonomy\TermStorageInterface $taxonomy_storage */
   23     $taxonomy_storage = $this->entityTypeManager->getStorage('taxonomy_term');
   24     $vocabulary = $vocab_storage->load($term->bundle());
   25 
   26     $parent = array_keys($taxonomy_storage->loadParents($term->id()));
   27     $form_state->set(['taxonomy', 'parent'], $parent);
   28     $form_state->set(['taxonomy', 'vocabulary'], $vocabulary);
   29 
   30     $form['relations'] = [
   31       '#type' => 'details',
   32       '#title' => $this->t('Relations'),
   33       '#open' => $taxonomy_storage->getVocabularyHierarchyType($vocabulary->id()) == VocabularyInterface::HIERARCHY_MULTIPLE,
   34       '#weight' => 10,
   35     ];
   36 
   37     // \Drupal\taxonomy\TermStorageInterface::loadTree() and
   38     // \Drupal\taxonomy\TermStorageInterface::loadParents() may contain large
   39     // numbers of items so we check for taxonomy.settings:override_selector
   40     // before loading the full vocabulary. Contrib modules can then intercept
   41     // before hook_form_alter to provide scalable alternatives.
   42     if (!$this->config('taxonomy.settings')->get('override_selector')) {
   43       $exclude = [];
   44       if (!$term->isNew()) {
   45         $parent = array_keys($taxonomy_storage->loadParents($term->id()));
   46         $children = $taxonomy_storage->loadTree($vocabulary->id(), $term->id());
   47 
   48         // A term can't be the child of itself, nor of its children.
   49         foreach ($children as $child) {
   50           $exclude[] = $child->tid;
   51         }
   52         $exclude[] = $term->id();
   53       }
   54 
   55       $tree = $taxonomy_storage->loadTree($vocabulary->id());
   56       $options = ['<' . $this->t('root') . '>'];
   57       if (empty($parent)) {
   58         $parent = [0];
   59       }
   60 
   61       foreach ($tree as $item) {
   62         if (!in_array($item->tid, $exclude)) {
   63           $options[$item->tid] = str_repeat('-', $item->depth) . $item->name;
   64         }
   65       }
   66 
   67       $form['relations']['parent'] = [
   68         '#type' => 'select',
   69         '#title' => $this->t('Parent terms'),
   70         '#options' => $options,
   71         '#default_value' => $parent,
   72         '#multiple' => TRUE,
   73       ];
   74     }
   75 
   76     $form['relations']['weight'] = [
   77       '#type' => 'textfield',
   78       '#title' => $this->t('Weight'),
   79       '#size' => 6,
   80       '#default_value' => $term->getWeight(),
   81       '#description' => $this->t('Terms are displayed in ascending order by weight.'),
   82       '#required' => TRUE,
   83     ];
   84 
   85     $form['vid'] = [
   86       '#type' => 'value',
   87       '#value' => $vocabulary->id(),
   88     ];
   89 
   90     $form['tid'] = [
   91       '#type' => 'value',
   92       '#value' => $term->id(),
   93     ];
   94 
   95     return parent::form($form, $form_state);
   96   }
   97 
   98   /**
   99    * {@inheritdoc}
  100    */
  101   public function validateForm(array &$form, FormStateInterface $form_state) {
  102     parent::validateForm($form, $form_state);
  103 
  104     // Ensure numeric values.
  105     if ($form_state->hasValue('weight') && !is_numeric($form_state->getValue('weight'))) {
  106       $form_state->setErrorByName('weight', $this->t('Weight value must be numeric.'));
  107     }
  108   }
  109 
  110   /**
  111    * {@inheritdoc}
  112    */
  113   public function buildEntity(array $form, FormStateInterface $form_state) {
  114     $term = parent::buildEntity($form, $form_state);
  115 
  116     // Prevent leading and trailing spaces in term names.
  117     $term->setName(trim($term->getName()));
  118 
  119     // Assign parents with proper delta values starting from 0.
  120     $term->parent = array_values($form_state->getValue('parent'));
  121 
  122     return $term;
  123   }
  124 
  125   /**
  126    * {@inheritdoc}
  127    */
  128   protected function getEditedFieldNames(FormStateInterface $form_state) {
  129     return array_merge(['parent', 'weight'], parent::getEditedFieldNames($form_state));
  130   }
  131 
  132   /**
  133    * {@inheritdoc}
  134    */
  135   protected function flagViolations(EntityConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) {
  136     // Manually flag violations of fields not handled by the form display. This
  137     // is necessary as entity form displays only flag violations for fields
  138     // contained in the display.
  139     // @see ::form()
  140     foreach ($violations->getByField('parent') as $violation) {
  141       $form_state->setErrorByName('parent', $violation->getMessage());
  142     }
  143     foreach ($violations->getByField('weight') as $violation) {
  144       $form_state->setErrorByName('weight', $violation->getMessage());
  145     }
  146 
  147     parent::flagViolations($violations, $form, $form_state);
  148   }
  149 
  150   /**
  151    * {@inheritdoc}
  152    */
  153   public function save(array $form, FormStateInterface $form_state) {
  154     $term = $this->entity;
  155 
  156     $result = $term->save();
  157 
  158     $edit_link = $term->toLink($this->t('Edit'), 'edit-form')->toString();
  159     $view_link = $term->toLink()->toString();
  160     switch ($result) {
  161       case SAVED_NEW:
  162         $this->messenger()->addStatus($this->t('Created new term %term.', ['%term' => $view_link]));
  163         $this->logger('taxonomy')->notice('Created new term %term.', ['%term' => $term->getName(), 'link' => $edit_link]);
  164         break;
  165 
  166       case SAVED_UPDATED:
  167         $this->messenger()->addStatus($this->t('Updated term %term.', ['%term' => $view_link]));
  168         $this->logger('taxonomy')->notice('Updated term %term.', ['%term' => $term->getName(), 'link' => $edit_link]);
  169         break;
  170     }
  171 
  172     $current_parent_count = count($form_state->getValue('parent'));
  173     // Root doesn't count if it's the only parent.
  174     if ($current_parent_count == 1 && $form_state->hasValue(['parent', 0])) {
  175       $form_state->setValue('parent', []);
  176     }
  177 
  178     $form_state->setValue('tid', $term->id());
  179     $form_state->set('tid', $term->id());
  180   }
  181 
  182 }