Score:0

is it posible to get the value of other fields right inside the buildForm() method without having to save configuration?

pl flag

I have a config form with two select fields. The first one(vocabulary) gets populated automatically without problems with options taken from the available vocabularies for users to pick up one. The problem comes now, the second select field should be automatically populated with taxonomy terms based con the chosen vocabulary...but it DOES NOT work ($form_state->getValue('vocabulary';). My quesion is: is it posible to get the value of other fields right inside the buildForm() method without having to save configuration in submitForm() and later get the value from saved configuration?

Here is my buildForm() method:

 public function buildForm(array $form, FormStateInterface $form_state) {


    //get all vocabularies available and store their vid in an array(to be passend to select htmm form element)
    //we store vid instead of label because the latest can change at any moment
    $vocabulary = $this->entityTypeManager->getStorage('taxonomy_vocabulary')->loadMultiple();
    $voc_options = ['--none--'];
    foreach ($vocabulary as $voc) {
      // $voc is here an entity object of type Drupal\taxonomy\Entity\Vocabulary;
      // convert the entity object to array and then access the value of vid(should be a better way)
      $voc_options[] = $voc->toArray()['vid'];
    }

    $form['vocabulary'] = [
      '#type' => 'select',
      '#title' => $this->t('Select vocabulary'),
      '#options' => $voc_options,
    ];

    //$vtarget = $form_state->getValue('vocabulary'); // does not work
    $vtarget = 'authors'; // works
    $terms = $this->entityTypeManager->getStorage('taxonomy_term')->loadByProperties(['vid' => $vtarget]);
    //$terms = $this->entityTypeManager->getStorage('taxonomy_term')->loadTree($vtarget);
    $sections = [];
    foreach ($terms as $term) {
      $sections[] = $term->label();

    }
    $form['section'] = [
      '#type' => 'select',
      '#title' => $this->t('Select section'),
      '#options' => $sections,
    ];

    return parent::buildForm($form, $form_state);
  }
Score:0
eu flag

Yes, it is possible.

What you need is adding the #ajax property to your vocabulary form element.
A good place to look for an example is the Examples for Developers project, which contains the DependentDropdown class.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.