Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By harivenuv on
Here is my code bit
public function buildForm(array $form, FormStateInterface $form_state) {
$this->wrapper = 'taxonomy-wrapper';
$query = \Drupal::entityQuery('taxonomy_vocabulary');
$all_ids = $query->execute();
foreach (Vocabulary::loadMultiple($all_ids) as $vocabulary) {
$vocs[$vocabulary->id()] = $this->t($vocabulary->label());
}
$form['taxonomy']['vocabulary'] = array(
'#type' => 'select',
'#title' => $this->t('Vocabulary'),
'#options' => $vocs,
'#empty_option' => $this->t('-select-'),
'#size' => 1,
'#required' => TRUE,
'#ajax' => [
'callback' => [$this, 'ajaxCallChangeTaxonomy'],
'wrapper' => $this->wrapper,
'progress' => array(
'type' => 'throbber',
'message' => "Loading..",
),
]
);
$option = [];
$form['taxonomy']['taxonomyterm'] = [
'#type' => 'select',
'#multiple' => TRUE,
'#title' => $this->t('Current Terms'),
'#options' => $option,
'#prefix' => '<div id="' . $this->wrapper . '">',
'#suffix' => '</div>',
];
return $form;
}
/**
* Ajax callback.
*/
public function ajaxCallChangeTaxonomy(array &$form, FormStateInterface $form_state) {
$element = $form;
// Get $form_state values.
$values = $form_state->getValues();
// Entity type.
$vid = $values['vocabulary'];
$terms = \Drupal::entityManager()->getStorage('taxonomy_term')->loadTree($vid);
$option = [];
if (!empty($terms)) {
foreach ($terms as $key => $term) {
$option[$term->tid] = $term->name;
}
}
$element['taxonomy']['taxonomyterm'] = [
'#type' => 'select',
'#multiple' => TRUE,
'#title' => $this->t('Current Terms'),
'#options' => $option,
'#prefix' => '<div id="' . $this->wrapper . '">',
'#suffix' => '</div>',
];
$response = new AjaxResponse();
$response->addCommand(new ReplaceCommand('#' . $this->wrapper, trim(drupal_render($element['taxonomy']['taxonomyterm']))));
return $response;
}
The ajax work fine but not getting the expected result. The render form field missing name, id, and other properties.
The output snippet
<div id="taxonomy-wrapper"><div class="js-form-item form-item js-form-type-select form-type-select js-form-item- form-item-">
<label>Current Terms</label>
<select class="form-select"><option value="1">test</option><option value="2">test1</option></select>
</div>
</div>
Anyone please help me.
Comments
dont use drupal_render