Field.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. <?php
  2. namespace Symfony\Component\Form;
  3. /*
  4. * This file is part of the Symfony package.
  5. *
  6. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. use Symfony\Component\Form\ValueTransformer\ValueTransformerInterface;
  12. use Symfony\Component\Form\ValueTransformer\TransformationFailedException;
  13. use Symfony\Component\Form\DataProcessor\DataProcessorInterface;
  14. use Symfony\Component\Form\Renderer\RendererInterface;
  15. use Symfony\Component\Form\Renderer\Plugin\PluginInterface;
  16. /**
  17. * Base class for form fields
  18. *
  19. * To implement your own form fields, you need to have a thorough understanding
  20. * of the data flow within a form field. A form field stores its data in three
  21. * different representations:
  22. *
  23. * (1) the format required by the form's object
  24. * (2) a normalized format for internal processing
  25. * (3) the format used for display
  26. *
  27. * A date field, for example, may store a date as "Y-m-d" string (1) in the
  28. * object. To facilitate processing in the field, this value is normalized
  29. * to a DateTime object (2). In the HTML representation of your form, a
  30. * localized string (3) is presented to and modified by the user.
  31. *
  32. * In most cases, format (1) and format (2) will be the same. For example,
  33. * a checkbox field uses a Boolean value both for internal processing as for
  34. * storage in the object. In these cases you simply need to set a value
  35. * transformer to convert between formats (2) and (3). You can do this by
  36. * calling setValueTransformer() in the configure() method.
  37. *
  38. * In some cases though it makes sense to make format (1) configurable. To
  39. * demonstrate this, let's extend our above date field to store the value
  40. * either as "Y-m-d" string or as timestamp. Internally we still want to
  41. * use a DateTime object for processing. To convert the data from string/integer
  42. * to DateTime you can set a normalization transformer by calling
  43. * setNormalizationTransformer() in configure(). The normalized data is then
  44. * converted to the displayed data as described before.
  45. *
  46. * @author Bernhard Schussek <bernhard.schussek@symfony-project.com>
  47. */
  48. class Field extends Configurable implements FieldInterface
  49. {
  50. private $errors = array();
  51. private $key = '';
  52. private $parent;
  53. private $submitted = false;
  54. private $required;
  55. private $data;
  56. private $normalizedData;
  57. private $transformedData = '';
  58. private $normalizationTransformer;
  59. private $valueTransformer;
  60. private $dataProcessor;
  61. private $propertyPath;
  62. private $transformationSuccessful = true;
  63. private $renderer;
  64. private $hidden = false;
  65. private $trim = true;
  66. private $disabled = false;
  67. public function __construct($key = null)
  68. {
  69. $this->key = (string)$key;
  70. }
  71. /**
  72. * Clones this field.
  73. */
  74. public function __clone()
  75. {
  76. // TODO
  77. }
  78. /**
  79. * Returns the data of the field as it is displayed to the user.
  80. *
  81. * @return string|array When the field is not submitted, the transformed
  82. * default data is returned. When the field is submitted,
  83. * the submitted data is returned.
  84. */
  85. public function getDisplayedData()
  86. {
  87. return $this->getTransformedData();
  88. }
  89. /**
  90. * Returns the data transformed by the value transformer
  91. *
  92. * @return string
  93. */
  94. public function getTransformedData()
  95. {
  96. return $this->transformedData;
  97. }
  98. /**
  99. * {@inheritDoc}
  100. */
  101. public function setPropertyPath($propertyPath)
  102. {
  103. $this->propertyPath = null === $propertyPath || '' === $propertyPath ? null : new PropertyPath($propertyPath);
  104. return $this;
  105. }
  106. /**
  107. * {@inheritDoc}
  108. */
  109. public function getPropertyPath()
  110. {
  111. return $this->propertyPath;
  112. }
  113. /**
  114. * {@inheritDoc}
  115. */
  116. public function setKey($key)
  117. {
  118. $this->key = (string)$key;
  119. }
  120. /**
  121. * {@inheritDoc}
  122. */
  123. public function getKey()
  124. {
  125. return $this->key;
  126. }
  127. /**
  128. * {@inheritDoc}
  129. */
  130. public function setRequired($required)
  131. {
  132. $this->required = $required;
  133. return $this;
  134. }
  135. /**
  136. * {@inheritDoc}
  137. */
  138. public function isRequired()
  139. {
  140. if (null === $this->parent || $this->parent->isRequired()) {
  141. return $this->required;
  142. }
  143. return false;
  144. }
  145. public function setDisabled($disabled)
  146. {
  147. $this->disabled = $disabled;
  148. return $this;
  149. }
  150. /**
  151. * {@inheritDoc}
  152. */
  153. public function isDisabled()
  154. {
  155. if (null === $this->parent || !$this->parent->isDisabled()) {
  156. return $this->disabled;
  157. }
  158. return true;
  159. }
  160. /**
  161. * {@inheritDoc}
  162. */
  163. public function isMultipart()
  164. {
  165. return false;
  166. }
  167. /**
  168. * {@inheritDoc}
  169. */
  170. public function setParent(FieldInterface $parent = null)
  171. {
  172. $this->parent = $parent;
  173. return $this;
  174. }
  175. /**
  176. * Returns the parent field.
  177. *
  178. * @return FieldInterface The parent field
  179. */
  180. public function getParent()
  181. {
  182. return $this->parent;
  183. }
  184. /**
  185. * Returns whether the field has a parent.
  186. *
  187. * @return Boolean
  188. */
  189. public function hasParent()
  190. {
  191. return null !== $this->parent;
  192. }
  193. /**
  194. * Returns the root of the form tree
  195. *
  196. * @return FieldInterface The root of the tree
  197. */
  198. public function getRoot()
  199. {
  200. return $this->parent ? $this->parent->getRoot() : $this;
  201. }
  202. /**
  203. * Returns whether the field is the root of the form tree
  204. *
  205. * @return Boolean
  206. */
  207. public function isRoot()
  208. {
  209. return !$this->hasParent();
  210. }
  211. /**
  212. * Updates the field with default data
  213. *
  214. * @see FieldInterface
  215. */
  216. public function setData($data)
  217. {
  218. // All four transformation methods must be executed to make sure
  219. // that all three data representations are synchronized
  220. // Store data in between steps because processData() might use
  221. // this data
  222. $this->data = $data;
  223. $this->normalizedData = $this->normalize($data);
  224. $this->transformedData = $this->transform($this->normalize($data));
  225. $this->normalizedData = $this->processData($this->reverseTransform($this->transformedData));
  226. $this->data = $this->denormalize($this->normalizedData);
  227. return $this;
  228. }
  229. /**
  230. * Binds POST data to the field, transforms and validates it.
  231. *
  232. * @param string|array $data The POST data
  233. */
  234. public function submit($data)
  235. {
  236. $this->transformedData = (is_array($data) || is_object($data)) ? $data : (string)$data;
  237. $this->submitted = true;
  238. $this->errors = array();
  239. if (is_string($this->transformedData) && $this->trim) {
  240. $this->transformedData = trim($this->transformedData);
  241. }
  242. try {
  243. $this->normalizedData = $this->processData($this->reverseTransform($this->transformedData));
  244. $this->data = $this->denormalize($this->normalizedData);
  245. $this->transformedData = $this->transform($this->normalizedData);
  246. $this->transformationSuccessful = true;
  247. } catch (TransformationFailedException $e) {
  248. $this->transformationSuccessful = false;
  249. }
  250. }
  251. /**
  252. * Processes the submitted reverse-transformed data.
  253. *
  254. * This method can be overridden if you want to modify the data entered
  255. * by the user. Note that the data is already in reverse transformed format.
  256. *
  257. * This method will not be called if reverse transformation fails.
  258. *
  259. * @param mixed $data
  260. * @return mixed
  261. */
  262. protected function processData($data)
  263. {
  264. if ($this->dataProcessor) {
  265. return $this->dataProcessor->processData($data);
  266. }
  267. return $data;
  268. }
  269. /**
  270. * Returns the data in the format needed for the underlying object.
  271. *
  272. * @return mixed
  273. */
  274. public function getData()
  275. {
  276. return $this->data;
  277. }
  278. /**
  279. * Returns the normalized data of the field.
  280. *
  281. * @return mixed When the field is not submitted, the default data is returned.
  282. * When the field is submitted, the normalized submitted data is
  283. * returned if the field is valid, null otherwise.
  284. */
  285. public function getNormalizedData()
  286. {
  287. return $this->normalizedData;
  288. }
  289. /**
  290. * Adds an error to the field.
  291. *
  292. * @see FieldInterface
  293. */
  294. public function addError(Error $error, PropertyPathIterator $pathIterator = null)
  295. {
  296. $this->errors[] = $error;
  297. }
  298. /**
  299. * Returns whether the field is submitted.
  300. *
  301. * @return Boolean true if the form is submitted to input values, false otherwise
  302. */
  303. public function isSubmitted()
  304. {
  305. return $this->submitted;
  306. }
  307. /**
  308. * Returns whether the submitted value could be reverse transformed correctly
  309. *
  310. * @return Boolean
  311. */
  312. public function isTransformationSuccessful()
  313. {
  314. return $this->transformationSuccessful;
  315. }
  316. /**
  317. * Returns whether the field is valid.
  318. *
  319. * @return Boolean
  320. */
  321. public function isValid()
  322. {
  323. return $this->isSubmitted() && !$this->hasErrors(); // TESTME
  324. }
  325. /**
  326. * Returns whether or not there are errors.
  327. *
  328. * @return Boolean true if form is submitted and not valid
  329. */
  330. public function hasErrors()
  331. {
  332. // Don't call isValid() here, as its semantics are slightly different
  333. // Field groups are not valid if their children are invalid, but
  334. // hasErrors() returns only true if a field/field group itself has
  335. // errors
  336. return count($this->errors) > 0;
  337. }
  338. /**
  339. * Returns all errors
  340. *
  341. * @return array An array of FieldError instances that occurred during submitting
  342. */
  343. public function getErrors()
  344. {
  345. return $this->errors;
  346. }
  347. /**
  348. * Sets the ValueTransformer.
  349. *
  350. * @param ValueTransformerInterface $valueTransformer
  351. */
  352. public function setNormalizationTransformer(ValueTransformerInterface $normalizationTransformer = null)
  353. {
  354. $this->normalizationTransformer = $normalizationTransformer;
  355. return $this;
  356. }
  357. /**
  358. * Returns the ValueTransformer.
  359. *
  360. * @return ValueTransformerInterface
  361. */
  362. public function getNormalizationTransformer()
  363. {
  364. return $this->normalizationTransformer;
  365. }
  366. /**
  367. * Sets the ValueTransformer.
  368. *
  369. * @param ValueTransformerInterface $valueTransformer
  370. */
  371. public function setValueTransformer(ValueTransformerInterface $valueTransformer = null)
  372. {
  373. $this->valueTransformer = $valueTransformer;
  374. return $this;
  375. }
  376. /**
  377. * Returns the ValueTransformer.
  378. *
  379. * @return ValueTransformerInterface
  380. */
  381. public function getValueTransformer()
  382. {
  383. return $this->valueTransformer;
  384. }
  385. /**
  386. * Sets the data processor
  387. *
  388. * @param DataProcessorInterface $dataProcessor
  389. */
  390. public function setDataProcessor(DataProcessorInterface $dataProcessor = null)
  391. {
  392. $this->dataProcessor = $dataProcessor;
  393. return $this;
  394. }
  395. /**
  396. * Returns the data processor
  397. *
  398. * @return DataProcessorInterface
  399. */
  400. public function getDataProcessor()
  401. {
  402. return $this->dataProcessor;
  403. }
  404. public function setTrim($trim)
  405. {
  406. $this->trim = $trim;
  407. return $this;
  408. }
  409. public function getTrim()
  410. {
  411. return $this->trim;
  412. }
  413. /**
  414. * Sets the renderer
  415. *
  416. * @param RendererInterface $renderer
  417. */
  418. public function setRenderer(RendererInterface $renderer)
  419. {
  420. $this->renderer = $renderer;
  421. return $this;
  422. }
  423. /**
  424. * Returns the renderer
  425. *
  426. * @return RendererInterface
  427. */
  428. public function getRenderer()
  429. {
  430. return $this->renderer;
  431. }
  432. public function addRendererPlugin(PluginInterface $plugin)
  433. {
  434. $this->renderer->addPlugin($plugin);
  435. return $this;
  436. }
  437. public function setRendererVar($name, $value)
  438. {
  439. $this->renderer->setVar($name, $value);
  440. return $this;
  441. }
  442. /**
  443. * Normalizes the value if a normalization transformer is set
  444. *
  445. * @param mixed $value The value to transform
  446. * @return string
  447. */
  448. protected function normalize($value)
  449. {
  450. if (null === $this->normalizationTransformer) {
  451. return $value;
  452. }
  453. return $this->normalizationTransformer->transform($value);
  454. }
  455. /**
  456. * Reverse transforms a value if a normalization transformer is set.
  457. *
  458. * @param string $value The value to reverse transform
  459. * @return mixed
  460. */
  461. protected function denormalize($value)
  462. {
  463. if (null === $this->normalizationTransformer) {
  464. return $value;
  465. }
  466. return $this->normalizationTransformer->reverseTransform($value, $this->data);
  467. }
  468. /**
  469. * Transforms the value if a value transformer is set.
  470. *
  471. * @param mixed $value The value to transform
  472. * @return string
  473. */
  474. protected function transform($value)
  475. {
  476. if (null === $this->valueTransformer) {
  477. // Scalar values should always be converted to strings to
  478. // facilitate differentiation between empty ("") and zero (0).
  479. return null === $value || is_scalar($value) ? (string)$value : $value;
  480. }
  481. return $this->valueTransformer->transform($value);
  482. }
  483. /**
  484. * Reverse transforms a value if a value transformer is set.
  485. *
  486. * @param string $value The value to reverse transform
  487. * @return mixed
  488. */
  489. protected function reverseTransform($value)
  490. {
  491. if (null === $this->valueTransformer) {
  492. return '' === $value ? null : $value;
  493. }
  494. return $this->valueTransformer->reverseTransform($value, $this->data);
  495. }
  496. /**
  497. * {@inheritDoc}
  498. */
  499. public function readProperty(&$objectOrArray)
  500. {
  501. // TODO throw exception if not object or array
  502. if ($this->propertyPath !== null) {
  503. $this->setData($this->propertyPath->getValue($objectOrArray));
  504. }
  505. }
  506. /**
  507. * {@inheritDoc}
  508. */
  509. public function writeProperty(&$objectOrArray)
  510. {
  511. // TODO throw exception if not object or array
  512. if ($this->propertyPath !== null) {
  513. $this->propertyPath->setValue($objectOrArray, $this->getData());
  514. }
  515. }
  516. /**
  517. * {@inheritDoc}
  518. */
  519. public function isEmpty()
  520. {
  521. return null === $this->data || '' === $this->data;
  522. }
  523. }