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

namespace Drupal\form_test;

5 6
use Drupal\Core\Form\FormStateInterface;

7
/**
8
 * Simple class for testing methods as Form API callbacks.
9 10 11 12 13 14
 */
class Callbacks {

  /**
   * Form element validation handler for 'name' in form_test_validate_form().
   */
15
  public function validateName(&$element, FormStateInterface $form_state) {
16
    $triggered = FALSE;
17
    if ($form_state->getValue('name') == 'element_validate') {
18 19 20
      // Alter the form element.
      $element['#value'] = '#value changed by #element_validate';
      // Alter the submitted value in $form_state.
21
      $form_state->setValueForElement($element, 'value changed by setValueForElement() in #element_validate');
22 23 24

      $triggered = TRUE;
    }
25
    if ($form_state->getValue('name') == 'element_validate_access') {
26
      $form_state->set('form_test_name', $form_state->getValue('name'));
27 28 29 30 31
      // Alter the form element.
      $element['#access'] = FALSE;

      $triggered = TRUE;
    }
32
    elseif ($form_state->has('form_test_name')) {
33
      // To simplify this test, just take over the element's value into $form_state.
34
      $form_state->setValueForElement($element, $form_state->get('form_test_name'));
35 36 37 38 39 40

      $triggered = TRUE;
    }

    if ($triggered) {
      // Output the element's value from $form_state.
41
      drupal_set_message(t('@label value: @value', ['@label' => $element['#title'], '@value' => $form_state->getValue('name')]));
42 43

      // Trigger a form validation error to see our changes.
44
      $form_state->setErrorByName('');
45 46
    }
  }
47

48
}