Dropbutton.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace Drupal\Core\Render\Element;
  3. /**
  4. * Provides a render element for a set of links rendered as a drop-down button.
  5. *
  6. * By default, this element sets #theme so that the 'links' theme hook is used
  7. * for rendering, with suffixes so that themes can override this specifically
  8. * without overriding all links theming. If the #subtype property is provided in
  9. * your render array with value 'foo', #theme is set to links__dropbutton__foo;
  10. * if not, it's links__dropbutton; both of these can be overridden by setting
  11. * the #theme property in your render array. See template_preprocess_links()
  12. * for documentation on the other properties used in theming; for instance, use
  13. * element property #links to provide $variables['links'] for theming.
  14. *
  15. * Properties:
  16. * - #links: An array of links to actions. See template_preprocess_links() for
  17. * documentation the properties of links in this array.
  18. *
  19. * Usage Example:
  20. * @code
  21. * $form['actions']['extra_actions'] = array(
  22. * '#type' => 'dropbutton',
  23. * '#links' => array(
  24. * 'simple_form' => array(
  25. * 'title' => $this->t('Simple Form'),
  26. * 'url' => Url::fromRoute('fapi_example.simple_form'),
  27. * ),
  28. * 'demo' => array(
  29. * 'title' => $this->t('Build Demo'),
  30. * 'url' => Url::fromRoute('fapi_example.build_demo'),
  31. * ),
  32. * ),
  33. * );
  34. * @endcode
  35. *
  36. * @see \Drupal\Core\Render\Element\Operations
  37. *
  38. * @RenderElement("dropbutton")
  39. */
  40. class Dropbutton extends RenderElement {
  41. /**
  42. * {@inheritdoc}
  43. */
  44. public function getInfo() {
  45. $class = get_class($this);
  46. return [
  47. '#pre_render' => [
  48. [$class, 'preRenderDropbutton'],
  49. ],
  50. '#theme' => 'links__dropbutton',
  51. ];
  52. }
  53. /**
  54. * Pre-render callback: Attaches the dropbutton library and required markup.
  55. */
  56. public static function preRenderDropbutton($element) {
  57. $element['#attached']['library'][] = 'core/drupal.dropbutton';
  58. $element['#attributes']['class'][] = 'dropbutton';
  59. if (!isset($element['#theme_wrappers'])) {
  60. $element['#theme_wrappers'] = [];
  61. }
  62. array_unshift($element['#theme_wrappers'], 'dropbutton_wrapper');
  63. // Enable targeted theming of specific dropbuttons (e.g., 'operations' or
  64. // 'operations__node').
  65. if (isset($element['#subtype'])) {
  66. $element['#theme'] .= '__' . $element['#subtype'];
  67. }
  68. return $element;
  69. }
  70. }