FieldGroup.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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\AlreadyBoundException;
  12. use Symfony\Component\Form\Exception\UnexpectedTypeException;
  13. use Symfony\Component\Form\Exception\DanglingFieldException;
  14. /**
  15. * FieldGroup represents an array of widgets bind to names and values.
  16. *
  17. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  18. */
  19. class FieldGroup extends Field implements \IteratorAggregate, FieldGroupInterface
  20. {
  21. /**
  22. * Contains all the fields of this group
  23. * @var array
  24. */
  25. protected $fields = array();
  26. /**
  27. * Contains the names of bound values who don't belong to any fields
  28. * @var array
  29. */
  30. protected $extraFields = array();
  31. /**
  32. * @inheritDoc
  33. */
  34. public function __construct($key, array $options = array())
  35. {
  36. $this->addOption('virtual', false);
  37. parent::__construct($key, $options);
  38. }
  39. /**
  40. * Clones this group
  41. */
  42. public function __clone()
  43. {
  44. foreach ($this->fields as $name => $field) {
  45. $field = clone $field;
  46. // this condition is only to "bypass" a PHPUnit bug with mocks
  47. if (null !== $field->getParent()) {
  48. $field->setParent($this);
  49. }
  50. $this->fields[$name] = $field;
  51. }
  52. }
  53. /**
  54. * Adds a new field to this group. A field must have a unique name within
  55. * the group. Otherwise the existing field is overwritten.
  56. *
  57. * If you add a nested group, this group should also be represented in the
  58. * object hierarchy. If you want to add a group that operates on the same
  59. * hierarchy level, use merge().
  60. *
  61. * <code>
  62. * class Entity
  63. * {
  64. * public $location;
  65. * }
  66. *
  67. * class Location
  68. * {
  69. * public $longitude;
  70. * public $latitude;
  71. * }
  72. *
  73. * $entity = new Entity();
  74. * $entity->location = new Location();
  75. *
  76. * $form = new Form('entity', $entity, $validator);
  77. *
  78. * $locationGroup = new FieldGroup('location');
  79. * $locationGroup->add(new TextField('longitude'));
  80. * $locationGroup->add(new TextField('latitude'));
  81. *
  82. * $form->add($locationGroup);
  83. * </code>
  84. *
  85. * @param FieldInterface|string $field
  86. */
  87. public function add($field)
  88. {
  89. if ($this->isBound()) {
  90. throw new AlreadyBoundException('You cannot add fields after binding a form');
  91. }
  92. // if the field is given as string, ask the field factory of the form
  93. // to create a field
  94. if (!$field instanceof FieldInterface) {
  95. if (!is_string($field)) {
  96. throw new UnexpectedTypeException($field, 'FieldInterface or string');
  97. }
  98. if (!$this->getRoot() instanceof Form) {
  99. throw new DanglingFieldException('Field groups must be added to a form before fields can be created automatically');
  100. }
  101. $factory = $this->getRoot()->getFieldFactory();
  102. if (!$factory) {
  103. throw new \LogicException('A field factory must be available for automatically creating fields');
  104. }
  105. $options = func_num_args() > 1 ? func_get_arg(1) : array();
  106. $field = $factory->getInstance($this->getData(), $field, $options);
  107. }
  108. $this->fields[$field->getKey()] = $field;
  109. $field->setParent($this);
  110. $data = $this->getTransformedData();
  111. // if the property "data" is NULL, getTransformedData() returns an empty
  112. // string
  113. if (!empty($data)) {
  114. $field->updateFromProperty($data);
  115. }
  116. return $field;
  117. }
  118. /**
  119. * Removes the field with the given key.
  120. *
  121. * @param string $key
  122. */
  123. public function remove($key)
  124. {
  125. $this->fields[$key]->setParent(null);
  126. unset($this->fields[$key]);
  127. }
  128. /**
  129. * Returns whether a field with the given key exists.
  130. *
  131. * @param string $key
  132. * @return boolean
  133. */
  134. public function has($key)
  135. {
  136. return isset($this->fields[$key]);
  137. }
  138. /**
  139. * Returns the field with the given key.
  140. *
  141. * @param string $key
  142. * @return FieldInterface
  143. */
  144. public function get($key)
  145. {
  146. if (isset($this->fields[$key])) {
  147. return $this->fields[$key];
  148. }
  149. throw new \InvalidArgumentException(sprintf('Field "%s" does not exist.', $key));
  150. }
  151. /**
  152. * Returns all fields in this group
  153. *
  154. * @return array
  155. */
  156. public function getFields()
  157. {
  158. return $this->fields;
  159. }
  160. /**
  161. * Returns an array of visible fields from the current schema.
  162. *
  163. * @return array
  164. */
  165. public function getVisibleFields()
  166. {
  167. return $this->getFieldsByVisibility(false, false);
  168. }
  169. /**
  170. * Returns an array of visible fields from the current schema.
  171. *
  172. * This variant of the method will recursively get all the
  173. * fields from the nested forms or field groups
  174. *
  175. * @return array
  176. */
  177. public function getAllVisibleFields()
  178. {
  179. return $this->getFieldsByVisibility(false, true);
  180. }
  181. /**
  182. * Returns an array of hidden fields from the current schema.
  183. *
  184. * @return array
  185. */
  186. public function getHiddenFields()
  187. {
  188. return $this->getFieldsByVisibility(true, false);
  189. }
  190. /**
  191. * Returns an array of hidden fields from the current schema.
  192. *
  193. * This variant of the method will recursively get all the
  194. * fields from the nested forms or field groups
  195. *
  196. * @return array
  197. */
  198. public function getAllHiddenFields()
  199. {
  200. return $this->getFieldsByVisibility(true, true);
  201. }
  202. /**
  203. * Returns a filtered array of fields from the current schema.
  204. *
  205. * @param boolean $hidden Whether to return hidden fields only or visible fields only
  206. * @param boolean $recursive Whether to recur through embedded schemas
  207. *
  208. * @return array
  209. */
  210. protected function getFieldsByVisibility($hidden, $recursive)
  211. {
  212. $fields = array();
  213. $hidden = (bool)$hidden;
  214. foreach ($this->fields as $field) {
  215. if ($field instanceof FieldGroup && $recursive) {
  216. $fields = array_merge($fields, $field->getFieldsByVisibility($hidden, $recursive));
  217. } else if ($hidden === $field->isHidden()) {
  218. $fields[] = $field;
  219. }
  220. }
  221. return $fields;
  222. }
  223. /**
  224. * Initializes the field group with an object to operate on
  225. *
  226. * @see FieldInterface
  227. */
  228. public function setData($data)
  229. {
  230. parent::setData($data);
  231. // get transformed data and pass its values to child fields
  232. $data = $this->getTransformedData();
  233. if (!empty($data) && !is_array($data) && !is_object($data)) {
  234. throw new \InvalidArgumentException(sprintf('Expected argument of type object or array, %s given', gettype($data)));
  235. }
  236. if (!empty($data)) {
  237. $this->updateFromObject($data);
  238. }
  239. }
  240. /**
  241. * Returns the data of the field as it is displayed to the user.
  242. *
  243. * @see FieldInterface
  244. */
  245. public function getDisplayedData()
  246. {
  247. $values = array();
  248. foreach ($this->fields as $key => $field) {
  249. $values[$key] = $field->getDisplayedData();
  250. }
  251. return $values;
  252. }
  253. /**
  254. * Binds POST data to the field, transforms and validates it.
  255. *
  256. * @param string|array $taintedData The POST data
  257. * @return boolean Whether the form is valid
  258. */
  259. public function bind($taintedData)
  260. {
  261. if (null === $taintedData) {
  262. $taintedData = array();
  263. }
  264. if (!is_array($taintedData)) {
  265. throw new UnexpectedTypeException($taintedData, 'array');
  266. }
  267. foreach ($this->fields as $key => $field) {
  268. if (!isset($taintedData[$key])) {
  269. $taintedData[$key] = null;
  270. }
  271. }
  272. $taintedData = $this->preprocessData($taintedData);
  273. foreach ($taintedData as $key => $value) {
  274. if ($this->has($key)) {
  275. $this->fields[$key]->bind($value);
  276. }
  277. }
  278. $data = $this->getTransformedData();
  279. $this->updateObject($data);
  280. // bind and reverse transform the data
  281. parent::bind($data);
  282. $this->extraFields = array();
  283. foreach ($taintedData as $key => $value) {
  284. if (!$this->has($key)) {
  285. $this->extraFields[] = $key;
  286. }
  287. }
  288. }
  289. /**
  290. * Updates the chield fields from the properties of the given data
  291. *
  292. * This method calls updateFromProperty() on all child fields that have a
  293. * property path set. If a child field has no property path set but
  294. * implements FieldGroupInterface, updateProperty() is called on its
  295. * children instead.
  296. *
  297. * @param array|object $objectOrArray
  298. */
  299. protected function updateFromObject(&$objectOrArray)
  300. {
  301. $iterator = new RecursiveFieldIterator($this);
  302. $iterator = new \RecursiveIteratorIterator($iterator);
  303. foreach ($iterator as $field) {
  304. $field->updateFromProperty($objectOrArray);
  305. }
  306. }
  307. /**
  308. * Updates all properties of the given data from the child fields
  309. *
  310. * This method calls updateProperty() on all child fields that have a property
  311. * path set. If a child field has no property path set but implements
  312. * FieldGroupInterface, updateProperty() is called on its children instead.
  313. *
  314. * @param array|object $objectOrArray
  315. */
  316. protected function updateObject(&$objectOrArray)
  317. {
  318. $iterator = new RecursiveFieldIterator($this);
  319. $iterator = new \RecursiveIteratorIterator($iterator);
  320. foreach ($iterator as $field) {
  321. $field->updateProperty($objectOrArray);
  322. }
  323. }
  324. /**
  325. * Processes the bound data before it is passed to the individual fields
  326. *
  327. * The data is in the user format.
  328. *
  329. * @param array $data
  330. * @return array
  331. */
  332. protected function preprocessData(array $data)
  333. {
  334. return $data;
  335. }
  336. /**
  337. * @inheritDoc
  338. */
  339. public function isVirtual()
  340. {
  341. return $this->getOption('virtual');
  342. }
  343. /**
  344. * Returns whether this form was bound with extra fields
  345. *
  346. * @return boolean
  347. */
  348. public function isBoundWithExtraFields()
  349. {
  350. // TODO: integrate the field names in the error message
  351. return count($this->extraFields) > 0;
  352. }
  353. /**
  354. * Returns whether the field is valid.
  355. *
  356. * @return boolean
  357. */
  358. public function isValid()
  359. {
  360. if (!parent::isValid()) {
  361. return false;
  362. }
  363. foreach ($this->fields as $field) {
  364. if (!$field->isValid()) {
  365. return false;
  366. }
  367. }
  368. return true;
  369. }
  370. /**
  371. * {@inheritDoc}
  372. */
  373. public function addError(FieldError $error, PropertyPathIterator $pathIterator = null, $type = null)
  374. {
  375. if (null !== $pathIterator) {
  376. if ($type === self::FIELD_ERROR && $pathIterator->hasNext()) {
  377. $pathIterator->next();
  378. if ($pathIterator->isProperty() && $pathIterator->current() === 'fields') {
  379. $pathIterator->next();
  380. }
  381. if ($this->has($pathIterator->current()) && !$this->get($pathIterator->current())->isHidden()) {
  382. $this->get($pathIterator->current())->addError($error, $pathIterator, $type);
  383. return;
  384. }
  385. } else if ($type === self::DATA_ERROR) {
  386. $iterator = new RecursiveFieldIterator($this);
  387. $iterator = new \RecursiveIteratorIterator($iterator);
  388. foreach ($iterator as $field) {
  389. if (null !== ($fieldPath = $field->getPropertyPath())) {
  390. if ($fieldPath->getElement(0) === $pathIterator->current() && !$field->isHidden()) {
  391. if ($pathIterator->hasNext()) {
  392. $pathIterator->next();
  393. }
  394. $field->addError($error, $pathIterator, $type);
  395. return;
  396. }
  397. }
  398. }
  399. }
  400. }
  401. parent::addError($error);
  402. }
  403. /**
  404. * Returns whether the field requires a multipart form.
  405. *
  406. * @return boolean
  407. */
  408. public function isMultipart()
  409. {
  410. foreach ($this->fields as $field) {
  411. if ($field->isMultipart()) {
  412. return true;
  413. }
  414. }
  415. return false;
  416. }
  417. /**
  418. * Returns true if the bound field exists (implements the \ArrayAccess interface).
  419. *
  420. * @param string $key The key of the bound field
  421. *
  422. * @return Boolean true if the widget exists, false otherwise
  423. */
  424. public function offsetExists($key)
  425. {
  426. return $this->has($key);
  427. }
  428. /**
  429. * Returns the form field associated with the name (implements the \ArrayAccess interface).
  430. *
  431. * @param string $key The offset of the value to get
  432. *
  433. * @return Field A form field instance
  434. */
  435. public function offsetGet($key)
  436. {
  437. return $this->get($key);
  438. }
  439. /**
  440. * Throws an exception saying that values cannot be set (implements the \ArrayAccess interface).
  441. *
  442. * @param string $offset (ignored)
  443. * @param string $value (ignored)
  444. *
  445. * @throws \LogicException
  446. */
  447. public function offsetSet($key, $field)
  448. {
  449. throw new \LogicException('Use the method add() to add fields');
  450. }
  451. /**
  452. * Throws an exception saying that values cannot be unset (implements the \ArrayAccess interface).
  453. *
  454. * @param string $key
  455. *
  456. * @throws \LogicException
  457. */
  458. public function offsetUnset($key)
  459. {
  460. return $this->remove($key);
  461. }
  462. /**
  463. * Returns the iterator for this group.
  464. *
  465. * @return \ArrayIterator
  466. */
  467. public function getIterator()
  468. {
  469. return new \ArrayIterator($this->fields);
  470. }
  471. /**
  472. * Returns the number of form fields (implements the \Countable interface).
  473. *
  474. * @return integer The number of embedded form fields
  475. */
  476. public function count()
  477. {
  478. return count($this->fields);
  479. }
  480. }