How to perform action from form opened in modal? I have a form where I have a link that opens a modal window with another form(something like adding a block to a region).

I would like to perform the action on the opened/second/modal form during submission as usual but I also want to tell the current window to close the modal and to hit a specific button(which is ajaxified and it will rebuild the form so the changes made via the second form would be visible in the main form - they are based on the same data source).

Is there a way to achieve this with ajax command from the second form?

A good example is View form. When a new window is opened(adding a field, or configuring some part of the View), actions in that window are reflected in the form itself after the window is closed.
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' =&gt; 'link',
  '#title' =&gt; $this-&gt;t('Click to open the modal'),
  '#url' =&gt; Url::fromRoute('route_name', ['route_parameters']),
  '#attributes' =&gt; [
    'class' =&gt; ['use-ajax'],
    'data-dialog-type' =&gt; 'modal',
    'data-dialog-options' =&gt; Json::encode([
      'height' =&gt; 400,
      'width' =&gt; 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' =&gt; 'submit',
  '#value' =&gt; t('Ajaxed submit button'),
  '#ajax' =&gt; [
    'callback' =&gt; [$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 &amp;$form, FormStateInterface $form_state, Request $request) {
  $response = new AjaxResponse();
  $response-&gt;addCommand(new CloseModalDialogCommand());
  $response-&gt;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 &amp;$form, FormStateInterface $form_state) {
  ...
  $form_state-&gt;setRedirect('route_to_previous_form');
}