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