$form_state->setErrorByName prevents previous $form_state updates

Created on 17 March 2020, over 4 years ago
Updated 12 July 2023, about 1 year ago

Extremely simplified example in the code below.

    $form_state->set('display_correct_cnum', TRUE);
    $form_state->setErrorByName('input', 'error');
    $form_state->setRebuild();

For some reason, the setErrorByName seems to prevent the previous set to work.
When I comment out that line, the set does work properly.

<?php

namespace Drupal\xxx\Form;

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

class TestForm extends FormBase {

  public function getFormId() {
    return 'testform';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['customer'] = [
      '#type' => 'container',
      '#attributes' => [
        'id' => ['company-fieldset'],
      ],
    ];

    $form['customer']['input'] = [
      '#type' => 'textfield',
      '#title' => 'input',
    ];

    $form['customer']['searchVAT'] = [
      '#type' => 'submit',
      '#value' => $this->t('Search'),
      '#name' => 'searchVAT',
      '#validate' => ['::validateVAT'],
      '#submit' => ['::searchVAT'],
      '#ajax' => [
        'callback' => '::searchVATCallback',
        'wrapper' => 'company-fieldset',
      ],
    ];

    $displayCheckbox = $form_state->get('display_correct_cnum');
    ksm($displayCheckbox);

    return $form;

  } // End of buildForm

  /**
   * Called when the search button for company number is clicked.
   *
   * Validates the VAT number before the submit handler is called.
   */
  public function validateVAT(array &$form, FormStateInterface $form_state) {
    $form_state->set('display_correct_cnum', TRUE);
    // commenting out the line below makes the above line work
    $form_state->setErrorByName('input', 'error');
    $form_state->setRebuild();
  }

  public function searchVAT(array &$form, FormStateInterface $form_state) {

  }

  public function searchVATCallback(array &$form, FormStateInterface $form_state) {
    return $form['customer'];
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {

  }

  public function submitForm(array &$form, FormStateInterface $form_state) {

  }

}
πŸ’¬ Support request
Status

Fixed

Version

9.4

Component
FormΒ  β†’

Last updated 1 minute ago

Created by

πŸ‡§πŸ‡ͺBelgium Pascal-

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024