I have an issue with changing / obtaining variables in form element's ajax callback function. (Sorry for typos, I just placed a pieces of whole code).
I have form with input field, where user can select how many pieces of each product he want
$form['wrapper_amount']['value'] = [
'#type' => 'number',
'#prefix' => '<div class="d-flex align-items-end form-element">',
'#suffix' => '<span class="form-element-unit">pcs</span></div>',
'#name' => "amount--product-1",
'#ajax' => [
'callback' => '::calculatePricePerUnit',
'event' => 'change',
'disable-refocus' => TRUE,
'progress' => [
'type' => 'fade',
'message' => NULL,
],
],
];
after choosing a number I calculate price using AJAX callback function and using
public function calculatePricePerUnit(array &$form, FormStateInterface $form_state)
{
// ... price calculation for specific product
// $new_price = (amount * price_per_unit);
$total_price = (float)$form_state->get('total_price_with_vat') + $new_price;
$response = new AjaxResponse();
$response->addCommand(
new InvokeCommand(
'#total-price',
'html', [$form_state->get('total_price_with_vat') . ' €']
)
);
}
The problem is that when used add amount to second product the $form_state->get('total_price_with_vat')
is 0
again. It means that I cant store $total_price
variable in $form_state, because it's not persistent (I've already read this somewhere, that I can't store variables to $form_state in AJAX callback function). So I tried to store it to $form_state->setStorage($my_values)
but it didn't work either.
Please note that all AjaxResponse commands are working and I only need to find best approach how to store data, not how to re-render form's elements.
My next step is to store data in PrivateTempStore, but question is, if it's good approach?
I don't need data on any other Wizard page, neither in Controller or any further step. I just need to calculate $total_price
and some other data that I need to use multiple times in AJAX callback function, and at the end use webform API to send webform submission results via email.