Form.php 22 KB

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