Skip to content
FormTestLimitValidationErrorsForm.php 3.03 KiB
Newer Older
<?php

namespace Drupal\form_test\Form;

use Drupal\Core\Form\FormBase;

/**
 * Builds a simple form with a button triggering partial validation.
 */
class FormTestLimitValidationErrorsForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'form_test_limit_validation_errors_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
      '#type' => 'textfield',
      '#title' => 'Title',
      '#required' => TRUE,
      '#title' => 'Test',
      '#type' => 'textfield',
      '#element_validate' => ['::elementValidateLimitValidationErrors'],
    ];
    $form['test_numeric_index'] = [
      '#title' => 'Test (numeric index)',
      '#type' => 'textfield',
      '#element_validate' => ['::elementValidateLimitValidationErrors'],
    ];
      '#title' => 'Test (substring) foo',
      '#type' => 'textfield',
      '#element_validate' => ['::elementValidateLimitValidationErrors'],
    ];
    $form['test_substring']['foobar'] = [
      '#title' => 'Test (substring) foobar',
      '#type' => 'textfield',
      '#element_validate' => ['::elementValidateLimitValidationErrors'],
    ];
      '#limit_validation_errors' => [['test']],
      '#submit' => ['::partialSubmitForm'],
    ];
    $form['actions']['partial_numeric_index'] = [
      '#limit_validation_errors' => [['test_numeric_index', 0]],
      '#submit' => ['::partialSubmitForm'],
      '#value' => t('Partial validate (numeric index)'),
      '#limit_validation_errors' => [['test_substring', 'foo']],
      '#submit' => ['::partialSubmitForm'],
      '#value' => t('Partial validate (substring)'),
      '#type' => 'submit',
      '#value' => t('Full validate'),
  public function elementValidateLimitValidationErrors($element, FormStateInterface $form_state) {
    if ($element['#value'] == 'invalid') {
      $form_state->setError($element, t('@label element is invalid', ['@label' => $element['#title']]));
  public function submitForm(array &$form, FormStateInterface $form_state) {
  public function partialSubmitForm(array &$form, FormStateInterface $form_state) {
    // The title has not been validated, thus its value - in case of the test case
    // an empty string - may not be set.
    if (!$form_state->hasValue('title') && $form_state->hasValue('test')) {
      drupal_set_message('Only validated values appear in the form values.');
    }
  }

}