RepeatedField.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  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. namespace Symfony\Component\Form;
  11. /**
  12. * A field for repeated input of values
  13. *
  14. * @author Bernhard Schussek <bernhard.schussek@symfony-project.com>
  15. */
  16. class RepeatedField extends FieldGroup
  17. {
  18. /**
  19. * The prototype for the inner fields
  20. * @var FieldInterface
  21. */
  22. protected $prototype;
  23. /**
  24. * Repeats the given field twice to verify the user's input
  25. *
  26. * @param FieldInterface $innerField
  27. */
  28. public function __construct(FieldInterface $innerField, array $options = array())
  29. {
  30. $this->prototype = $innerField;
  31. parent::__construct($innerField->getKey(), $options);
  32. }
  33. /**
  34. * {@inheritDoc}
  35. */
  36. protected function configure()
  37. {
  38. $this->addOption('first_key', 'first');
  39. $this->addOption('second_key', 'second');
  40. parent::configure();
  41. $field = clone $this->prototype;
  42. $field->setKey($this->getOption('first_key'));
  43. $field->setPropertyPath($this->getOption('first_key'));
  44. $this->add($field);
  45. $field = clone $this->prototype;
  46. $field->setKey($this->getOption('second_key'));
  47. $field->setPropertyPath($this->getOption('second_key'));
  48. $this->add($field);
  49. }
  50. /**
  51. * Returns whether both entered values are equal
  52. *
  53. * @return bool
  54. */
  55. public function isFirstEqualToSecond()
  56. {
  57. return $this->get($this->getOption('first_key'))->getData() === $this->get($this->getOption('second_key'))->getData();
  58. }
  59. /**
  60. * Sets the values of both fields to this value
  61. *
  62. * @param mixed $data
  63. */
  64. public function setData($data)
  65. {
  66. parent::setData(array(
  67. $this->getOption('first_key') => $data,
  68. $this->getOption('second_key') => $data
  69. ));
  70. }
  71. /**
  72. * Return only value of first password field.
  73. *
  74. * @return string The password.
  75. */
  76. public function getData()
  77. {
  78. if ($this->isBound() && $this->isFirstEqualToSecond()) {
  79. return $this->get($this->getOption('first_key'))->getData();
  80. }
  81. return null;
  82. }
  83. }