I have a custom module which adds a button to a node form. The button opens another node form in a modal and when submitted, it takes the entity created in the modal and fills in an entity ref field on the first node form:
function add_venue_form_node_master_events_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// only do this if from Modal
if (!isset($_POST['_drupal_ajax'])) return;
$form['actions']['submit']['#submit'][] = '_add_venue_ajax_submit';
$form['actions']['submit']['#attributes']['class'][] = 'use-ajax-submit';
}
function _add_venue_ajax_submit(array $form, FormStateInterface &$form_state) {
// get NID of Venue we just created
$nid = $form_state->getValue('nid');
$node = Node::load($nid);
$value = $node->getTitle() . ' (' . $nid . ')';
$response = new AjaxResponse();
$response->addCommand(new CloseModalDialogCommand());
$response->addCommand(new InvokeCommand('#edit-field-vcr-cert-holder-name-0-target-id', 'val', [$value]));
$response->addCommand(new InvokeCommand('#edit-field-pcr-cert-holder-name-0-target-id', 'val', [$value]));
$form_state->setResponse($response);
}
This works perfectly but the form doesn't validate (required fields that aren't filled in aren't highlighted in red and no message at the top of the modal to show errors).
I found wombatbuddy's response here: Showing Form Validation Errors inside Modal showing how to do validation. This does work, but then my submit function doesn't work.
Does anyone know how to add validation into my existing code?