CompositeFormElementTrait.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. <?php
  2. namespace Drupal\Core\Render\Element;
  3. /**
  4. * Provides a trait for radios, checkboxes, and similar composite form elements.
  5. *
  6. * Any form element that is comprised of several distinct parts can use this
  7. * trait to add support for a composite title or description.
  8. */
  9. trait CompositeFormElementTrait {
  10. /**
  11. * Adds form element theming to an element if its title or description is set.
  12. *
  13. * This is used as a pre render function for checkboxes and radios.
  14. */
  15. public static function preRenderCompositeFormElement($element) {
  16. // Set the element's title attribute to show #title as a tooltip, if needed.
  17. if (isset($element['#title']) && $element['#title_display'] == 'attribute') {
  18. $element['#attributes']['title'] = $element['#title'];
  19. if (!empty($element['#required'])) {
  20. // Append an indication that this field is required.
  21. $element['#attributes']['title'] .= ' (' . t('Required') . ')';
  22. }
  23. }
  24. if (isset($element['#title']) || isset($element['#description'])) {
  25. // @see #type 'fieldgroup'
  26. $element['#attributes']['id'] = $element['#id'] . '--wrapper';
  27. $element['#theme_wrappers'][] = 'fieldset';
  28. $element['#attributes']['class'][] = 'fieldgroup';
  29. $element['#attributes']['class'][] = 'form-composite';
  30. }
  31. return $element;
  32. }
  33. }