HybridField.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. namespace Symfony\Component\Form;
  3. /*
  4. * This file is part of the Symfony framework.
  5. *
  6. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  7. *
  8. * This source file is subject to the MIT license that is bundled
  9. * with this source code in the file LICENSE.
  10. */
  11. use Symfony\Component\Form\Exception\FormException;
  12. /**
  13. * A field that can dynamically act like a field or like a field group
  14. *
  15. * You can use the method setFieldMode() to switch between the modes
  16. * HybridField::FIELD and HybridField::GROUP. This is useful when you want
  17. * to create a field that, depending on its configuration, can either be
  18. * a single field or a combination of different fields.
  19. *
  20. * @author Bernhard Schussek <bernhard.schussek@symfony-project.com>
  21. */
  22. class HybridField extends FieldGroup
  23. {
  24. const FIELD = 0;
  25. const GROUP = 1;
  26. protected $mode = self::FIELD;
  27. /**
  28. * Sets the current mode of the field
  29. *
  30. * Note that you can't switch modes anymore once you have added children to
  31. * this field.
  32. *
  33. * @param integer $mode One of the constants HybridField::FIELD and
  34. * HybridField::GROUP.
  35. */
  36. public function setFieldMode($mode)
  37. {
  38. if (count($this) > 0 && $mode === self::FIELD) {
  39. throw new FormException('Switching to mode FIELD is not allowed after adding nested fields');
  40. }
  41. $this->mode = $mode;
  42. }
  43. /**
  44. * {@inheritDoc}
  45. *
  46. * @throws FormException When the field is in mode HybridField::FIELD adding
  47. * subfields is not allowed
  48. */
  49. public function add(FieldInterface $field)
  50. {
  51. if ($this->mode === self::FIELD) {
  52. throw new FormException('You cannot add nested fields while in mode FIELD');
  53. }
  54. return parent::add($field);
  55. }
  56. /**
  57. * {@inheritDoc}
  58. */
  59. public function getDisplayedData()
  60. {
  61. if ($this->mode === self::GROUP) {
  62. return parent::getDisplayedData();
  63. } else {
  64. return Field::getDisplayedData();
  65. }
  66. }
  67. /**
  68. * {@inheritDoc}
  69. */
  70. public function setData($data)
  71. {
  72. if ($this->mode === self::GROUP) {
  73. parent::setData($data);
  74. } else {
  75. Field::setData($data);
  76. }
  77. }
  78. /**
  79. * {@inheritDoc}
  80. */
  81. public function bind($data)
  82. {
  83. if ($this->mode === self::GROUP) {
  84. parent::bind($data);
  85. } else {
  86. Field::bind($data);
  87. }
  88. }
  89. }