J. Dough J. Dough - 18 days ago 9
Javascript Question

How to pass a value from javascript to drupal 8 form?

I need to pass a value from Javascript to my drupal 8 form.

I've added a hidden field to the form. Javascript is calculating a value and writes it into the field. But how can I get to the value within the function submitForm()?

Is using a hidden field even the right approach? If so, what do I have to do, to make this work?

I've removed most of the code for readability.

FooForm.php:

class FooForm extends FormBase
{
public function getFormId()
{
return 'fooID';
}
public function buildForm(array $form, FormStateInterface $form_state)
{

//...here are lot's of elements not relevant right now

$form['myhiddenfield'] = ['#type' => 'hidden'];//adding hidden field.
$form['#attached']['library'][] = 'foo/foocalculator';

return $form;
}

public function submitForm(array &$form, FormStateInterface $form_state)
{
dpm($form_state->getValues()['myhiddenfield']);//not getting the calculated value.
}


foocalculator.js:

(function ($, Drupal) {
passToDrupal = $('#myhiddenfield');
$('#edit-submit--3').click(function (event) {
calcRoute(address, $editparcel.fieldValue().toString())
});
})(jQuery, Drupal);

function calcRoute(start, destination) {
var request = {
origin: start,
destination: destination,
};
directionsService.route(request, function (result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
mydistance = result.routes[0].legs[0].distance.value;
passToDrupal.val(mydistance);//adds value to hidden field.
}
});
}

Answer

The hidden fields are a bit special because the changes of the field value are not directly visible among the submitted values (which can be retrieved with $form_state->getValues()). Instead, they are visible in the user input values of the form state, so try this:

$form_state->getUserInput()['myhiddenfield']

Be careful with using the getUserInput() for hidden fields, because unless you have a good reason why you do it (like you have in this case) a change in a hidden field is usually done by "unfriendly" entities, which are trying to break your site.