sfWidgetFormSchema.class.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685
  1. <?php
  2. /*
  3. * This file is part of the symfony package.
  4. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  5. *
  6. * For the full copyright and license information, please view the LICENSE
  7. * file that was distributed with this source code.
  8. */
  9. /**
  10. * sfWidgetFormSchema represents an array of fields.
  11. *
  12. * A field is a named validator.
  13. *
  14. * @package symfony
  15. * @subpackage widget
  16. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  17. * @version SVN: $Id: sfWidgetFormSchema.class.php 17587 2009-04-24 18:41:19Z Kris.Wallsmith $
  18. */
  19. class sfWidgetFormSchema extends sfWidgetForm implements ArrayAccess
  20. {
  21. const
  22. FIRST = 'first',
  23. LAST = 'last',
  24. BEFORE = 'before',
  25. AFTER = 'after';
  26. protected static
  27. $defaultFormatterName = 'table';
  28. protected
  29. $parent = null,
  30. $formFormatters = array(),
  31. $options = array(),
  32. $labels = array(),
  33. $fields = array(),
  34. $positions = array(),
  35. $helps = array();
  36. /**
  37. * Constructor.
  38. *
  39. * The first argument can be:
  40. *
  41. * * null
  42. * * an array of sfWidget instances
  43. *
  44. * Available options:
  45. *
  46. * * name_format: The sprintf pattern to use for input names
  47. * * form_formatter: The form formatter name (table and list are bundled)
  48. *
  49. * @param mixed $fields Initial fields
  50. * @param array $options An array of options
  51. * @param array $attributes An array of default HTML attributes
  52. * @param array $labels An array of HTML labels
  53. * @param array $helps An array of help texts
  54. *
  55. * @see sfWidgetForm
  56. */
  57. public function __construct($fields = null, $options = array(), $attributes = array(), $labels = array(), $helps = array())
  58. {
  59. $this->labels = $labels;
  60. $this->helps = $helps;
  61. $this->addOption('name_format', '%s');
  62. $this->addOption('form_formatter', null);
  63. parent::__construct($options, $attributes);
  64. if (is_array($fields))
  65. {
  66. foreach ($fields as $name => $widget)
  67. {
  68. $this[$name] = $widget;
  69. }
  70. }
  71. else if (!is_null($fields))
  72. {
  73. throw new InvalidArgumentException('sfWidgetFormSchema constructor takes an array of sfWidget objects.');
  74. }
  75. }
  76. /**
  77. * Adds a form formatter.
  78. *
  79. * @param string $name The formatter name
  80. * @param sfWidgetFormSchemaFormatter $formatter An sfWidgetFormSchemaFormatter instance
  81. */
  82. public function addFormFormatter($name, sfWidgetFormSchemaFormatter $formatter)
  83. {
  84. $this->formFormatters[$name] = $formatter;
  85. }
  86. /**
  87. * Returns all the form formats defined for this form schema.
  88. *
  89. * @return array An array of named form formats
  90. */
  91. public function getFormFormatters()
  92. {
  93. return $this->formFormatters;
  94. }
  95. /**
  96. * Sets the generic default formatter name used by the class. If you want all
  97. * of your forms to be generated with the <code>list</code> format, you can
  98. * do it in a project or application configuration class:
  99. *
  100. * <pre>
  101. * class ProjectConfiguration extends sfProjectConfiguration
  102. * {
  103. * public function setup()
  104. * {
  105. * sfWidgetFormSchema::setDefaultFormFormatterName('list');
  106. * }
  107. * }
  108. * </pre>
  109. *
  110. * @param string $name New default formatter name
  111. */
  112. static public function setDefaultFormFormatterName($name)
  113. {
  114. self::$defaultFormatterName = $name;
  115. }
  116. /**
  117. * Sets the form formatter name to use when rendering the widget schema.
  118. *
  119. * @param string $name The form formatter name
  120. */
  121. public function setFormFormatterName($name)
  122. {
  123. $this->options['form_formatter'] = $name;
  124. }
  125. /**
  126. * Gets the form formatter name that will be used to render the widget schema.
  127. *
  128. * @return string The form formatter name
  129. */
  130. public function getFormFormatterName()
  131. {
  132. return is_null($this->options['form_formatter']) ? self::$defaultFormatterName : $this->options['form_formatter'];
  133. }
  134. /**
  135. * Returns the form formatter to use for widget schema rendering
  136. *
  137. * @return sfWidgetFormSchemaFormatter sfWidgetFormSchemaFormatter instance
  138. *
  139. * @throws InvalidArgumentException
  140. */
  141. public function getFormFormatter()
  142. {
  143. $name = $this->getFormFormatterName();
  144. if (!isset($this->formFormatters[$name]))
  145. {
  146. $class = 'sfWidgetFormSchemaFormatter'.ucfirst($name);
  147. if (!class_exists($class))
  148. {
  149. throw new InvalidArgumentException(sprintf('The form formatter "%s" does not exist.', $name));
  150. }
  151. $this->formFormatters[$name] = new $class($this);
  152. }
  153. return $this->formFormatters[$name];
  154. }
  155. /**
  156. * Sets the format string for the name HTML attribute.
  157. *
  158. * If you are using the form framework with symfony, do not use a reserved word in the
  159. * name format. If you do, symfony may act in an unexpected manner.
  160. *
  161. * For symfony 1.1 and 1.2, the following words are reserved and must NOT be used as
  162. * the name format:
  163. *
  164. * * module (example: module[%s])
  165. * * action (example: action[%s])
  166. *
  167. * However, you CAN use other variations, such as actions[%s] (note the s).
  168. *
  169. * @param string $format The format string (must contain a %s for the name placeholder)
  170. */
  171. public function setNameFormat($format)
  172. {
  173. if (false !== $format && false === strpos($format, '%s'))
  174. {
  175. throw new InvalidArgumentException(sprintf('The name format must contain %%s ("%s" given)', $format));
  176. }
  177. $this->options['name_format'] = $format;
  178. }
  179. /**
  180. * Gets the format string for the name HTML attribute.
  181. *
  182. * @return string The format string
  183. */
  184. public function getNameFormat()
  185. {
  186. return $this->options['name_format'];
  187. }
  188. /**
  189. * Sets the label names to render for each field.
  190. *
  191. * @param array $labels An array of label names
  192. */
  193. public function setLabels($labels)
  194. {
  195. $this->labels = $labels;
  196. }
  197. /**
  198. * Gets the labels.
  199. *
  200. * @return array An array of label names
  201. */
  202. public function getLabels()
  203. {
  204. return $this->labels;
  205. }
  206. /**
  207. * Sets a label.
  208. *
  209. * @param string $name The field name
  210. * @param string $value The label name
  211. */
  212. public function setLabel($name, $value)
  213. {
  214. $this->labels[$name] = $value;
  215. }
  216. /**
  217. * Gets a label by field name.
  218. *
  219. * @param string $name The field name
  220. *
  221. * @return string The label name or an empty string if it is not defined
  222. */
  223. public function getLabel($name)
  224. {
  225. return array_key_exists($name, $this->labels) ? $this->labels[$name] : '';
  226. }
  227. /**
  228. * Sets the help texts to render for each field.
  229. *
  230. * @param array $helps An array of help texts
  231. */
  232. public function setHelps($helps)
  233. {
  234. $this->helps = $helps;
  235. }
  236. /**
  237. * Sets the help texts.
  238. *
  239. * @return array An array of help texts
  240. */
  241. public function getHelps()
  242. {
  243. return $this->helps;
  244. }
  245. /**
  246. * Sets a help text.
  247. *
  248. * @param string $name The field name
  249. * @param string $help The help text
  250. */
  251. public function setHelp($name, $help)
  252. {
  253. $this->helps[$name] = $help;
  254. }
  255. /**
  256. * Gets a text help by field name.
  257. *
  258. * @param string $name The field name
  259. *
  260. * @return string The help text or an empty string if it is not defined
  261. */
  262. public function getHelp($name)
  263. {
  264. return array_key_exists($name, $this->helps) ? $this->helps[$name] : '';
  265. }
  266. /**
  267. * Returns true if the widget schema needs a multipart form.
  268. *
  269. * @return bool true if the widget schema needs a multipart form, false otherwise
  270. */
  271. public function needsMultipartForm()
  272. {
  273. foreach ($this->fields as $field)
  274. {
  275. if ($field->needsMultipartForm())
  276. {
  277. return true;
  278. }
  279. }
  280. return false;
  281. }
  282. /**
  283. * Renders a field by name.
  284. *
  285. * @param string $name The field name
  286. * @param string $value The field value
  287. * @param array $attributes An array of HTML attributes to be merged with the current HTML attributes
  288. * @param array $attributes An array of errors for the field
  289. *
  290. * @return string An HTML string representing the rendered widget
  291. */
  292. public function renderField($name, $value = null, $attributes = array(), $errors = array())
  293. {
  294. if (is_null($widget = $this[$name]))
  295. {
  296. throw new InvalidArgumentException(sprintf('The field named "%s" does not exist.', $name));
  297. }
  298. if ($widget instanceof sfWidgetFormSchema && $errors && !$errors instanceof sfValidatorErrorSchema)
  299. {
  300. $errors = new sfValidatorErrorSchema($errors->getValidator(), array($errors));
  301. }
  302. // we clone the widget because we want to change the id format temporarily
  303. $clone = clone $widget;
  304. $clone->setIdFormat($this->options['id_format']);
  305. return $clone->render($this->generateName($name), $value, array_merge($clone->getAttributes(), $attributes), $errors);
  306. }
  307. /**
  308. * Renders the widget.
  309. *
  310. * @param string $name The name of the HTML widget
  311. * @param mixed $values The values of the widget
  312. * @param array $attributes An array of HTML attributes
  313. * @param array $errors An array of errors
  314. *
  315. * @return string An HTML representation of the widget
  316. */
  317. public function render($name, $values = array(), $attributes = array(), $errors = array())
  318. {
  319. if (is_null($values))
  320. {
  321. $values = array();
  322. }
  323. if (!is_array($values) && !$values instanceof ArrayAccess)
  324. {
  325. throw new InvalidArgumentException('You must pass an array of values to render a widget schema');
  326. }
  327. $formFormat = $this->getFormFormatter();
  328. $rows = array();
  329. $hiddenRows = array();
  330. $errorRows = array();
  331. // render each field
  332. foreach ($this->positions as $name)
  333. {
  334. $widget = $this[$name];
  335. $value = isset($values[$name]) ? $values[$name] : null;
  336. $error = isset($errors[$name]) ? $errors[$name] : array();
  337. $widgetAttributes = isset($attributes[$name]) ? $attributes[$name] : array();
  338. if ($widget instanceof sfWidgetForm && $widget->isHidden())
  339. {
  340. $hiddenRows[] = $this->renderField($name, $value, $widgetAttributes);
  341. }
  342. else
  343. {
  344. $field = $this->renderField($name, $value, $widgetAttributes, $error);
  345. // don't add a label tag and errors if we embed a form schema
  346. $label = $widget instanceof sfWidgetFormSchema ? $this->getFormFormatter()->generateLabelName($name) : $this->getFormFormatter()->generateLabel($name);
  347. $error = $widget instanceof sfWidgetFormSchema ? array() : $error;
  348. $rows[] = $formFormat->formatRow($label, $field, $error, $this->getHelp($name));
  349. }
  350. }
  351. if ($rows)
  352. {
  353. // insert hidden fields in the last row
  354. for ($i = 0, $max = count($rows); $i < $max; $i++)
  355. {
  356. $rows[$i] = strtr($rows[$i], array('%hidden_fields%' => $i == $max - 1 ? implode("\n", $hiddenRows) : ''));
  357. }
  358. }
  359. else
  360. {
  361. // only hidden fields
  362. $rows[0] = implode("\n", $hiddenRows);
  363. }
  364. return $this->getFormFormatter()->formatErrorRow($this->getGlobalErrors($errors)).implode('', $rows);
  365. }
  366. /**
  367. * Gets errors that need to be included in global errors.
  368. *
  369. * @param array $errors An array of errors
  370. *
  371. * @return string An HTML representation of global errors for the widget
  372. */
  373. public function getGlobalErrors($errors)
  374. {
  375. $globalErrors = array();
  376. // global errors and errors for non existent fields
  377. if (!is_null($errors))
  378. {
  379. foreach ($errors as $name => $error)
  380. {
  381. if (!isset($this->fields[$name]))
  382. {
  383. $globalErrors[] = $error;
  384. }
  385. }
  386. }
  387. // errors for hidden fields
  388. foreach ($this->positions as $name)
  389. {
  390. if ($this[$name] instanceof sfWidgetForm && $this[$name]->isHidden())
  391. {
  392. if (isset($errors[$name]))
  393. {
  394. $globalErrors[$this->getFormFormatter()->generateLabelName($name)] = $errors[$name];
  395. }
  396. }
  397. }
  398. return $globalErrors;
  399. }
  400. /**
  401. * Generates a name.
  402. *
  403. * @param string $name The name
  404. *
  405. * @param string The generated name
  406. */
  407. public function generateName($name)
  408. {
  409. $format = $this->getNameFormat();
  410. if ('[%s]' == substr($format, -4) && preg_match('/^(.+?)\[(.+)\]$/', $name, $match))
  411. {
  412. $name = sprintf('%s[%s][%s]', substr($format, 0, -4), $match[1], $match[2]);
  413. }
  414. else if (false !== $format)
  415. {
  416. $name = sprintf($format, $name);
  417. }
  418. if ($parent = $this->getParent())
  419. {
  420. $name = $parent->generateName($name);
  421. }
  422. return $name;
  423. }
  424. /**
  425. * Gets the parent widget schema.
  426. *
  427. * @return sfWidgetFormSchema The parent widget schema
  428. */
  429. public function getParent()
  430. {
  431. return $this->parent;
  432. }
  433. /**
  434. * Sets the parent widget schema.
  435. *
  436. * @parent sfWidgetFormSchema $parent The parent widget schema
  437. */
  438. public function setParent(sfWidgetFormSchema $parent = null)
  439. {
  440. $this->parent = $parent;
  441. }
  442. /**
  443. * Returns true if the schema has a field with the given name (implements the ArrayAccess interface).
  444. *
  445. * @param string $name The field name
  446. *
  447. * @return bool true if the schema has a field with the given name, false otherwise
  448. */
  449. public function offsetExists($name)
  450. {
  451. return isset($this->fields[$name]);
  452. }
  453. /**
  454. * Gets the field associated with the given name (implements the ArrayAccess interface).
  455. *
  456. * @param string $name The field name
  457. *
  458. * @return sfWidget The sfWidget instance associated with the given name, null if it does not exist
  459. */
  460. public function offsetGet($name)
  461. {
  462. return isset($this->fields[$name]) ? $this->fields[$name] : null;
  463. }
  464. /**
  465. * Sets a field (implements the ArrayAccess interface).
  466. *
  467. * @param string $name The field name
  468. * @param sfWidget $widget An sfWidget instance
  469. */
  470. public function offsetSet($name, $widget)
  471. {
  472. if (!$widget instanceof sfWidget)
  473. {
  474. throw new InvalidArgumentException('A field must be an instance of sfWidget.');
  475. }
  476. if (!isset($this->fields[$name]))
  477. {
  478. $this->positions[] = $name;
  479. }
  480. $this->fields[$name] = clone $widget;
  481. if ($widget instanceof sfWidgetFormSchema)
  482. {
  483. $this->fields[$name]->setParent($this);
  484. $this->fields[$name]->setNameFormat($name.'[%s]');
  485. }
  486. }
  487. /**
  488. * Removes a field by name (implements the ArrayAccess interface).
  489. *
  490. * @param string
  491. */
  492. public function offsetUnset($name)
  493. {
  494. unset($this->fields[$name]);
  495. if (false !== $position = array_search($name, $this->positions))
  496. {
  497. unset($this->positions[$position]);
  498. $this->positions = array_values($this->positions);
  499. }
  500. }
  501. /**
  502. * Returns an array of fields.
  503. *
  504. * @return sfWidget An array of sfWidget instance
  505. */
  506. public function getFields()
  507. {
  508. return $this->fields;
  509. }
  510. /**
  511. * Gets the positions of the fields.
  512. *
  513. * The field positions are only used when rendering the schema with ->render().
  514. *
  515. * @return array An ordered array of field names
  516. */
  517. public function getPositions()
  518. {
  519. return $this->positions;
  520. }
  521. /**
  522. * Sets the positions of the fields.
  523. *
  524. * @param array An ordered array of field names
  525. *
  526. * @see getPositions()
  527. */
  528. public function setPositions($positions)
  529. {
  530. $positions = array_values($positions);
  531. if (array_diff($positions, array_keys($this->fields)) || array_diff(array_keys($this->fields), $positions))
  532. {
  533. throw new InvalidArgumentException('Positions must contains all field names.');
  534. }
  535. $this->positions = $positions;
  536. }
  537. /**
  538. * Moves a field in a given position
  539. *
  540. * Available actions are:
  541. *
  542. * * sfWidgetFormSchema::BEFORE
  543. * * sfWidgetFormSchema::AFTER
  544. * * sfWidgetFormSchema::LAST
  545. * * sfWidgetFormSchema::FIRST
  546. *
  547. * @param string The field name to move
  548. * @param constant The action (see above for all possible actions)
  549. * @param string The field name used for AFTER and BEFORE actions
  550. */
  551. public function moveField($field, $action, $pivot = null)
  552. {
  553. if (false === $fieldPosition = array_search($field, $this->positions))
  554. {
  555. throw new InvalidArgumentException(sprintf('Field "%s" does not exist.', $field));
  556. }
  557. unset($this->positions[$fieldPosition]);
  558. $this->positions = array_values($this->positions);
  559. if (!is_null($pivot))
  560. {
  561. if (false === $pivotPosition = array_search($pivot, $this->positions))
  562. {
  563. throw new InvalidArgumentException(sprintf('Field "%s" does not exist.', $pivot));
  564. }
  565. }
  566. switch ($action)
  567. {
  568. case sfWidgetFormSchema::FIRST:
  569. array_unshift($this->positions, $field);
  570. break;
  571. case sfWidgetFormSchema::LAST:
  572. array_push($this->positions, $field);
  573. break;
  574. case sfWidgetFormSchema::BEFORE:
  575. if (is_null($pivot))
  576. {
  577. throw new LogicException(sprintf('Unable to move field "%s" without a relative field.', $field));
  578. }
  579. $this->positions = array_merge(
  580. array_slice($this->positions, 0, $pivotPosition),
  581. array($field),
  582. array_slice($this->positions, $pivotPosition)
  583. );
  584. break;
  585. case sfWidgetFormSchema::AFTER:
  586. if (is_null($pivot))
  587. {
  588. throw new LogicException(sprintf('Unable to move field "%s" without a relative field.', $field));
  589. }
  590. $this->positions = array_merge(
  591. array_slice($this->positions, 0, $pivotPosition + 1),
  592. array($field),
  593. array_slice($this->positions, $pivotPosition + 1)
  594. );
  595. break;
  596. default:
  597. throw new LogicException(sprintf('Unknown move operation for field "%s".', $field));
  598. }
  599. }
  600. public function __clone()
  601. {
  602. foreach ($this->fields as $name => $field)
  603. {
  604. // offsetSet will clone the field and change the parent
  605. $this[$name] = $field;
  606. }
  607. foreach ($this->formFormatters as &$formFormatter)
  608. {
  609. $formFormatter = clone $formFormatter;
  610. $formFormatter->setWidgetSchema($this);
  611. }
  612. }
  613. }