First thing I noticed is that you copied the entire add to cart form, I would recommend you extend the addToCart form instead of reimplementing the entire form. In order to make ajax work for we changed the actions function like so:
/**
* {@inheritdoc}
*/
protected function actions(array $form, FormStateInterface $form_state) {
$actions['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Add to cart'),
'#submit' => ['::submitForm'],
'#ajax' => [
'callback' => '::ajaxSubmit',
'wrapper' => $this->getAddToCartWrapperId(),
],
];
return $actions;
}
And added the ajaxSubmit function:
public function ajaxSubmit(array &$form, FormStateInterface $form_state) {
$response = new AjaxResponse();
$messagesRender = StatusMessages::renderMessages(NULL);
$messages = \Drupal::service('renderer')->renderPlain($messagesRender);
// Remove any existing messages
$response->addCommand(new RemoveCommand('.messages'));
if ($form_state->hasAnyErrors()) {
$response->addCommand(
new PrependCommand('.main-content', $messages)
);
return $response;
}
else {
$form_state->setRebuild(FALSE);
}
return $form;
}
Not sure if you need to return the status messages in case of errors but for our implementation we needed it. But after this is worked.
I can make a small patch if you would like it but I am not sure when it will be. Let me know what you think and how it works out.
// Jesper
Comments
Comment #2
subhojit777In 7.x the module shows any feedback message ajaxifically. I will need the same in 8.x. Please create a patch for this.
At first I was extending the addToCart form, then I had to change some helper message, so I ended up using the FormatterBase. You can also create a patch for this, but in a separate issue please.
Thanks for review.
Comment #3
subhojit777Ajax confirmation message #2910738: Ajaxify the confirmation message. The code improvement has also been addressed.