Callbacks.php 2.5 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\ajax_forms_test;

5 6 7
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\DataCommand;
use Drupal\Core\Ajax\HtmlCommand;
8
use Drupal\Core\Form\FormStateInterface;
9

10 11 12 13 14 15 16 17
/**
 * Simple object for testing methods as Ajax callbacks.
 */
class Callbacks {

  /**
   * Ajax callback triggered by select.
   */
18
  public function selectCallback($form, FormStateInterface $form_state) {
19
    $response = new AjaxResponse();
20 21
    $response->addCommand(new HtmlCommand('#ajax_selected_color', $form_state->getValue('select')));
    $response->addCommand(new DataCommand('#ajax_selected_color', 'form_state_value_select', $form_state->getValue('select')));
22
    return $response;
23 24
  }

25 26 27 28 29 30 31 32 33 34
  /**
   * Ajax callback triggered by date.
   */
  public function dateCallback($form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $response->addCommand(new HtmlCommand('#ajax_date_value', $form_state->getValue('date')));
    $response->addCommand(new DataCommand('#ajax_date_value', 'form_state_value_date', $form_state->getValue('date')));
    return $response;
  }

35 36 37 38 39 40 41 42 43 44 45 46
  /**
   * Ajax callback triggered by datetime.
   */
  public function datetimeCallback($form, FormStateInterface $form_state) {
    $datetime = $form_state->getValue('datetime')['date'] . ' ' . $form_state->getValue('datetime')['time'];

    $response = new AjaxResponse();
    $response->addCommand(new HtmlCommand('#ajax_datetime_value', $datetime));
    $response->addCommand(new DataCommand('#ajax_datetime_value', 'form_state_value_datetime', $datetime));
    return $response;
  }

47 48 49
  /**
   * Ajax callback triggered by checkbox.
   */
50
  public function checkboxCallback($form, FormStateInterface $form_state) {
51
    $response = new AjaxResponse();
52 53
    $response->addCommand(new HtmlCommand('#ajax_checkbox_value', (int) $form_state->getValue('checkbox')));
    $response->addCommand(new DataCommand('#ajax_checkbox_value', 'form_state_value_select', (int) $form_state->getValue('checkbox')));
54
    return $response;
55
  }
56

57 58 59 60 61 62 63 64 65
  /**
   * Ajax callback to confirm image button was submitted.
   */
  public function imageButtonCallback($form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $response->addCommand(new HtmlCommand('#ajax_image_button_result', "<div id='ajax-1-more-div'>Something witty!</div>"));
    return $response;
  }

66 67 68
  /**
   * Ajax callback triggered by the checkbox in a #group.
   */
69
  public function checkboxGroupCallback($form, FormStateInterface $form_state) {
70 71 72
    return $form['checkbox_in_group_wrapper'];
  }

73
}