Early Bird Registration for DrupalCon Portland 2024 is open! Register by 23:59 PST on 31 March 2024, to get $100 off your ticket.
By KilianM on
Hi all,
I actually have a problem for alter submit value on Drupal 8.2.
This is my code :
function MODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {
if ($form_id == 'views_exposed_form' && $form['#id'] == 'views-exposed-form-id') {
array_unshift($form['actions']['submit']['#submit'],'submit_form_function');
}
}
function submit_form_function($form, FormStateInterface $form_state) {
$geolocation_geocoder_google_geocoding_api = $form_state->getValue('geolocation_geocoder_google_geocoding_api');
$GoogleGeoAPI = new \Drupal\geolocation\Plugin\geolocation\Geocoder\GoogleGeocodingAPI(array());
if (!empty($geolocation_geocoder_google_geocoding_api)) {
$result = $GoogleGeoAPI->geocode($geolocation_geocoder_google_geocoding_api);
if (!empty($result)) {
$form_state->set('field_agency_gps_geolocation_proximity-lat', $result['location']['lat']);
$form_state->setValue('field_agency_gps_geolocation_proximity-lat', $result['location']['lat']);
$form_state->set('field_agency_gps_geolocation_proximity-lng', $result['location']['lng']);
$form_state->setValue('field_agency_gps_geolocation_proximity-lng', $result['location']['lng']);
}
}
}
But when I submit the form. It's not working.
Is it the good way to alter value ?
Thanx for help.
Comments
Hello,
Hello,
I had a quick look and I can see 2 errors:
1-
I think this is not the right way to call a function on form submit
array_unshift($form['actions']['submit']['#submit'],'submit_form_function');It should be:
if ($form_id == 'views_exposed_form' && $form['#id'] == 'views-exposed-form-id') {
$form['#submit'][] = 'submit_form_function';
}
2- In the callback function you are using both $form_state-set() and $form_state-setValue(). As per the documentation you should use setValue() only.
This is the page for this method: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21Fo...
This doc page clearly say that this method is to: 'Sets the submitted form value for a specific key.'
Thx but
Thanx for the answer.
My value change on form_state but not change when the form reload (default value).
I did some tests and my value change in form_state but the $_GET parameter and the default value of field is still the old one.
I don't know why.