I recently had to do something similar, and I took a good amount of time to understand how Drupal 8 ajax works.
Here are the steps:
Step 1: Ajaxify the link to open the modal, this is easy and you've probably done it already.
$form['ajaxed_link'] = [
'#type' => 'link',
'#title' => $this->t('Click to open the modal'),
'#url' => Url::fromRoute('route_name', ['route_parameters']),
'#attributes' => [
'class' => ['use-ajax'],
'data-dialog-type' => 'modal',
'data-dialog-options' => Json::encode([
'height' => 400,
'width' => 700
]),
],
Step 2: Create the form that will open when the #url is called and create a route for it as well. Remember to make the submit button there ajax too, and specify an ajax submit handler using the callback
key.
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Ajaxed submit button'),
'#ajax' => [
'callback' => [$this, 'ajaxSubmit'],
]
);
Step 3: Define a function for the callback and make sure it returns an ajax response with the right commands. The first command closes the modal and the second command invokes the click on the desired button (use the correct jquery-selector).
public function ajaxSubmit(array &$form, FormStateInterface $form_state, Request $request) {
$response = new AjaxResponse();
$response->addCommand(new CloseModalDialogCommand());
$response->addCommand(new InvokeCommand('#jquery-selector', 'click'));
return $response;
}
Take note that it's a good idea to provide a non-ajax fallback return value from the ajaxSubmit
callback for clients where JS is disabled. Do this by setting a form redirect in the regular form submit handler.
public function submitForm(array &$form, FormStateInterface $form_state) {
...
$form_state->setRedirect('route_to_previous_form');
}