File.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace Drupal\Core\Render\Element;
  3. use Drupal\Core\Form\FormStateInterface;
  4. use Drupal\Core\Render\Element;
  5. /**
  6. * Provides a form element for uploading a file.
  7. *
  8. * If you add this element to a form the enctype="multipart/form-data" attribute
  9. * will automatically be added to the form element.
  10. *
  11. * Properties:
  12. * - #multiple: A Boolean indicating whether multiple files may be uploaded.
  13. * - #size: The size of the file input element in characters.
  14. *
  15. * @FormElement("file")
  16. */
  17. class File extends FormElement {
  18. /**
  19. * {@inheritdoc}
  20. */
  21. public function getInfo() {
  22. $class = get_class($this);
  23. return [
  24. '#input' => TRUE,
  25. '#multiple' => FALSE,
  26. '#process' => [
  27. [$class, 'processFile'],
  28. ],
  29. '#size' => 60,
  30. '#pre_render' => [
  31. [$class, 'preRenderFile'],
  32. ],
  33. '#theme' => 'input__file',
  34. '#theme_wrappers' => ['form_element'],
  35. ];
  36. }
  37. /**
  38. * Processes a file upload element, make use of #multiple if present.
  39. */
  40. public static function processFile(&$element, FormStateInterface $form_state, &$complete_form) {
  41. if ($element['#multiple']) {
  42. $element['#attributes'] = ['multiple' => 'multiple'];
  43. $element['#name'] .= '[]';
  44. }
  45. return $element;
  46. }
  47. /**
  48. * Prepares a #type 'file' render element for input.html.twig.
  49. *
  50. * For assistance with handling the uploaded file correctly, see the API
  51. * provided by file.inc.
  52. *
  53. * @param array $element
  54. * An associative array containing the properties of the element.
  55. * Properties used: #title, #name, #size, #description, #required,
  56. * #attributes.
  57. *
  58. * @return array
  59. * The $element with prepared variables ready for input.html.twig.
  60. */
  61. public static function preRenderFile($element) {
  62. $element['#attributes']['type'] = 'file';
  63. Element::setAttributes($element, ['id', 'name', 'size']);
  64. static::setAttributes($element, ['js-form-file', 'form-file']);
  65. return $element;
  66. }
  67. }