Skip to content

Instantly share code, notes, and snippets.

@samuelsolis
Last active October 26, 2022 18:52
Show Gist options
  • Save samuelsolis/91b24256e16ed931dfcc9bcf175781a0 to your computer and use it in GitHub Desktop.
Save samuelsolis/91b24256e16ed931dfcc9bcf175781a0 to your computer and use it in GitHub Desktop.
Change Field value in drupal 8 form with Ajax
<?php
/**
* Form controller for the bb_report entity edit forms.
*
* @ingroup report
*/
class FeeForm extends ContentEntityForm {
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form = parent::buildForm($form, $form_state);
//Set all as empty value in province.
$form['province']['widget']['#options']['_none'] = $this->t('- All -');
//Set a wrapper for the ajax petition.
$form['province']['widget']['#prefix'] = '<div id="edit-province">';
$form['province']['widget']['#suffix'] = '</div>';
//Add ajax function to complete another field.
$form['country']['widget'] = [
'#ajax' => [
'callback' => [$this, 'rebuildProvinces'],
'event' => 'change',
'wrapper' => 'edit-province',
],
] + $form['country']['widget'];
return $form;
}
/**
* @param array $form
* @param FormStateInterface $form_state
* @return AjaxResponse
*/
public function rebuildProvinces(array &$form, FormStateInterface $form_state) {
$countries = $form_state->getValues('country');
//Get current country selections.
$countriesIds = [];
foreach ($countries['country'] as $country) {
if(is_array($country)) {
$countriesIds[] = $country['target_id'];
}
}
//Get associated province ids
$provincesIds = \Drupal::entityQuery('province')
->condition('country', $countriesIds, 'IN')
->execute();
$provincesIds[] = '_none';
//Filter provinces using selected countries.
$form['province']['widget']['#options'] = array_intersect_key($form['province']['widget']['#options'], array_flip($provincesIds));
return $form['province'];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment