nortmas
3/23/2018 - 4:08 AM

Ajax Form

<?php

namespace Drupal\mymodule\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class ExampleForm extends FormBase {
  
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    // Unique ID of the form.
    return 'example_form';
  }
  
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    
    // Output status messages.
    $form['#status_messages'] = [
      '#type' => 'status_messages',
    ];

    // Create a $form API array.
    $form['phone_number'] = array(
      '#type' => 'tel',
      '#title' => $this->t('Your phone number'),
      '#element_validate' => '::requiredValidate';
    );
    
    $form['save'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#button_type' => 'primary',
      '#submit' => ['::submitForm'],
    );
    
    $form['save']['#ajax'] = [
      'wrapper' => 'contact-ajax-wrapper',
      'callback' => '::ajaxFormRebuild',
    ];
    
    // Specify AJAX wrapper.
    $form['#prefix'] = '<div id="' . $form['actions']['submit']['#ajax']['wrapper'] . '">';
    $form['#suffix'] = '</div>';
    
    return $form;
  }
  
  /**
   *  Validate submitted form data.
   */
  public function requiredValidate(array $element, FormStateInterface $form_state) {
    $widget = $element['widget'];
    $field_val = $form_state->getValue($widget['#field_name']][0]['value']);
    
    if (empty($field_val)) {
      $message = t('@name field is required.', ['@name' => $widget['#title']]);
      $form_state->setError($widget, $message);
    }
  }
  
  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

    // Validate submitted form data.
  }
  
  /**
   * {@inheritdoc}
   */
  public function ajaxFormRebuild(array &$form, FormStateInterface $form_state) {
    // Create Ajax response object.
    $response = new AjaxResponse();

    if ($form_state->getErrors()) {
      $form['status_messages'] = [
        '#type' => 'status_messages',
        '#weight' => -10,
      ];
    }

    /** @var \Symfony\Component\HttpFoundation\RedirectResponse $redirect */
    $redirect = $this->formSubmitter->redirectForm($form_state);

    if ($redirect) {
      $response->addCommand(new RedirectCommand($redirect->getTargetUrl()));
    }

    $response->addCommand(new ReplaceCommand('#contact-ajax-wrapper', $form));
    $response->addCommand(new RemoveCommand('.message-block', $form));
    $response->addCommand(new InvokeCommand('html, body', 'animate', [
      ['scrollTop' => '0px'],
      300,
    ]));

    return $response;
  }
  
  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Handle submitted form data.
    drupal_set_message(t('Contact information saved.'));
    $route_name = 'acc_user_profiles.user_profile';
    $route_options = [];
    $form_state->setRedirect($route_name, $route_options);
  }

}