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]));

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?

  • 1
    Do you know about the Entity Browser module? It provides this functionality. – sonfd Jun 27 at 21:15
  • Interesting module. Turns out we already had it installed. Took a while to get it to do anything but seem to have it sort of working. Wouldn't fit well with the interface I am trying to create. – liquidcms Jun 28 at 20:18
  • I found the answer here: drupal.stackexchange.com/questions/232188/… – liquidcms Jul 3 at 16:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.