I am creating a complexed multistep form based on data from an Excel document. The user can save parts of the form using AJAX save buttons and updated data from the Excel document are displayed in the form. I am fetching a lot of data from Excel - some are for inputs and some are read-only which are not put into FormState.
The issue is that I need to populate the form with data based on the API callback but as the form is not rebuild after the API call to Excel, the updated data from Excel is not put into the form until the next AJAX call. So the data is always one step behind.
I've tried to simplify the architecture and code:
Form
class Form [..] {
public Service $service;
public function buildForm(array $form, FormStateInterface $form_state) {
$form['part_one'] = [
'#attributes' => [
'id' => ['part_one'],
],
'input' => [
'#type' => 'number',
'#value' => $form_state->getUserInput()['input'] ?? $this->service->model->input,
],
'value' => [
'#type' => 'html_tag',
'#tag' => 'p',
'#value' => $this->service->model->value,
],
'save' => [
'#type' => 'button',
'#value' => 'Save',
'#ajax' => [
'callback' => [$this, 'save'],
'wrapper' => 'part_one',
],
],
];
return $form;
}
public function save(array &$form, FormStateInterface $formState) {
$value = $formState->getUserInput()['input'];
$this->service->save($value);
return $form['part_one'];
}
}
Service
class Service {
public Model $model;
public function save($value) {
$httpExcel->save($value);
$modelValues = $httpExcel->get();
$model = new Model($modelValues);
}
}
Model
class Model {
public int $input;
public int $value;
}