Saturday, January 7, 2017

Submit node form via AJAX

If you want to submit node form (or any form) via ajax request you need to follow next steps:
  1. Alter needed form: add container for validation messages and ajax callback for submit action.
  2. Implement ajax callback that returns ajax commands.
<?php

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function module_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Add container for validation messages.
  $form['#prefix'] = '
'; // Add ajax callback for submit action. $form['actions']['submit']['#ajax'] = [ 'callback' => 'module_node_form_ajax_submit', ]; // Don't forget to include node.pages.inc file. Without it Drupal will not be // able to find and call node_form_validate() function. form_load_include($form_state, 'inc', 'node', 'node.pages'); } /** * Form ajax submit callback. * * @return array * Array contains Drupal ajax commands. */ function module_node_form_ajax_submit() { // Remove all status messages from $_SESSION['messages'] variable // because we want to render only error messages. drupal_get_messages('status'); // Check form for possible validation messages. if (form_get_errors()) { // Validation failure: return rendered validation messages. $commands[] = ajax_command_html('#validation-messages', [theme('status_messages')]); } else { // Validation success: do something, for instance redirect user. ctools_include('ajax'); $commands[] = ctools_ajax_command_redirect('some/page'); } return [ '#type' => 'ajax', '#commands' => $commands, ]; }

Key notes:

No comments:

Post a Comment