calculation_fields
This module extends the Drupal form API adding two more form element types.
- Calculation element
- Calculation element markup
Both elements can evaluate a math expression and display the result.
The Calculation element displays as number input, you can use this value as normal input displaying the result on the front, and the result value will be submitted to the backend.
With Calculation element markup you can provide a specific markup to display the result. The result won't be submitted with the form.
Webform integration.
These elements can also be used in Webforms. Just enable the Webform Calculation fields and you can use these elements on your webform.
How does it work in a form array?
The example below demonstrates how to create the calculation number element.
The #evaluation_fields you gonna inform the math expression.
As you can see in the code below, to use another field from the form inside the expression you can use : it to inform the name of the field.
$form['result'] = [
'#type' => 'form_calculation_element',
'#title' => $this->t('Result'),
'#required' => TRUE,
'#evaluation_fields' => '(:first_value + :second_value + :third_value) * :multiple',
'#evaluation_round' => 2,
];
The result will be calculated when all those fields on the expression are populated. Then the field will be replaced by the value and finally, the expression will be executed and the input field will be updated with the result.
You can use any kind of math expression like the examples below.
'#title' => $this->t('BMI = weight (kg) / (height (m) * height (m))'),
'#evaluation_fields' => ':weight / (:height * :height)',
'#title' => $this->t('Loan Repayment Calculation Example'),
'#evaluation_fields' => '(:loan_amount * :interest_rate * (1 + :interest_rate) ^ :loan_term) / ((1 + :interest_rate) ^ :loan_term - 1)',
Additional Requirements
On the front-end side we use the library Mathjs to evaluate the expression. You don't need to install this library.
On the back-end side to evaluate the expression we use symfony/expression-language package.
Community Documentation
If you need more information about how to configure the form elements please take a look on the README that has some examples and it's explained in details. Also, enable the calculation fields examples to see the elements working and feel free to take a look on the form CalculationFieldsExample
Also, to check more details about the integration with webforms please take a look at README and install the webform_calculation_fields_examples module to get some webforms already configured as examples.