Drupal 8: Get widget state

When working with the hook altering the widget form, you often need to get the widget state to get the entities behind the form as well as additional information that is stored in the state. Here is the utility function for it.


use Drupal\Core\Form\FormStateInterface;

 * Get the widget state.
 * @param array $element
 *   Widget element.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   Form state object.
 * @return array
 *   Widget state.
function get_widget_state(array $element, FormStateInterface $form_state) {
$parents = array_slice($element['subform']['#parents'], 0, -2);
$storage_parents = array_merge(['field_storage', '#parents'], $element['#field_parents'], ['#fields'], [end($parents)]);
NestedArray::getValue($form_state->getStorage(), $storage_parents);