2

I need to track previous values of a few form elements on a form to detect when they change to invalidate some other options on the page. Essentially, if the value of these fields change a field that controls pagination should reset.

I'm trying to accomplish this with this:

$values = $form_state->getValues();
$form['element1'] = [
      '#type' => 'radios',
      '#title' => $this->t('Element 1'),
      '#options' => [
        // Omitted for brevity
      ],
      '#weight' => '0',
      '#ajax' => [
        'callback' => [$this, 'my_callback'],
        'disable-refocus' => true
      ]
    ];

// dump($values['element1']);
$form['element1_previous'] = [
      '#type' => 'value',
      '#value' => (isset($values['element1'])) ? $values['element1'] : 'none',
    ];

No matter what I do the value of $values['element1_previous] is none. If I uncomment the dump() statement right before it I can see the value of $values['element1'] changing each time AJAX is submitted so the value is there.

If I do something like:

$form['element1_previous'] = [
          '#type' => 'value',
          '#value' => rand()
        ];

I can see $values['element1_previous'] being set to a different integer each AJAX submission. I just can't assign the value of $form['element1'] to that field.

What am I doing wrong? Is there a better way I could handle this?

1

This:

(isset($values['element1']))

will always return TRUE, since the form element exists, and therefore a value is always passed to the submit hander, even when the value is empty.

You likely want this:

!empty($values['element1'])
| improve this answer | |
  • Yes, !empty() is a better check in this case. Be aware that empty() returns FALSE if var exists and has a non-empty, non-zero value, otherwise returns TRUE. This is super useful but can have unpredictable side effects. As always, php.net will have the whole story: php.net/manual/en/function.empty.php – hotwebmatter May 28 at 5:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.