1

I added a submit function in the form_alter hook when inserting a node:

$form['actions']['save_as_draft'] = [
  '#type' => 'submit',
  '#value' => t('Save as Draft'),
  '#submit' => ['save_as_draft'],
  '#limit_validation_errors' => [],
];

In the save_as_draft() function, I want to get the address value from the form state, but there are no values (except for the additional submit button).

function save_as_draft(&$form, Drupal\Core\Form\FormStateInterface $form_state) {
  var_dump($form_state->getValue('field_address'));                      // outputs NULL
  var_dump($form_state->get('field_address'));                           // outputs NULL 
  var_dump($form['field_address']['widget'][0]['value']['#value']);      // outputs 'Address value'
  var_dump(array_keys($form_state->getValues())); // outputs { [0]=>  "save_as_draft" [1]=> "op" }
}

How can I get the form_state values in this alternative submit function without validating the whole form?

Is there another way of retrieving the form values instead of digging through the widget arrays?

2
  • did you try $form_state->getValues() to see all values ?
    – berramou
    Sep 24, 2020 at 11:00
  • @berramou yes, this is the last var_dump. The getUserInput() works, but still a bit mixed structure I guess
    – NeonBlank
    Sep 24, 2020 at 11:08

3 Answers 3

1

Entity forms usually run as first submit handler the entity builder functions. Then following submit handlers can get the processed field values directly from the form object entity:

$entity = $form_state->getFormObject()->getEntity();
$field_values = $entity->field_foo->getValue();
1
  • With this particular question's setup, this doesn't work. All the entity values are 0 when adding a new page for example.
    – No Sssweat
    Sep 28, 2020 at 5:20
0

the correct $form_state get value should be

*recommended* : $form_state->getValue('key'); 
or
$form_state->getValues()['key']
0

How can I get the form_state values in this alternative submit function without validating the whole form?

$form['actions']['save_as_draft'] = [
  '#type' => 'submit',
  '#value' => t('Save as Draft'),
  '#submit' => ['::submitForm', '::save'],
];
array_unshift($form['#validate'], 'save_as_draft'); // adds a custom validate that runs before the default node validate.

Now this should work

function save_as_draft(&$form, Drupal\Core\Form\FormStateInterface $form_state) {
  if ($form_state->getTriggeringElement()['#parents'][0] == 'save_as_draft') { // check Save As Draft button was clicked
    var_dump($form_state->getValue('field_address')); 
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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