3

I want to see all the values in my edit form, I tried dsm($form_state->getValues()) but i dont get anything.
if I do dsm($form_state) I get a huge amoung of things too much to look through.

what is the correct syntax to get just values in my form in the edit page.

  • Edited answer for an alternative way – chadpeppers Jun 14 '17 at 21:30
  • $form_state->getFormObject()->getEntity()->getData() And you can use getElementData('your_field') – batMask Sep 24 '18 at 13:41
9

The form_state->getValues() only works during the validation and submit process. Instead you need to look to the $form variable for values. Unfortunately you cannot get all the values easily you must dig into the form itself:

$form['title']['widget'][0]['value']['default_value'];

EDIT I was looking into this more and there may be a cleaner way.

First you must get the form object from the $form_state variable. From there you can use the function getEntity() to actually get the entity that the form is editing. Then if you want to get a value you can use the get('field_name') method or if you want all the values use toArray()

// Get the entire node as an array and will include all values
$node = $form_state->getFormObject()->getEntity()->toArray();

or

// Get the entity object
$node = $form_state->getFormObject()->getEntity();

// Get the field
$node->get('field_my_field');

// Get the field as a string (returns value)
$node->get('field_my_field')->getString();
| improve this answer | |
  • It seems like getFormObject() doesn't return a type that implements getEntity(), so the method cannot be called. Am I missing something? – Ynhockey Jan 16 '19 at 10:24
  • @Ynhockey pretty sure you need to reference Drupal\Core\Form\FormStateInterface in your form alter declaration to access that method. ie. use Drupal\Core\Form\FormStateInterface; function module_form_alter(&$form, FormStateInterface &$form_state, $form_id) { ... } – redbrickone Dec 2 '19 at 19:49
0

If I understand the question correctly, a short way to do it is by passing an empty array to getValue(). For example:

$form_values = $form_state->getValue(array());

This will also return stuff like object elements, but it shouldn't be difficult to trim it to only the values to want.

| improve this answer | |

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