FormElementHelper.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace Drupal\Core\Form;
  3. use Drupal\Core\Render\Element;
  4. /**
  5. * Provides common functionality for form elements.
  6. */
  7. class FormElementHelper {
  8. /**
  9. * Retrieves a form element.
  10. *
  11. * @param string $name
  12. * The name of the form element. If the #parents property of your form
  13. * element is ['foo', 'bar', 'baz'] then the name is 'foo][bar][baz'.
  14. * @param array $form
  15. * An associative array containing the structure of the form.
  16. *
  17. * @return array
  18. * The form element.
  19. */
  20. public static function getElementByName($name, array $form) {
  21. foreach (Element::children($form) as $key) {
  22. if (implode('][', $form[$key]['#parents']) === $name) {
  23. return $form[$key];
  24. }
  25. elseif ($element = static::getElementByName($name, $form[$key])) {
  26. return $element;
  27. }
  28. }
  29. return [];
  30. }
  31. /**
  32. * Returns the title for the element.
  33. *
  34. * If the element has no title, this will recurse through all children of the
  35. * element until a title is found.
  36. *
  37. * @param array $element
  38. * An associative array containing the properties of the form element.
  39. *
  40. * @return string
  41. * The title of the element, or an empty string if none is found.
  42. */
  43. public static function getElementTitle(array $element) {
  44. $title = '';
  45. if (isset($element['#title'])) {
  46. $title = $element['#title'];
  47. }
  48. else {
  49. foreach (Element::children($element) as $key) {
  50. if ($title = static::getElementTitle($element[$key])) {
  51. break;
  52. }
  53. }
  54. }
  55. return $title;
  56. }
  57. }