Custom FormElement with AJAX does not persist FormState

Created on 12 June 2018, about 6 years ago
Updated 6 September 2024, 2 days ago

I'm creating a custom FormElement that uses AJAX, however, when adding some data through $form_state->set('foo', 'bar'), the data is not persisted when the AJAX is triggered again. When pasting my code into a normal Form, it works as expected.

public static function process(array &$element, FormStateInterface $form_state, array &$complete_form) {
    $element['add'] = [
      '#type' => 'button',
      '#value' => t('Add'),
      '#ajax' => [
        'callback' => [self::class, 'ajaxCallback'],
      ],
    ];

    // Always empty
    $form_state->get('foo');

    // I'm writing pseudo-code here, never mind the condition in the if statement...
    if ($form_state->getTriggeringElement() == $element['add']) {
        // 'bar' is set, but isn't there when calling $form_state->get('foo') when 
        // AJAX is triggered for a second time.
        // Moving this code to [self::class, 'ajaxCallback'] does not help either.
        $form_state->set('foo', 'bar');
    }

Is this normal behavior or a bug? How do I make this work?

πŸ’¬ Support request
Status

Closed: outdated

Version

11.0 πŸ”₯

Component
FormΒ  β†’

Last updated 1 minute ago

Created by

πŸ‡§πŸ‡ͺBelgium Bart Vanhoutte

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.

  • πŸ‡¨πŸ‡¦Canada No Sssweat

    I am also experiencing this.

  • Status changed to Closed: outdated 2 days ago
  • πŸ‡³πŸ‡ΏNew Zealand quietone New Zealand

    As explained in #7 there are better places than the core issue queue to get support.

    The Drupal Core issue queue is not the ideal place for support requests. The 'support request' option is there for filing support issues for contributed modules and themes. There are several support options listed on our support page β†’ (Community > Support at the top of Drupal.org) and there is Drupal Slack β†’ . You may get better replies in one of those places.

Production build 0.71.5 2024