Form.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.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. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\FileBag;
  13. use Symfony\Component\Form\Event\DataEvent;
  14. use Symfony\Component\Form\Event\FilterDataEvent;
  15. use Symfony\Component\Form\Exception\FormException;
  16. use Symfony\Component\Form\Exception\MissingOptionsException;
  17. use Symfony\Component\Form\Exception\AlreadyBoundException;
  18. use Symfony\Component\Form\Exception\UnexpectedTypeException;
  19. use Symfony\Component\Form\Exception\DanglingFieldException;
  20. use Symfony\Component\Form\Exception\FieldDefinitionException;
  21. use Symfony\Component\Form\CsrfProvider\CsrfProviderInterface;
  22. use Symfony\Component\Form\DataTransformer\DataTransformerInterface;
  23. use Symfony\Component\Form\DataTransformer\TransformationFailedException;
  24. use Symfony\Component\Form\DataMapper\DataMapperInterface;
  25. use Symfony\Component\Form\Validator\FormValidatorInterface;
  26. use Symfony\Component\Form\Renderer\FormRendererInterface;
  27. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  28. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  29. /**
  30. * Form represents a form.
  31. *
  32. * A form is composed of a validator schema and a widget form schema.
  33. *
  34. * Form also takes care of CSRF protection by default.
  35. *
  36. * A CSRF secret can be any random string. If set to false, it disables the
  37. * CSRF protection, and if set to null, it forces the form to use the global
  38. * CSRF secret. If the global CSRF secret is also null, then a random one
  39. * is generated on the fly.
  40. *
  41. * To implement your own form fields, you need to have a thorough understanding
  42. * of the data flow within a form field. A form field stores its data in three
  43. * different representations:
  44. *
  45. * (1) the format required by the form's object
  46. * (2) a normalized format for internal processing
  47. * (3) the format used for display
  48. *
  49. * A date field, for example, may store a date as "Y-m-d" string (1) in the
  50. * object. To facilitate processing in the field, this value is normalized
  51. * to a DateTime object (2). In the HTML representation of your form, a
  52. * localized string (3) is presented to and modified by the user.
  53. *
  54. * In most cases, format (1) and format (2) will be the same. For example,
  55. * a checkbox field uses a Boolean value both for internal processing as for
  56. * storage in the object. In these cases you simply need to set a value
  57. * transformer to convert between formats (2) and (3). You can do this by
  58. * calling setClientTransformer() in the configure() method.
  59. *
  60. * In some cases though it makes sense to make format (1) configurable. To
  61. * demonstrate this, let's extend our above date field to store the value
  62. * either as "Y-m-d" string or as timestamp. Internally we still want to
  63. * use a DateTime object for processing. To convert the data from string/integer
  64. * to DateTime you can set a normalization transformer by calling
  65. * setNormTransformer() in configure(). The normalized data is then
  66. * converted to the displayed data as described before.
  67. *
  68. * @author Fabien Potencier <fabien@symfony.com>
  69. * @author Bernhard Schussek <bernhard.schussek@symfony.com>
  70. */
  71. class Form implements \IteratorAggregate, FormInterface
  72. {
  73. /**
  74. * Contains all the children of this group
  75. * @var array
  76. */
  77. private $children = array();
  78. private $dataMapper;
  79. private $errors = array();
  80. private $errorBubbling;
  81. private $name = '';
  82. private $parent;
  83. private $bound = false;
  84. private $required;
  85. private $data;
  86. private $normData;
  87. private $clientData;
  88. /**
  89. * Contains the names of bound values who don't belong to any children
  90. * @var array
  91. */
  92. private $extraData = array();
  93. private $normTransformer;
  94. private $clientTransformer;
  95. private $synchronized = true;
  96. private $validators;
  97. private $renderer;
  98. private $readOnly = false;
  99. private $dispatcher;
  100. private $attributes;
  101. private $types;
  102. public function __construct($name, array $types,
  103. EventDispatcherInterface $dispatcher,
  104. FormRendererInterface $renderer = null, DataTransformerInterface $clientTransformer = null,
  105. DataTransformerInterface $normTransformer = null,
  106. DataMapperInterface $dataMapper = null, array $validators = array(),
  107. $required = false, $readOnly = false, $errorBubbling = false,
  108. array $attributes = array())
  109. {
  110. foreach ($validators as $validator) {
  111. if (!$validator instanceof FormValidatorInterface) {
  112. throw new UnexpectedTypeException($validator, 'Symfony\Component\Form\Validator\FormValidatorInterface');
  113. }
  114. }
  115. $this->name = (string)$name;
  116. $this->types = $types;
  117. $this->dispatcher = $dispatcher;
  118. $this->renderer = $renderer;
  119. $this->clientTransformer = $clientTransformer;
  120. $this->normTransformer = $normTransformer;
  121. $this->validators = $validators;
  122. $this->dataMapper = $dataMapper;
  123. $this->required = $required;
  124. $this->readOnly = $readOnly;
  125. $this->attributes = $attributes;
  126. $this->errorBubbling = $errorBubbling;
  127. if ($renderer) {
  128. $renderer->setForm($this);
  129. }
  130. $this->setData(null);
  131. }
  132. public function __clone()
  133. {
  134. foreach ($this->children as $key => $child) {
  135. $this->children[$key] = clone $child;
  136. }
  137. }
  138. /**
  139. * {@inheritDoc}
  140. */
  141. public function getName()
  142. {
  143. return $this->name;
  144. }
  145. public function getTypes()
  146. {
  147. return $this->types;
  148. }
  149. /**
  150. * {@inheritDoc}
  151. */
  152. public function isRequired()
  153. {
  154. if (null === $this->parent || $this->parent->isRequired()) {
  155. return $this->required;
  156. }
  157. return false;
  158. }
  159. /**
  160. * {@inheritDoc}
  161. */
  162. public function isReadOnly()
  163. {
  164. if (null === $this->parent || !$this->parent->isReadOnly()) {
  165. return $this->readOnly;
  166. }
  167. return true;
  168. }
  169. /**
  170. * {@inheritDoc}
  171. */
  172. public function setParent(FormInterface $parent = null)
  173. {
  174. $this->parent = $parent;
  175. return $this;
  176. }
  177. /**
  178. * Returns the parent field.
  179. *
  180. * @return FormInterface The parent field
  181. */
  182. public function getParent()
  183. {
  184. return $this->parent;
  185. }
  186. /**
  187. * Returns whether the field has a parent.
  188. *
  189. * @return Boolean
  190. */
  191. public function hasParent()
  192. {
  193. return null !== $this->parent;
  194. }
  195. /**
  196. * Returns the root of the form tree
  197. *
  198. * @return FormInterface The root of the tree
  199. */
  200. public function getRoot()
  201. {
  202. return $this->parent ? $this->parent->getRoot() : $this;
  203. }
  204. /**
  205. * Returns whether the field is the root of the form tree
  206. *
  207. * @return Boolean
  208. */
  209. public function isRoot()
  210. {
  211. return !$this->hasParent();
  212. }
  213. public function hasAttribute($name)
  214. {
  215. return isset($this->attributes[$name]);
  216. }
  217. public function getAttribute($name)
  218. {
  219. return $this->attributes[$name];
  220. }
  221. /**
  222. * Updates the field with default data
  223. *
  224. * @see FormInterface
  225. */
  226. public function setData($appData)
  227. {
  228. $event = new DataEvent($this, $appData);
  229. $this->dispatcher->dispatch(Events::preSetData, $event);
  230. // Hook to change content of the data
  231. $event = new FilterDataEvent($this, $appData);
  232. $this->dispatcher->dispatch(Events::filterSetData, $event);
  233. $appData = $event->getData();
  234. // Fix data if empty
  235. if (!$this->clientTransformer) {
  236. if (empty($appData) && !$this->normTransformer && $this->dataMapper) {
  237. $appData = $this->dataMapper->createEmptyData();
  238. }
  239. // Treat data as strings unless a value transformer exists
  240. if (is_scalar($appData)) {
  241. $appData = (string)$appData;
  242. }
  243. }
  244. // Synchronize representations - must not change the content!
  245. $normData = $this->appToNorm($appData);
  246. $clientData = $this->normToClient($normData);
  247. $this->data = $appData;
  248. $this->normData = $normData;
  249. $this->clientData = $clientData;
  250. $this->synchronized = true;
  251. if ($this->dataMapper) {
  252. // Update child forms from the data
  253. $this->dataMapper->mapDataToForms($clientData, $this->children);
  254. }
  255. $event = new DataEvent($this, $appData);
  256. $this->dispatcher->dispatch(Events::postSetData, $event);
  257. return $this;
  258. }
  259. /**
  260. * Binds POST data to the field, transforms and validates it.
  261. *
  262. * @param string|array $data The POST data
  263. */
  264. public function bind($clientData)
  265. {
  266. if (is_scalar($clientData) || null === $clientData) {
  267. $clientData = (string)$clientData;
  268. }
  269. // Initialize errors in the very beginning so that we don't lose any
  270. // errors added during listeners
  271. $this->errors = array();
  272. $event = new DataEvent($this, $clientData);
  273. $this->dispatcher->dispatch(Events::preBind, $event);
  274. $appData = null;
  275. $normData = null;
  276. $extraData = array();
  277. $synchronized = false;
  278. // Hook to change content of the data bound by the browser
  279. $event = new FilterDataEvent($this, $clientData);
  280. $this->dispatcher->dispatch(Events::filterBoundClientData, $event);
  281. $clientData = $event->getData();
  282. if (count($this->children) > 0) {
  283. if (empty($clientData)) {
  284. $clientData = array();
  285. }
  286. if (!is_array($clientData)) {
  287. throw new UnexpectedTypeException($clientData, 'array');
  288. }
  289. foreach ($this->children as $name => $child) {
  290. if (!isset($clientData[$name])) {
  291. $clientData[$name] = null;
  292. }
  293. }
  294. foreach ($clientData as $name => $value) {
  295. if ($this->has($name)) {
  296. $this->children[$name]->bind($value);
  297. } else {
  298. $extraData[$name] = $value;
  299. }
  300. }
  301. // Merge form data from children into existing client data
  302. if ($this->dataMapper) {
  303. $clientData = $this->getClientData();
  304. $this->dataMapper->mapFormsToData($this->children, $clientData);
  305. }
  306. }
  307. try {
  308. // Normalize data to unified representation
  309. $normData = $this->clientToNorm($clientData);
  310. $synchronized = true;
  311. } catch (TransformationFailedException $e) {
  312. }
  313. if ($synchronized) {
  314. // Hook to change content of the data in the normalized
  315. // representation
  316. $event = new FilterDataEvent($this, $normData);
  317. $this->dispatcher->dispatch(Events::filterBoundNormData, $event);
  318. $normData = $event->getData();
  319. // Synchronize representations - must not change the content!
  320. $appData = $this->normToApp($normData);
  321. $clientData = $this->normToClient($normData);
  322. }
  323. $this->bound = true;
  324. $this->data = $appData;
  325. $this->normData = $normData;
  326. $this->clientData = $clientData;
  327. $this->extraData = $extraData;
  328. $this->synchronized = $synchronized;
  329. $event = new DataEvent($this, $clientData);
  330. $this->dispatcher->dispatch(Events::postBind, $event);
  331. foreach ($this->validators as $validator) {
  332. $validator->validate($this);
  333. }
  334. }
  335. /**
  336. * Returns the data in the format needed for the underlying object.
  337. *
  338. * @return mixed
  339. */
  340. public function getData()
  341. {
  342. return $this->data;
  343. }
  344. /**
  345. * Returns the normalized data of the field.
  346. *
  347. * @return mixed When the field is not bound, the default data is returned.
  348. * When the field is bound, the normalized bound data is
  349. * returned if the field is valid, null otherwise.
  350. */
  351. public function getNormData()
  352. {
  353. return $this->normData;
  354. }
  355. /**
  356. * Returns the data transformed by the value transformer
  357. *
  358. * @return string
  359. */
  360. public function getClientData()
  361. {
  362. return $this->clientData;
  363. }
  364. public function getExtraData()
  365. {
  366. return $this->extraData;
  367. }
  368. /**
  369. * Adds an error to the field.
  370. *
  371. * @see FormInterface
  372. */
  373. public function addError(FormError $error)
  374. {
  375. if ($this->parent && $this->errorBubbling) {
  376. $this->parent->addError($error);
  377. } else {
  378. $this->errors[] = $error;
  379. }
  380. }
  381. /**
  382. * Returns whether errors bubble up to the parent
  383. *
  384. * @return Boolean
  385. */
  386. public function getErrorBubbling()
  387. {
  388. return $this->errorBubbling;
  389. }
  390. /**
  391. * Returns whether the field is bound.
  392. *
  393. * @return Boolean true if the form is bound to input values, false otherwise
  394. */
  395. public function isBound()
  396. {
  397. return $this->bound;
  398. }
  399. /**
  400. * Returns whether the data in the different formats is synchronized
  401. *
  402. * @return Boolean
  403. */
  404. public function isSynchronized()
  405. {
  406. return $this->synchronized;
  407. }
  408. /**
  409. * {@inheritDoc}
  410. */
  411. public function isEmpty()
  412. {
  413. foreach ($this->children as $child) {
  414. if (!$child->isEmpty()) {
  415. return false;
  416. }
  417. }
  418. return array() === $this->data || null === $this->data || '' === $this->data;
  419. }
  420. /**
  421. * Returns whether the field is valid.
  422. *
  423. * @return Boolean
  424. */
  425. public function isValid()
  426. {
  427. // TESTME
  428. if (!$this->isBound() || $this->hasErrors()) {
  429. return false;
  430. }
  431. foreach ($this->children as $child) {
  432. if (!$child->isValid()) {
  433. return false;
  434. }
  435. }
  436. return true;
  437. }
  438. /**
  439. * Returns whether or not there are errors.
  440. *
  441. * @return Boolean true if form is bound and not valid
  442. */
  443. public function hasErrors()
  444. {
  445. // Don't call isValid() here, as its semantics are slightly different
  446. // Field groups are not valid if their children are invalid, but
  447. // hasErrors() returns only true if a field/field group itself has
  448. // errors
  449. return count($this->errors) > 0;
  450. }
  451. /**
  452. * Returns all errors
  453. *
  454. * @return array An array of FormError instances that occurred during binding
  455. */
  456. public function getErrors()
  457. {
  458. return $this->errors;
  459. }
  460. /**
  461. * Returns the DataTransformer.
  462. *
  463. * @return DataTransformerInterface
  464. */
  465. public function getNormTransformer()
  466. {
  467. return $this->normTransformer;
  468. }
  469. /**
  470. * Returns the DataTransformer.
  471. *
  472. * @return DataTransformerInterface
  473. */
  474. public function getClientTransformer()
  475. {
  476. return $this->clientTransformer;
  477. }
  478. /**
  479. * Returns the renderer
  480. *
  481. * @return FormRendererInterface
  482. */
  483. public function getRenderer()
  484. {
  485. return $this->renderer;
  486. }
  487. /**
  488. * Returns all children in this group
  489. *
  490. * @return array
  491. */
  492. public function getChildren()
  493. {
  494. return $this->children;
  495. }
  496. public function hasChildren()
  497. {
  498. return count($this->children) > 0;
  499. }
  500. public function add(FormInterface $child)
  501. {
  502. $this->children[$child->getName()] = $child;
  503. $child->setParent($this);
  504. if ($this->dataMapper) {
  505. $this->dataMapper->mapDataToForm($this->getClientData(), $child);
  506. }
  507. }
  508. public function remove($name)
  509. {
  510. if (isset($this->children[$name])) {
  511. $this->children[$name]->setParent(null);
  512. unset($this->children[$name]);
  513. }
  514. }
  515. /**
  516. * Returns whether a child with the given name exists.
  517. *
  518. * @param string $name
  519. * @return Boolean
  520. */
  521. public function has($name)
  522. {
  523. return isset($this->children[$name]);
  524. }
  525. /**
  526. * Returns the child with the given name.
  527. *
  528. * @param string $name
  529. * @return FormInterface
  530. */
  531. public function get($name)
  532. {
  533. if (isset($this->children[$name])) {
  534. return $this->children[$name];
  535. }
  536. throw new \InvalidArgumentException(sprintf('Field "%s" does not exist.', $name));
  537. }
  538. /**
  539. * Returns true if the child exists (implements the \ArrayAccess interface).
  540. *
  541. * @param string $name The name of the child
  542. *
  543. * @return Boolean true if the widget exists, false otherwise
  544. */
  545. public function offsetExists($name)
  546. {
  547. return $this->has($name);
  548. }
  549. /**
  550. * Returns the form child associated with the name (implements the \ArrayAccess interface).
  551. *
  552. * @param string $name The offset of the value to get
  553. *
  554. * @return Field A form child instance
  555. */
  556. public function offsetGet($name)
  557. {
  558. return $this->get($name);
  559. }
  560. /**
  561. * Throws an exception saying that values cannot be set (implements the \ArrayAccess interface).
  562. *
  563. * @param string $offset (ignored)
  564. * @param string $value (ignored)
  565. *
  566. * @throws \LogicException
  567. */
  568. public function offsetSet($name, $child)
  569. {
  570. throw new \BadMethodCallException('offsetSet() is not supported');
  571. }
  572. /**
  573. * Throws an exception saying that values cannot be unset (implements the \ArrayAccess interface).
  574. *
  575. * @param string $name
  576. *
  577. * @throws \LogicException
  578. */
  579. public function offsetUnset($name)
  580. {
  581. throw new \BadMethodCallException('offsetUnset() is not supported');
  582. }
  583. /**
  584. * Returns the iterator for this group.
  585. *
  586. * @return \ArrayIterator
  587. */
  588. public function getIterator()
  589. {
  590. return new \ArrayIterator($this->children);
  591. }
  592. /**
  593. * Returns the number of form children (implements the \Countable interface).
  594. *
  595. * @return integer The number of embedded form children
  596. */
  597. public function count()
  598. {
  599. return count($this->children);
  600. }
  601. /**
  602. * Normalizes the value if a normalization transformer is set
  603. *
  604. * @param mixed $value The value to transform
  605. * @return string
  606. */
  607. private function appToNorm($value)
  608. {
  609. if (null === $this->normTransformer) {
  610. return $value;
  611. }
  612. return $this->normTransformer->transform($value);
  613. }
  614. /**
  615. * Reverse transforms a value if a normalization transformer is set.
  616. *
  617. * @param string $value The value to reverse transform
  618. * @return mixed
  619. */
  620. private function normToApp($value)
  621. {
  622. if (null === $this->normTransformer) {
  623. return $value;
  624. }
  625. return $this->normTransformer->reverseTransform($value);
  626. }
  627. /**
  628. * Transforms the value if a value transformer is set.
  629. *
  630. * @param mixed $value The value to transform
  631. * @return string
  632. */
  633. private function normToClient($value)
  634. {
  635. if (null === $this->clientTransformer) {
  636. // Scalar values should always be converted to strings to
  637. // facilitate differentiation between empty ("") and zero (0).
  638. return null === $value || is_scalar($value) ? (string)$value : $value;
  639. }
  640. return $this->clientTransformer->transform($value);
  641. }
  642. /**
  643. * Reverse transforms a value if a value transformer is set.
  644. *
  645. * @param string $value The value to reverse transform
  646. * @return mixed
  647. */
  648. private function clientToNorm($value)
  649. {
  650. if (null === $this->clientTransformer) {
  651. return '' === $value ? null : $value;
  652. }
  653. return $this->clientTransformer->reverseTransform($value);
  654. }
  655. /**
  656. * Binds a request to the form
  657. *
  658. * If the request was a POST request, the data is bound to the form,
  659. * transformed and written into the form data (an object or an array).
  660. * You can set the form data by passing it in the second parameter
  661. * of this method or by passing it in the "data" option of the form's
  662. * constructor.
  663. *
  664. * @param Request $request The request to bind to the form
  665. * @param array|object $data The data from which to read default values
  666. * and where to write bound values
  667. */
  668. public function bindRequest(Request $request)
  669. {
  670. // Store the bound data in case of a post request
  671. switch ($request->getMethod()) {
  672. case 'POST':
  673. case 'PUT':
  674. $data = array_replace_recursive(
  675. $request->request->get($this->getName(), array()),
  676. $request->files->get($this->getName(), array())
  677. );
  678. break;
  679. case 'GET':
  680. $data = $request->query->get($this->getName(), array());
  681. break;
  682. default:
  683. throw new FormException(sprintf('The request method "%s" is not supported', $request->getMethod()));
  684. }
  685. $this->bind($data);
  686. }
  687. }