sfWidgetFormSchema.class.php 21 KB

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