Skip to main content
andrés ignacio torres

Handle errors on custom Elementor Form Actions

If you're using the Elementor plug-in for WordPress, you might eventually need to customize one or several submit actions for Elementor Forms. For example, you might need to call a specific API on form submission or create custom rows in your database when the built-in actions (such as sending emails or saving submissions) fall short.

The official Elementor Form Actions documentation contains an introduction to form actions, including two code samples for creating new ones. However, none of the examples (or the rest of the documentation) showcase how to handle errors (e.g. how to inform the front-end that you can't process the data any further and the user must review their answers).

To achieve this, you can try the following code snippet:

public function run( $record, $ajax_handler )
{
  // This is the function that runs your custom action
  // to handle an Elementor Form submit

  // Let's try to do something that (we know) can fail
  try {
    action_that_can_fail();
  } catch (Exception $e) {
    // Adding the exception message to the AJAX handler
    $ajax_handler->add_error_message($e->getMessage());

    // You can also set the error to a specific field
    $ajax_handler->add_error(
      'username',
      $e->getMessage()
    );

    return false;
  }
}

Note that this code and its behavior are similar to those in the Elementor Form Fields documentation which I discovered after starting to write this blog post. However, since it's not mentioned on the Form Actions documentation, I hope this post serves as a bridge between the two for anyone wondering how to gracefully handle errors on form submission for their custom actions.