Last active
October 26, 2022 18:52
-
-
Save samuelsolis/91b24256e16ed931dfcc9bcf175781a0 to your computer and use it in GitHub Desktop.
Change Field value in drupal 8 form with Ajax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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