Autocalculate computed twig field I'm building a form which should calculate some values during the form view. I've tried to use the computed twig field. The calculation is working after submission and also, when I move to the previous or next page but I want the field to be calculated immediately after the base values has been entered (jQuery/AJAX).



If theres no way of doing it automatically, how can I accomplish this using a "Calculate" button?

I hope somebody can help with this issue or give an example for a form which is using this kind of calculation.

Cheers
if you use the form API to build your form, then you can use the ajax form API.

In the field you want to trigger ajax method, use this : 

$form['test'] = [
  '#type' =&gt; 'textfield',
  '#title' =&gt; 'A Textfield',
  '#required' =&gt; TRUE,
  '#ajax' =&gt; [
    'callback' =&gt; '::ajaxTest',
    'event' =&gt; 'keyup',
    'wrapper' =&gt; 'edit-output',
    'progress' =&gt; [
      'type' =&gt; 'throbber',
      'message' =&gt; t('Verifying entry...'),
    ],
  ],
];


Then create a ajaxTest function in your Form :

public function ajaxTest(array &amp;$form, FormStateInterface $form_state) : array {
  // you can use the $form_state here to get values of all your fields
  $my_value = $form_state-&gt;getValue('my_field');
  // Make your logic code here
  $new_val = 'foo';
}


And then just add a AjaxCommand to your ajaxTest function : 

$response = new AjaxResponse();
$response-&gt;addCommand(new InvokeCommand('#my_id_to_change', 'val', $new_val));
return $response;


You can find all those in the Form and AJAX API here https://api.drupal.org/api/drupal/core%21core.api.php/group/ajax/8.5.x, regards.