Drupal - $form_state->setValue() doesn't save value

If it is a custom variable, you should use $form_state->set('property_name', 'value') (instead of "$form_state->setValue(...)").

Example:

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

    // Update custom variable (in PHP "null + 1" equals one)
    $form_state->set('my_variable', $form_state->get('my_variable') + 1);

    // Below is only required when your "buildForm(...)" depends on the variable
    $form_state->setRebuild();
}


Just to add if you'd like to actually save a form value. I do the following when using webform, I imagine it's easily modified for a usual form.

$form['elements']['form_element']['#default_value'] = 'my_value'

Tags:

Forms

8