Password.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 entering a password, with hidden text.
  7. *
  8. * Properties:
  9. * - #size: The size of the input element in characters.
  10. * - #pattern: A string for the native HTML5 pattern attribute.
  11. *
  12. * Usage example:
  13. * @code
  14. * $form['pass'] = array(
  15. * '#type' => 'password',
  16. * '#title' => $this->t('Password'),
  17. * '#size' => 25,
  18. * '#pattern' => '[01]+',
  19. * );
  20. * @endcode
  21. *
  22. * @see \Drupal\Core\Render\Element\PasswordConfirm
  23. * @see \Drupal\Core\Render\Element\Textfield
  24. *
  25. * @FormElement("password")
  26. */
  27. class Password extends FormElement {
  28. /**
  29. * {@inheritdoc}
  30. */
  31. public function getInfo() {
  32. $class = get_class($this);
  33. return [
  34. '#input' => TRUE,
  35. '#size' => 60,
  36. '#maxlength' => 128,
  37. '#process' => [
  38. [$class, 'processAjaxForm'],
  39. [$class, 'processPattern'],
  40. ],
  41. '#pre_render' => [
  42. [$class, 'preRenderPassword'],
  43. ],
  44. '#theme' => 'input__password',
  45. '#theme_wrappers' => ['form_element'],
  46. ];
  47. }
  48. /**
  49. * Prepares a #type 'password' render element for input.html.twig.
  50. *
  51. * @param array $element
  52. * An associative array containing the properties of the element.
  53. * Properties used: #title, #value, #description, #size, #maxlength,
  54. * #placeholder, #required, #attributes.
  55. *
  56. * @return array
  57. * The $element with prepared variables ready for input.html.twig.
  58. */
  59. public static function preRenderPassword($element) {
  60. $element['#attributes']['type'] = 'password';
  61. Element::setAttributes($element, ['id', 'name', 'size', 'maxlength', 'placeholder']);
  62. static::setAttributes($element, ['form-text']);
  63. return $element;
  64. }
  65. /**
  66. * {@inheritdoc}
  67. */
  68. public static function valueCallback(&$element, $input, FormStateInterface $form_state) {
  69. if ($input !== FALSE && $input !== NULL) {
  70. // This should be a string, but allow other scalars since they might be
  71. // valid input in programmatic form submissions.
  72. return is_scalar($input) ? (string) $input : '';
  73. }
  74. return NULL;
  75. }
  76. }