0

I have a form which is built using some data which is partially random. Unfortunately, at the first AJAX call (nothing has been submitted yet, neither AJAX, nor in the normal way) the form will be rebuilt so that all random inputs are lost. Is there any way to avoid it?

class AjaxTestForm extends FormBase {

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

  public function buildForm(array $form, FormStateInterface $form_state) {
    $options = $this->_getOptions();
    $form['select'] = [
      '#type' => 'select',
      '#title' => 'Select',
      '#options' => $options,
      '#ajax' => [
        'callback' => [$this, 'ajaxCallback'],
      ],
      '#empty_option' => 'Please select',
      '#required' => TRUE,
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => 'Save',
    ];
    $form_state->set('ajaxoptions', $options);
    return $form;
  }

  private function _getOptions()
  {
    // Actually data from an external Controller
    // But those, too, are random
    $options = [
      mt_rand(1000, 9999),
      mt_rand(1000, 9999),
      mt_rand(1000, 9999),
    ];
    return $options;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Do nothing
  }

  public function ajaxCallback($form, $form_state)
  {
    print_r($form_state->getValue('select'));
    echo "\n";
    print_r($form['select']['#options']);
    print_r($form_state->get('ajaxoptions'));
  }

}

When the user selects an option, in the Ajax callback (or Ajax submit, if I had one) I can't know which options were originally in the select box available. Is there any way to preserve that information?

  • I think it's clear from the code, but it's better to add it's Drupal 8. – Attus Feb 6 '18 at 13:36
  • Why print statements? Use xdebug – Kevin Feb 6 '18 at 14:12
-1

Get the value from:

$_temp_var_ = $form_state->getUserInput('_field_name_');

Use getUserInput() instead of getValue().

And then set the value to:

$form['_field_name_'] = $_temp_var_;

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.