Drupal 8: Notate element path for the form states

Drupal 8 Form API supports form states, that allow to ad jQuery behaviors with form API. To do that, however, you need to convert the element's parents array into the notation like field_body[0][subform]. This utility function concatenates the element's parents array into the required notation.

<?php

/**
 * Get the notated element path.
 *
 * @param array $element
 *   Form element.
 *
 * @return string
 *   Concatenated and notated path like "field[0][subform]".
 */
function _get_element_path_notated(array $element) {
 
$parents = $element['subform']['#parents'];
 
$widget_path = array_shift($parents);
  foreach (
$parents as $parent) {
   
$widget_path .= "[$parent]";
  }

  return
$widget_path;
}

?>