CollectionField.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace Symfony\Components\Form;
  3. use Symfony\Components\Form\FieldInterface;
  4. use Symfony\Components\Form\Exception\UnexpectedTypeException;
  5. /*
  6. * This file is part of the symfony package.
  7. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  8. *
  9. * For the full copyright and license information, please view the LICENSE
  10. * file that was distributed with this source code.
  11. */
  12. /**
  13. * @package symfony
  14. * @subpackage form
  15. * @author Bernhard Schussek <bernhard.schussek@symfony-project.com>
  16. * @version SVN: $Id: FieldGroup.php 79 2009-12-08 12:53:15Z bernhard $
  17. */
  18. class CollectionField extends FieldGroup
  19. {
  20. /**
  21. * The prototype for the inner fields
  22. * @var FieldInterface
  23. */
  24. protected $prototype;
  25. /**
  26. * Repeats the given field twice to verify the user's input
  27. *
  28. * @param FieldInterface $innerField
  29. */
  30. public function __construct(FieldInterface $innerField, array $options = array())
  31. {
  32. $this->prototype = $innerField;
  33. parent::__construct($innerField->getKey(), $options);
  34. }
  35. protected function configure()
  36. {
  37. $this->addOption('modifiable', false);
  38. if ($this->getOption('modifiable')) {
  39. $field = $this->newField('$$key$$', null);
  40. // TESTME
  41. $field->setRequired(false);
  42. $this->add($field);
  43. }
  44. }
  45. public function setData($collection)
  46. {
  47. if (!is_array($collection) && !$collection instanceof \Traversable) {
  48. throw new UnexpectedTypeException('The data must be an array');
  49. }
  50. foreach ($collection as $name => $value) {
  51. $this->add($this->newField($name, $name));
  52. }
  53. parent::setData($collection);
  54. }
  55. public function bind($taintedData)
  56. {
  57. if (is_null($taintedData)) {
  58. $taintedData = array();
  59. }
  60. foreach ($this as $name => $field) {
  61. if (!isset($taintedData[$name]) && $this->getOption('modifiable') && $name != '$$key$$') {
  62. $this->remove($name);
  63. }
  64. }
  65. foreach ($taintedData as $name => $value) {
  66. if (!isset($this[$name]) && $this->getOption('modifiable')) {
  67. $this->add($this->newField($name, $name));
  68. }
  69. }
  70. return parent::bind($taintedData);
  71. }
  72. protected function newField($key, $propertyPath)
  73. {
  74. $field = clone $this->prototype;
  75. $field->setKey($key);
  76. $field->setPropertyPath($propertyPath === null ? null : '['.$propertyPath.']');
  77. return $field;
  78. }
  79. }