RepeatedField.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace Symfony\Components\Form;
  3. /*
  4. * This file is part of the symfony package.
  5. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. /**
  11. * A field for repeated input of values
  12. *
  13. * @author Bernhard Schussek <bernhard.schussek@symfony-project.com>
  14. */
  15. class RepeatedField extends FieldGroup
  16. {
  17. /**
  18. * The prototype for the inner fields
  19. * @var FieldInterface
  20. */
  21. protected $prototype;
  22. /**
  23. * Repeats the given field twice to verify the user's input
  24. *
  25. * @param FieldInterface $innerField
  26. */
  27. public function __construct(FieldInterface $innerField, array $options = array())
  28. {
  29. $this->prototype = $innerField;
  30. parent::__construct($innerField->getKey(), $options);
  31. }
  32. /**
  33. * {@inheritDoc}
  34. */
  35. protected function configure()
  36. {
  37. $field = clone $this->prototype;
  38. $field->setKey('first');
  39. $field->setPropertyPath('first');
  40. $this->add($field);
  41. $field = clone $this->prototype;
  42. $field->setKey('second');
  43. $field->setPropertyPath('second');
  44. $this->add($field);
  45. }
  46. /**
  47. * Returns whether both entered values are equal
  48. *
  49. * @return bool
  50. */
  51. public function isFirstEqualToSecond()
  52. {
  53. return $this->get('first')->getData() === $this->get('second')->getData();
  54. }
  55. /**
  56. * Sets the values of both fields to this value
  57. *
  58. * @param mixed $data
  59. */
  60. public function setData($data)
  61. {
  62. parent::setData(array('first' => $data, 'second' => $data));
  63. }
  64. /**
  65. * Return only value of first password field.
  66. *
  67. * @return string The password.
  68. */
  69. public function getData()
  70. {
  71. if ($this->isBound() && $this->isFirstEqualToSecond()) {
  72. return $this->get('first')->getData();
  73. }
  74. return null;
  75. }
  76. }