public static function RenderElement::setAttributes

public static RenderElement::setAttributes(&$element, $class = array())

Sets a form element's class attribute.

Adds 'required' and 'error' classes as needed.

Parameters

array $element: The form element.

array $class: Array of new class names to be added.

Overrides ElementInterface::setAttributes

File

core/lib/Drupal/Core/Render/Element/RenderElement.php, line 129

Class

RenderElement
Provides a base class for render element plugins.

Namespace

Drupal\Core\Render\Element

Code

public static function setAttributes(&$element, $class = array()) {
  if (!empty($class)) {
    if (!isset($element['#attributes']['class'])) {
      $element['#attributes']['class'] = array();
    }
    $element['#attributes']['class'] = array_merge($element['#attributes']['class'], $class);
  }
  // This function is invoked from form element theme functions, but the
  // rendered form element may not necessarily have been processed by
  // \Drupal::formBuilder()->doBuildForm().
  if (!empty($element['#required'])) {
    $element['#attributes']['class'][] = 'required';
    $element['#attributes']['required'] = 'required';
    $element['#attributes']['aria-required'] = 'true';
  }
  if (isset($element['#parents']) && isset($element['#errors']) && !empty($element['#validated'])) {
    $element['#attributes']['class'][] = 'error';
    $element['#attributes']['aria-invalid'] = 'true';
  }
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!Element!RenderElement.php/function/RenderElement::setAttributes/8.1.x