By the time submitForm() runs, every value the user typed is already sitting inside $form_state — Drupal collected it all during the request. This lesson is about the one method you'll use constantly to get that data back out: $form_state->getValue(), plus its variations for nested and multi-value fields.
What you'll learn in this lesson
- The basic form of
getValue()for a top-level field - How to read a value nested inside a fieldset or container
- The difference between
getValue()andgetValues()
Reading a simple field
$title = $form_state->getValue('title');
The string you pass matches the form element's array key — if you built the field as $form['title'] = [...], you read it back with getValue('title'). This is true no matter what #type the element was; text fields, selects, checkboxes, and dates all come back through the same method.
Reading a nested value
$email = $form_state->getValue(['contact_details', 'email']);
If a field lives inside a fieldset or container — say $form['contact_details']['email'] — pass an array of keys describing the path, from outermost to innermost, instead of a single string. This only works correctly if $form['#tree'] = TRUE; was set when the form was built; without it, Drupal flattens nested values to the top level and the array-path lookup won't find anything.
Getting everything at once
$all_values = $form_state->getValues();
Note the plural. getValues() (no arguments) returns the entire submitted values array in one call — useful when you're about to pass the whole thing to something like an entity's set() calls in a loop, rather than pulling out fields one at a time.
'0', not PHP false or null. If you write if ($form_state->getValue('agree')) {...} that still works correctly in PHP (since '0' is falsy), but a strict comparison like === FALSE will silently never match. Use loose comparison or explicitly check == '0'/== '1' for checkbox values.Quick check: a form has a
datefield nested inside a fieldset calledevent_details, and the form set#tree = TRUE. What's the correct call to read it?$form_state->getValue(['event_details', 'date'])— an array path matching the nesting, only reliable because#treewas set.
Key takeaways
$form_state->getValue('key')reads one top-level field by its array key.$form_state->getValue(['parent', 'child'])reads a nested field — only reliable when the form set#tree = TRUE.$form_state->getValues()(plural, no arguments) returns every submitted value at once.- A checkbox's unchecked value is the string
'0'— avoid strict boolean comparisons against it.
Coming up next
Once you've read the submitted values, the next natural step is sending the user somewhere useful. The next lesson covers setRedirect() — controlling exactly where a visitor lands after a successful submission.