PageRenderTime 64ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/protected/vendors/Zend/Form.php

https://bitbucket.org/negge/tlklan2
PHP | 3399 lines | 1971 code | 338 blank | 1090 comment | 321 complexity | e5ec9e82235f66da9ae54f76aca6424b MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, BSD-2-Clause, GPL-3.0
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Form
  17. * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. */
  20. /** @see Zend_Validate_Interface */
  21. require_once 'Zend/Validate/Interface.php';
  22. /**
  23. * Zend_Form
  24. *
  25. * @category Zend
  26. * @package Zend_Form
  27. * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
  28. * @license http://framework.zend.com/license/new-bsd New BSD License
  29. * @version $Id: Form.php 24848 2012-05-31 19:28:48Z rob $
  30. */
  31. class Zend_Form implements Iterator, Countable, Zend_Validate_Interface
  32. {
  33. /**#@+
  34. * Plugin loader type constants
  35. */
  36. const DECORATOR = 'DECORATOR';
  37. const ELEMENT = 'ELEMENT';
  38. /**#@-*/
  39. /**#@+
  40. * Method type constants
  41. */
  42. const METHOD_DELETE = 'delete';
  43. const METHOD_GET = 'get';
  44. const METHOD_POST = 'post';
  45. const METHOD_PUT = 'put';
  46. /**#@-*/
  47. /**#@+
  48. * Encoding type constants
  49. */
  50. const ENCTYPE_URLENCODED = 'application/x-www-form-urlencoded';
  51. const ENCTYPE_MULTIPART = 'multipart/form-data';
  52. /**#@-*/
  53. /**
  54. * Form metadata and attributes
  55. * @var array
  56. */
  57. protected $_attribs = array();
  58. /**
  59. * Decorators for rendering
  60. * @var array
  61. */
  62. protected $_decorators = array();
  63. /**
  64. * Default display group class
  65. * @var string
  66. */
  67. protected $_defaultDisplayGroupClass = 'Zend_Form_DisplayGroup';
  68. /**
  69. * Form description
  70. * @var string
  71. */
  72. protected $_description;
  73. /**
  74. * Should we disable loading the default decorators?
  75. * @var bool
  76. */
  77. protected $_disableLoadDefaultDecorators = false;
  78. /**
  79. * Display group prefix paths
  80. * @var array
  81. */
  82. protected $_displayGroupPrefixPaths = array();
  83. /**
  84. * Groups of elements grouped for display purposes
  85. * @var array
  86. */
  87. protected $_displayGroups = array();
  88. /**
  89. * Global decorators to apply to all elements
  90. * @var null|array
  91. */
  92. protected $_elementDecorators;
  93. /**
  94. * Prefix paths to use when creating elements
  95. * @var array
  96. */
  97. protected $_elementPrefixPaths = array();
  98. /**
  99. * Form elements
  100. * @var array
  101. */
  102. protected $_elements = array();
  103. /**
  104. * Array to which elements belong (if any)
  105. * @var string
  106. */
  107. protected $_elementsBelongTo;
  108. /**
  109. * Custom form-level error messages
  110. * @var array
  111. */
  112. protected $_errorMessages = array();
  113. /**
  114. * Are there errors in the form?
  115. * @var bool
  116. */
  117. protected $_errorsExist = false;
  118. /**
  119. * Has the form been manually flagged as an error?
  120. * @var bool
  121. */
  122. protected $_errorsForced = false;
  123. /**
  124. * Form order
  125. * @var int|null
  126. */
  127. protected $_formOrder;
  128. /**
  129. * Whether or not form elements are members of an array
  130. * @var bool
  131. */
  132. protected $_isArray = false;
  133. /**
  134. * Form legend
  135. * @var string
  136. */
  137. protected $_legend;
  138. /**
  139. * Plugin loaders
  140. * @var array
  141. */
  142. protected $_loaders = array();
  143. /**
  144. * Allowed form methods
  145. * @var array
  146. */
  147. protected $_methods = array('delete', 'get', 'post', 'put');
  148. /**
  149. * Order in which to display and iterate elements
  150. * @var array
  151. */
  152. protected $_order = array();
  153. /**
  154. * Whether internal order has been updated or not
  155. * @var bool
  156. */
  157. protected $_orderUpdated = false;
  158. /**
  159. * Sub form prefix paths
  160. * @var array
  161. */
  162. protected $_subFormPrefixPaths = array();
  163. /**
  164. * Sub forms
  165. * @var array
  166. */
  167. protected $_subForms = array();
  168. /**
  169. * @var Zend_Translate
  170. */
  171. protected $_translator;
  172. /**
  173. * Global default translation adapter
  174. * @var Zend_Translate
  175. */
  176. protected static $_translatorDefault;
  177. /**
  178. * is the translator disabled?
  179. * @var bool
  180. */
  181. protected $_translatorDisabled = false;
  182. /**
  183. * @var Zend_View_Interface
  184. */
  185. protected $_view;
  186. /**
  187. * @var bool
  188. */
  189. protected $_isRendered = false;
  190. /**
  191. * Constructor
  192. *
  193. * Registers form view helper as decorator
  194. *
  195. * @param mixed $options
  196. * @return void
  197. */
  198. public function __construct($options = null)
  199. {
  200. if (is_array($options)) {
  201. $this->setOptions($options);
  202. } elseif ($options instanceof Zend_Config) {
  203. $this->setConfig($options);
  204. }
  205. // Extensions...
  206. $this->init();
  207. $this->loadDefaultDecorators();
  208. }
  209. /**
  210. * Clone form object and all children
  211. *
  212. * @return void
  213. */
  214. public function __clone()
  215. {
  216. $elements = array();
  217. foreach ($this->getElements() as $name => $element) {
  218. $elements[] = clone $element;
  219. }
  220. $this->setElements($elements);
  221. $subForms = array();
  222. foreach ($this->getSubForms() as $name => $subForm) {
  223. $subForms[$name] = clone $subForm;
  224. }
  225. $this->setSubForms($subForms);
  226. $displayGroups = array();
  227. foreach ($this->_displayGroups as $group) {
  228. $clone = clone $group;
  229. $elements = array();
  230. foreach ($clone->getElements() as $name => $e) {
  231. $elements[] = $this->getElement($name);
  232. }
  233. $clone->setElements($elements);
  234. $displayGroups[] = $clone;
  235. }
  236. $this->setDisplayGroups($displayGroups);
  237. }
  238. /**
  239. * Reset values of form
  240. *
  241. * @return Zend_Form
  242. */
  243. public function reset()
  244. {
  245. foreach ($this->getElements() as $element) {
  246. $element->setValue(null);
  247. }
  248. foreach ($this->getSubForms() as $subForm) {
  249. $subForm->reset();
  250. }
  251. return $this;
  252. }
  253. /**
  254. * Initialize form (used by extending classes)
  255. *
  256. * @return void
  257. */
  258. public function init()
  259. {
  260. }
  261. /**
  262. * Set form state from options array
  263. *
  264. * @param array $options
  265. * @return Zend_Form
  266. */
  267. public function setOptions(array $options)
  268. {
  269. if (isset($options['prefixPath'])) {
  270. $this->addPrefixPaths($options['prefixPath']);
  271. unset($options['prefixPath']);
  272. }
  273. if (isset($options['elementPrefixPath'])) {
  274. $this->addElementPrefixPaths($options['elementPrefixPath']);
  275. unset($options['elementPrefixPath']);
  276. }
  277. if (isset($options['displayGroupPrefixPath'])) {
  278. $this->addDisplayGroupPrefixPaths($options['displayGroupPrefixPath']);
  279. unset($options['displayGroupPrefixPath']);
  280. }
  281. if (isset($options['elementDecorators'])) {
  282. $this->_elementDecorators = $options['elementDecorators'];
  283. unset($options['elementDecorators']);
  284. }
  285. if (isset($options['elements'])) {
  286. $this->setElements($options['elements']);
  287. unset($options['elements']);
  288. }
  289. if (isset($options['defaultDisplayGroupClass'])) {
  290. $this->setDefaultDisplayGroupClass($options['defaultDisplayGroupClass']);
  291. unset($options['defaultDisplayGroupClass']);
  292. }
  293. if (isset($options['displayGroupDecorators'])) {
  294. $displayGroupDecorators = $options['displayGroupDecorators'];
  295. unset($options['displayGroupDecorators']);
  296. }
  297. if (isset($options['elementsBelongTo'])) {
  298. $elementsBelongTo = $options['elementsBelongTo'];
  299. unset($options['elementsBelongTo']);
  300. }
  301. if (isset($options['attribs'])) {
  302. $this->addAttribs($options['attribs']);
  303. unset($options['attribs']);
  304. }
  305. $forbidden = array(
  306. 'Options', 'Config', 'PluginLoader', 'SubForms', 'Translator',
  307. 'Attrib', 'Default',
  308. );
  309. foreach ($options as $key => $value) {
  310. $normalized = ucfirst($key);
  311. if (in_array($normalized, $forbidden)) {
  312. continue;
  313. }
  314. $method = 'set' . $normalized;
  315. if (method_exists($this, $method)) {
  316. if($normalized == 'View' && !($value instanceof Zend_View_Interface)) {
  317. continue;
  318. }
  319. $this->$method($value);
  320. } else {
  321. $this->setAttrib($key, $value);
  322. }
  323. }
  324. if (isset($displayGroupDecorators)) {
  325. $this->setDisplayGroupDecorators($displayGroupDecorators);
  326. }
  327. if (isset($elementsBelongTo)) {
  328. $this->setElementsBelongTo($elementsBelongTo);
  329. }
  330. return $this;
  331. }
  332. /**
  333. * Set form state from config object
  334. *
  335. * @param Zend_Config $config
  336. * @return Zend_Form
  337. */
  338. public function setConfig(Zend_Config $config)
  339. {
  340. return $this->setOptions($config->toArray());
  341. }
  342. // Loaders
  343. /**
  344. * Set plugin loaders for use with decorators and elements
  345. *
  346. * @param Zend_Loader_PluginLoader_Interface $loader
  347. * @param string $type 'decorator' or 'element'
  348. * @return Zend_Form
  349. * @throws Zend_Form_Exception on invalid type
  350. */
  351. public function setPluginLoader(Zend_Loader_PluginLoader_Interface $loader, $type = null)
  352. {
  353. $type = strtoupper($type);
  354. switch ($type) {
  355. case self::DECORATOR:
  356. case self::ELEMENT:
  357. $this->_loaders[$type] = $loader;
  358. return $this;
  359. default:
  360. require_once 'Zend/Form/Exception.php';
  361. throw new Zend_Form_Exception(sprintf('Invalid type "%s" provided to setPluginLoader()', $type));
  362. }
  363. }
  364. /**
  365. * Retrieve plugin loader for given type
  366. *
  367. * $type may be one of:
  368. * - decorator
  369. * - element
  370. *
  371. * If a plugin loader does not exist for the given type, defaults are
  372. * created.
  373. *
  374. * @param string $type
  375. * @return Zend_Loader_PluginLoader_Interface
  376. */
  377. public function getPluginLoader($type = null)
  378. {
  379. $type = strtoupper($type);
  380. if (!isset($this->_loaders[$type])) {
  381. switch ($type) {
  382. case self::DECORATOR:
  383. $prefixSegment = 'Form_Decorator';
  384. $pathSegment = 'Form/Decorator';
  385. break;
  386. case self::ELEMENT:
  387. $prefixSegment = 'Form_Element';
  388. $pathSegment = 'Form/Element';
  389. break;
  390. default:
  391. require_once 'Zend/Form/Exception.php';
  392. throw new Zend_Form_Exception(sprintf('Invalid type "%s" provided to getPluginLoader()', $type));
  393. }
  394. require_once 'Zend/Loader/PluginLoader.php';
  395. $this->_loaders[$type] = new Zend_Loader_PluginLoader(
  396. array('Zend_' . $prefixSegment . '_' => 'Zend/' . $pathSegment . '/')
  397. );
  398. }
  399. return $this->_loaders[$type];
  400. }
  401. /**
  402. * Add prefix path for plugin loader
  403. *
  404. * If no $type specified, assumes it is a base path for both filters and
  405. * validators, and sets each according to the following rules:
  406. * - decorators: $prefix = $prefix . '_Decorator'
  407. * - elements: $prefix = $prefix . '_Element'
  408. *
  409. * Otherwise, the path prefix is set on the appropriate plugin loader.
  410. *
  411. * If $type is 'decorator', sets the path in the decorator plugin loader
  412. * for all elements. Additionally, if no $type is provided,
  413. * the prefix and path is added to both decorator and element
  414. * plugin loader with following settings:
  415. * $prefix . '_Decorator', $path . '/Decorator/'
  416. * $prefix . '_Element', $path . '/Element/'
  417. *
  418. * @param string $prefix
  419. * @param string $path
  420. * @param string $type
  421. * @return Zend_Form
  422. * @throws Zend_Form_Exception for invalid type
  423. */
  424. public function addPrefixPath($prefix, $path, $type = null)
  425. {
  426. $type = strtoupper($type);
  427. switch ($type) {
  428. case self::DECORATOR:
  429. case self::ELEMENT:
  430. $loader = $this->getPluginLoader($type);
  431. $loader->addPrefixPath($prefix, $path);
  432. return $this;
  433. case null:
  434. $nsSeparator = (false !== strpos($prefix, '\\'))?'\\':'_';
  435. $prefix = rtrim($prefix, $nsSeparator);
  436. $path = rtrim($path, DIRECTORY_SEPARATOR);
  437. foreach (array(self::DECORATOR, self::ELEMENT) as $type) {
  438. $cType = ucfirst(strtolower($type));
  439. $pluginPath = $path . DIRECTORY_SEPARATOR . $cType . DIRECTORY_SEPARATOR;
  440. $pluginPrefix = $prefix . $nsSeparator . $cType;
  441. $loader = $this->getPluginLoader($type);
  442. $loader->addPrefixPath($pluginPrefix, $pluginPath);
  443. }
  444. return $this;
  445. default:
  446. require_once 'Zend/Form/Exception.php';
  447. throw new Zend_Form_Exception(sprintf('Invalid type "%s" provided to getPluginLoader()', $type));
  448. }
  449. }
  450. /**
  451. * Add many prefix paths at once
  452. *
  453. * @param array $spec
  454. * @return Zend_Form
  455. */
  456. public function addPrefixPaths(array $spec)
  457. {
  458. if (isset($spec['prefix']) && isset($spec['path'])) {
  459. return $this->addPrefixPath($spec['prefix'], $spec['path']);
  460. }
  461. foreach ($spec as $type => $paths) {
  462. if (is_numeric($type) && is_array($paths)) {
  463. $type = null;
  464. if (isset($paths['prefix']) && isset($paths['path'])) {
  465. if (isset($paths['type'])) {
  466. $type = $paths['type'];
  467. }
  468. $this->addPrefixPath($paths['prefix'], $paths['path'], $type);
  469. }
  470. } elseif (!is_numeric($type)) {
  471. if (!isset($paths['prefix']) || !isset($paths['path'])) {
  472. continue;
  473. }
  474. $this->addPrefixPath($paths['prefix'], $paths['path'], $type);
  475. }
  476. }
  477. return $this;
  478. }
  479. /**
  480. * Add prefix path for all elements
  481. *
  482. * @param string $prefix
  483. * @param string $path
  484. * @param string $type
  485. * @return Zend_Form
  486. */
  487. public function addElementPrefixPath($prefix, $path, $type = null)
  488. {
  489. $this->_elementPrefixPaths[] = array(
  490. 'prefix' => $prefix,
  491. 'path' => $path,
  492. 'type' => $type,
  493. );
  494. foreach ($this->getElements() as $element) {
  495. $element->addPrefixPath($prefix, $path, $type);
  496. }
  497. foreach ($this->getSubForms() as $subForm) {
  498. $subForm->addElementPrefixPath($prefix, $path, $type);
  499. }
  500. return $this;
  501. }
  502. /**
  503. * Add prefix paths for all elements
  504. *
  505. * @param array $spec
  506. * @return Zend_Form
  507. */
  508. public function addElementPrefixPaths(array $spec)
  509. {
  510. $this->_elementPrefixPaths = $this->_elementPrefixPaths + $spec;
  511. foreach ($this->getElements() as $element) {
  512. $element->addPrefixPaths($spec);
  513. }
  514. return $this;
  515. }
  516. /**
  517. * Add prefix path for all display groups
  518. *
  519. * @param string $prefix
  520. * @param string $path
  521. * @return Zend_Form
  522. */
  523. public function addDisplayGroupPrefixPath($prefix, $path)
  524. {
  525. $this->_displayGroupPrefixPaths[] = array(
  526. 'prefix' => $prefix,
  527. 'path' => $path,
  528. );
  529. foreach ($this->getDisplayGroups() as $group) {
  530. $group->addPrefixPath($prefix, $path);
  531. }
  532. return $this;
  533. }
  534. /**
  535. * Add multiple display group prefix paths at once
  536. *
  537. * @param array $spec
  538. * @return Zend_Form
  539. */
  540. public function addDisplayGroupPrefixPaths(array $spec)
  541. {
  542. foreach ($spec as $key => $value) {
  543. if (is_string($value) && !is_numeric($key)) {
  544. $this->addDisplayGroupPrefixPath($key, $value);
  545. continue;
  546. }
  547. if (is_string($value) && is_numeric($key)) {
  548. continue;
  549. }
  550. if (is_array($value)) {
  551. $count = count($value);
  552. if (array_keys($value) === range(0, $count - 1)) {
  553. if ($count < 2) {
  554. continue;
  555. }
  556. $prefix = array_shift($value);
  557. $path = array_shift($value);
  558. $this->addDisplayGroupPrefixPath($prefix, $path);
  559. continue;
  560. }
  561. if (array_key_exists('prefix', $value) && array_key_exists('path', $value)) {
  562. $this->addDisplayGroupPrefixPath($value['prefix'], $value['path']);
  563. }
  564. }
  565. }
  566. return $this;
  567. }
  568. // Form metadata:
  569. /**
  570. * Set form attribute
  571. *
  572. * @param string $key
  573. * @param mixed $value
  574. * @return Zend_Form
  575. */
  576. public function setAttrib($key, $value)
  577. {
  578. $key = (string) $key;
  579. $this->_attribs[$key] = $value;
  580. return $this;
  581. }
  582. /**
  583. * Add multiple form attributes at once
  584. *
  585. * @param array $attribs
  586. * @return Zend_Form
  587. */
  588. public function addAttribs(array $attribs)
  589. {
  590. foreach ($attribs as $key => $value) {
  591. $this->setAttrib($key, $value);
  592. }
  593. return $this;
  594. }
  595. /**
  596. * Set multiple form attributes at once
  597. *
  598. * Overwrites any previously set attributes.
  599. *
  600. * @param array $attribs
  601. * @return Zend_Form
  602. */
  603. public function setAttribs(array $attribs)
  604. {
  605. $this->clearAttribs();
  606. return $this->addAttribs($attribs);
  607. }
  608. /**
  609. * Retrieve a single form attribute
  610. *
  611. * @param string $key
  612. * @return mixed
  613. */
  614. public function getAttrib($key)
  615. {
  616. $key = (string) $key;
  617. if (!isset($this->_attribs[$key])) {
  618. return null;
  619. }
  620. return $this->_attribs[$key];
  621. }
  622. /**
  623. * Retrieve all form attributes/metadata
  624. *
  625. * @return array
  626. */
  627. public function getAttribs()
  628. {
  629. return $this->_attribs;
  630. }
  631. /**
  632. * Remove attribute
  633. *
  634. * @param string $key
  635. * @return bool
  636. */
  637. public function removeAttrib($key)
  638. {
  639. if (isset($this->_attribs[$key])) {
  640. unset($this->_attribs[$key]);
  641. return true;
  642. }
  643. return false;
  644. }
  645. /**
  646. * Clear all form attributes
  647. *
  648. * @return Zend_Form
  649. */
  650. public function clearAttribs()
  651. {
  652. $this->_attribs = array();
  653. return $this;
  654. }
  655. /**
  656. * Set form action
  657. *
  658. * @param string $action
  659. * @return Zend_Form
  660. */
  661. public function setAction($action)
  662. {
  663. return $this->setAttrib('action', (string) $action);
  664. }
  665. /**
  666. * Get form action
  667. *
  668. * Sets default to '' if not set.
  669. *
  670. * @return string
  671. */
  672. public function getAction()
  673. {
  674. $action = $this->getAttrib('action');
  675. if (null === $action) {
  676. $action = '';
  677. $this->setAction($action);
  678. }
  679. return $action;
  680. }
  681. /**
  682. * Set form method
  683. *
  684. * Only values in {@link $_methods()} allowed
  685. *
  686. * @param string $method
  687. * @return Zend_Form
  688. * @throws Zend_Form_Exception
  689. */
  690. public function setMethod($method)
  691. {
  692. $method = strtolower($method);
  693. if (!in_array($method, $this->_methods)) {
  694. require_once 'Zend/Form/Exception.php';
  695. throw new Zend_Form_Exception(sprintf('"%s" is an invalid form method', $method));
  696. }
  697. $this->setAttrib('method', $method);
  698. return $this;
  699. }
  700. /**
  701. * Retrieve form method
  702. *
  703. * @return string
  704. */
  705. public function getMethod()
  706. {
  707. if (null === ($method = $this->getAttrib('method'))) {
  708. $method = self::METHOD_POST;
  709. $this->setAttrib('method', $method);
  710. }
  711. return strtolower($method);
  712. }
  713. /**
  714. * Set encoding type
  715. *
  716. * @param string $value
  717. * @return Zend_Form
  718. */
  719. public function setEnctype($value)
  720. {
  721. $this->setAttrib('enctype', $value);
  722. return $this;
  723. }
  724. /**
  725. * Get encoding type
  726. *
  727. * @return string
  728. */
  729. public function getEnctype()
  730. {
  731. if (null === ($enctype = $this->getAttrib('enctype'))) {
  732. $enctype = self::ENCTYPE_URLENCODED;
  733. $this->setAttrib('enctype', $enctype);
  734. }
  735. return $this->getAttrib('enctype');
  736. }
  737. /**
  738. * Filter a name to only allow valid variable characters
  739. *
  740. * @param string $value
  741. * @param bool $allowBrackets
  742. * @return string
  743. */
  744. public function filterName($value, $allowBrackets = false)
  745. {
  746. $charset = '^a-zA-Z0-9_\x7f-\xff';
  747. if ($allowBrackets) {
  748. $charset .= '\[\]';
  749. }
  750. return preg_replace('/[' . $charset . ']/', '', (string) $value);
  751. }
  752. /**
  753. * Set form name
  754. *
  755. * @param string $name
  756. * @return Zend_Form
  757. */
  758. public function setName($name)
  759. {
  760. $name = $this->filterName($name);
  761. if ('' === (string)$name) {
  762. require_once 'Zend/Form/Exception.php';
  763. throw new Zend_Form_Exception('Invalid name provided; must contain only valid variable characters and be non-empty');
  764. }
  765. return $this->setAttrib('name', $name);
  766. }
  767. /**
  768. * Get name attribute
  769. *
  770. * @return null|string
  771. */
  772. public function getName()
  773. {
  774. return $this->getAttrib('name');
  775. }
  776. /**
  777. * Get fully qualified name
  778. *
  779. * Places name as subitem of array and/or appends brackets.
  780. *
  781. * @return string
  782. */
  783. public function getFullyQualifiedName()
  784. {
  785. return $this->getName();
  786. }
  787. /**
  788. * Get element id
  789. *
  790. * @return string
  791. */
  792. public function getId()
  793. {
  794. if (null !== ($id = $this->getAttrib('id'))) {
  795. return $id;
  796. }
  797. $id = $this->getFullyQualifiedName();
  798. // Bail early if no array notation detected
  799. if (!strstr($id, '[')) {
  800. return $id;
  801. }
  802. // Strip array notation
  803. if ('[]' == substr($id, -2)) {
  804. $id = substr($id, 0, strlen($id) - 2);
  805. }
  806. $id = str_replace('][', '-', $id);
  807. $id = str_replace(array(']', '['), '-', $id);
  808. $id = trim($id, '-');
  809. return $id;
  810. }
  811. /**
  812. * Set form legend
  813. *
  814. * @param string $value
  815. * @return Zend_Form
  816. */
  817. public function setLegend($value)
  818. {
  819. $this->_legend = (string) $value;
  820. return $this;
  821. }
  822. /**
  823. * Get form legend
  824. *
  825. * @return string
  826. */
  827. public function getLegend()
  828. {
  829. return $this->_legend;
  830. }
  831. /**
  832. * Set form description
  833. *
  834. * @param string $value
  835. * @return Zend_Form
  836. */
  837. public function setDescription($value)
  838. {
  839. $this->_description = (string) $value;
  840. return $this;
  841. }
  842. /**
  843. * Retrieve form description
  844. *
  845. * @return string
  846. */
  847. public function getDescription()
  848. {
  849. return $this->_description;
  850. }
  851. /**
  852. * Set form order
  853. *
  854. * @param int $index
  855. * @return Zend_Form
  856. */
  857. public function setOrder($index)
  858. {
  859. $this->_formOrder = (int) $index;
  860. return $this;
  861. }
  862. /**
  863. * Get form order
  864. *
  865. * @return int|null
  866. */
  867. public function getOrder()
  868. {
  869. return $this->_formOrder;
  870. }
  871. /**
  872. * When calling renderFormElements or render this method
  873. * is used to set $_isRendered member to prevent repeatedly
  874. * merging belongsTo setting
  875. */
  876. protected function _setIsRendered()
  877. {
  878. $this->_isRendered = true;
  879. return $this;
  880. }
  881. /**
  882. * Get the value of $_isRendered member
  883. */
  884. protected function _getIsRendered()
  885. {
  886. return (bool)$this->_isRendered;
  887. }
  888. // Element interaction:
  889. /**
  890. * Add a new element
  891. *
  892. * $element may be either a string element type, or an object of type
  893. * Zend_Form_Element. If a string element type is provided, $name must be
  894. * provided, and $options may be optionally provided for configuring the
  895. * element.
  896. *
  897. * If a Zend_Form_Element is provided, $name may be optionally provided,
  898. * and any provided $options will be ignored.
  899. *
  900. * @param string|Zend_Form_Element $element
  901. * @param string $name
  902. * @param array|Zend_Config $options
  903. * @throws Zend_Form_Exception on invalid element
  904. * @return Zend_Form
  905. */
  906. public function addElement($element, $name = null, $options = null)
  907. {
  908. if (is_string($element)) {
  909. if (null === $name) {
  910. require_once 'Zend/Form/Exception.php';
  911. throw new Zend_Form_Exception('Elements specified by string must have an accompanying name');
  912. }
  913. if (is_array($this->_elementDecorators)) {
  914. if (null === $options) {
  915. $options = array('decorators' => $this->_elementDecorators);
  916. } elseif ($options instanceof Zend_Config) {
  917. $options = $options->toArray();
  918. }
  919. if (is_array($options)
  920. && !array_key_exists('decorators', $options)
  921. ) {
  922. $options['decorators'] = $this->_elementDecorators;
  923. }
  924. }
  925. $this->_elements[$name] = $this->createElement($element, $name, $options);
  926. } elseif ($element instanceof Zend_Form_Element) {
  927. $prefixPaths = array();
  928. $prefixPaths['decorator'] = $this->getPluginLoader('decorator')->getPaths();
  929. if (!empty($this->_elementPrefixPaths)) {
  930. $prefixPaths = array_merge($prefixPaths, $this->_elementPrefixPaths);
  931. }
  932. if (null === $name) {
  933. $name = $element->getName();
  934. }
  935. $this->_elements[$name] = $element;
  936. $this->_elements[$name]->addPrefixPaths($prefixPaths);
  937. } else {
  938. require_once 'Zend/Form/Exception.php';
  939. throw new Zend_Form_Exception('Element must be specified by string or Zend_Form_Element instance');
  940. }
  941. $this->_order[$name] = $this->_elements[$name]->getOrder();
  942. $this->_orderUpdated = true;
  943. $this->_setElementsBelongTo($name);
  944. return $this;
  945. }
  946. /**
  947. * Create an element
  948. *
  949. * Acts as a factory for creating elements. Elements created with this
  950. * method will not be attached to the form, but will contain element
  951. * settings as specified in the form object (including plugin loader
  952. * prefix paths, default decorators, etc.).
  953. *
  954. * @param string $type
  955. * @param string $name
  956. * @param array|Zend_Config $options
  957. * @return Zend_Form_Element
  958. */
  959. public function createElement($type, $name, $options = null)
  960. {
  961. if (!is_string($type)) {
  962. require_once 'Zend/Form/Exception.php';
  963. throw new Zend_Form_Exception('Element type must be a string indicating type');
  964. }
  965. if (!is_string($name)) {
  966. require_once 'Zend/Form/Exception.php';
  967. throw new Zend_Form_Exception('Element name must be a string');
  968. }
  969. $prefixPaths = array();
  970. $prefixPaths['decorator'] = $this->getPluginLoader('decorator')->getPaths();
  971. if (!empty($this->_elementPrefixPaths)) {
  972. $prefixPaths = array_merge($prefixPaths, $this->_elementPrefixPaths);
  973. }
  974. if ($options instanceof Zend_Config) {
  975. $options = $options->toArray();
  976. }
  977. if ((null === $options) || !is_array($options)) {
  978. $options = array('prefixPath' => $prefixPaths);
  979. } elseif (is_array($options)) {
  980. if (array_key_exists('prefixPath', $options)) {
  981. $options['prefixPath'] = array_merge($prefixPaths, $options['prefixPath']);
  982. } else {
  983. $options['prefixPath'] = $prefixPaths;
  984. }
  985. }
  986. $class = $this->getPluginLoader(self::ELEMENT)->load($type);
  987. $element = new $class($name, $options);
  988. return $element;
  989. }
  990. /**
  991. * Add multiple elements at once
  992. *
  993. * @param array $elements
  994. * @return Zend_Form
  995. */
  996. public function addElements(array $elements)
  997. {
  998. foreach ($elements as $key => $spec) {
  999. $name = null;
  1000. if (!is_numeric($key)) {
  1001. $name = $key;
  1002. }
  1003. if (is_string($spec) || ($spec instanceof Zend_Form_Element)) {
  1004. $this->addElement($spec, $name);
  1005. continue;
  1006. }
  1007. if (is_array($spec)) {
  1008. $argc = count($spec);
  1009. $options = array();
  1010. if (isset($spec['type'])) {
  1011. $type = $spec['type'];
  1012. if (isset($spec['name'])) {
  1013. $name = $spec['name'];
  1014. }
  1015. if (isset($spec['options'])) {
  1016. $options = $spec['options'];
  1017. }
  1018. $this->addElement($type, $name, $options);
  1019. } else {
  1020. switch ($argc) {
  1021. case 0:
  1022. continue;
  1023. case (1 <= $argc):
  1024. $type = array_shift($spec);
  1025. case (2 <= $argc):
  1026. if (null === $name) {
  1027. $name = array_shift($spec);
  1028. } else {
  1029. $options = array_shift($spec);
  1030. }
  1031. case (3 <= $argc):
  1032. if (empty($options)) {
  1033. $options = array_shift($spec);
  1034. }
  1035. default:
  1036. $this->addElement($type, $name, $options);
  1037. }
  1038. }
  1039. }
  1040. }
  1041. return $this;
  1042. }
  1043. /**
  1044. * Set form elements (overwrites existing elements)
  1045. *
  1046. * @param array $elements
  1047. * @return Zend_Form
  1048. */
  1049. public function setElements(array $elements)
  1050. {
  1051. $this->clearElements();
  1052. return $this->addElements($elements);
  1053. }
  1054. /**
  1055. * Retrieve a single element
  1056. *
  1057. * @param string $name
  1058. * @return Zend_Form_Element|null
  1059. */
  1060. public function getElement($name)
  1061. {
  1062. if (array_key_exists($name, $this->_elements)) {
  1063. return $this->_elements[$name];
  1064. }
  1065. return null;
  1066. }
  1067. /**
  1068. * Retrieve all elements
  1069. *
  1070. * @return array
  1071. */
  1072. public function getElements()
  1073. {
  1074. return $this->_elements;
  1075. }
  1076. /**
  1077. * Remove element
  1078. *
  1079. * @param string $name
  1080. * @return boolean
  1081. */
  1082. public function removeElement($name)
  1083. {
  1084. $name = (string) $name;
  1085. if (isset($this->_elements[$name])) {
  1086. unset($this->_elements[$name]);
  1087. if (array_key_exists($name, $this->_order)) {
  1088. unset($this->_order[$name]);
  1089. $this->_orderUpdated = true;
  1090. } else {
  1091. foreach ($this->_displayGroups as $group) {
  1092. if (null !== $group->getElement($name)) {
  1093. $group->removeElement($name);
  1094. }
  1095. }
  1096. }
  1097. return true;
  1098. }
  1099. return false;
  1100. }
  1101. /**
  1102. * Remove all form elements
  1103. *
  1104. * @return Zend_Form
  1105. */
  1106. public function clearElements()
  1107. {
  1108. foreach (array_keys($this->_elements) as $key) {
  1109. if (array_key_exists($key, $this->_order)) {
  1110. unset($this->_order[$key]);
  1111. }
  1112. }
  1113. $this->_elements = array();
  1114. $this->_orderUpdated = true;
  1115. return $this;
  1116. }
  1117. /**
  1118. * Set default values for elements
  1119. *
  1120. * Sets values for all elements specified in the array of $defaults.
  1121. *
  1122. * @param array $defaults
  1123. * @return Zend_Form
  1124. */
  1125. public function setDefaults(array $defaults)
  1126. {
  1127. $eBelongTo = null;
  1128. if ($this->isArray()) {
  1129. $eBelongTo = $this->getElementsBelongTo();
  1130. $defaults = $this->_dissolveArrayValue($defaults, $eBelongTo);
  1131. }
  1132. foreach ($this->getElements() as $name => $element) {
  1133. $check = $defaults;
  1134. if (($belongsTo = $element->getBelongsTo()) !== $eBelongTo) {
  1135. $check = $this->_dissolveArrayValue($defaults, $belongsTo);
  1136. }
  1137. if (array_key_exists($name, $check)) {
  1138. $this->setDefault($name, $check[$name]);
  1139. $defaults = $this->_dissolveArrayUnsetKey($defaults, $belongsTo, $name);
  1140. }
  1141. }
  1142. foreach ($this->getSubForms() as $name => $form) {
  1143. if (!$form->isArray() && array_key_exists($name, $defaults)) {
  1144. $form->setDefaults($defaults[$name]);
  1145. } else {
  1146. $form->setDefaults($defaults);
  1147. }
  1148. }
  1149. return $this;
  1150. }
  1151. /**
  1152. * Set default value for an element
  1153. *
  1154. * @param string $name
  1155. * @param mixed $value
  1156. * @return Zend_Form
  1157. */
  1158. public function setDefault($name, $value)
  1159. {
  1160. $name = (string) $name;
  1161. if ($element = $this->getElement($name)) {
  1162. $element->setValue($value);
  1163. } else {
  1164. if (is_scalar($value)) {
  1165. foreach ($this->getSubForms() as $subForm) {
  1166. $subForm->setDefault($name, $value);
  1167. }
  1168. } elseif (is_array($value) && ($subForm = $this->getSubForm($name))) {
  1169. $subForm->setDefaults($value);
  1170. }
  1171. }
  1172. return $this;
  1173. }
  1174. /**
  1175. * Retrieve value for single element
  1176. *
  1177. * @param string $name
  1178. * @return mixed
  1179. */
  1180. public function getValue($name)
  1181. {
  1182. if ($element = $this->getElement($name)) {
  1183. return $element->getValue();
  1184. }
  1185. if ($subForm = $this->getSubForm($name)) {
  1186. return $subForm->getValues(true);
  1187. }
  1188. foreach ($this->getSubForms() as $subForm) {
  1189. if ($name == $subForm->getElementsBelongTo()) {
  1190. return $subForm->getValues(true);
  1191. }
  1192. }
  1193. return null;
  1194. }
  1195. /**
  1196. * Retrieve all form element values
  1197. *
  1198. * @param bool $suppressArrayNotation
  1199. * @return array
  1200. */
  1201. public function getValues($suppressArrayNotation = false)
  1202. {
  1203. $values = array();
  1204. $eBelongTo = null;
  1205. if ($this->isArray()) {
  1206. $eBelongTo = $this->getElementsBelongTo();
  1207. }
  1208. foreach ($this->getElements() as $key => $element) {
  1209. if (!$element->getIgnore()) {
  1210. $merge = array();
  1211. if (($belongsTo = $element->getBelongsTo()) !== $eBelongTo) {
  1212. if ('' !== (string)$belongsTo) {
  1213. $key = $belongsTo . '[' . $key . ']';
  1214. }
  1215. }
  1216. $merge = $this->_attachToArray($element->getValue(), $key);
  1217. $values = $this->_array_replace_recursive($values, $merge);
  1218. }
  1219. }
  1220. foreach ($this->getSubForms() as $key => $subForm) {
  1221. $merge = array();
  1222. if (!$subForm->isArray()) {
  1223. $merge[$key] = $subForm->getValues();
  1224. } else {
  1225. $merge = $this->_attachToArray($subForm->getValues(true),
  1226. $subForm->getElementsBelongTo());
  1227. }
  1228. $values = $this->_array_replace_recursive($values, $merge);
  1229. }
  1230. if (!$suppressArrayNotation &&
  1231. $this->isArray() &&
  1232. !$this->_getIsRendered()) {
  1233. $values = $this->_attachToArray($values, $this->getElementsBelongTo());
  1234. }
  1235. return $values;
  1236. }
  1237. /**
  1238. * Returns only the valid values from the given form input.
  1239. *
  1240. * For models that can be saved in a partially valid state, for example when following the builder,
  1241. * prototype or state patterns it is particularly interessting to retrieve all the current valid
  1242. * values to persist them.
  1243. *
  1244. * @param array $data
  1245. * @param bool $suppressArrayNotation
  1246. * @return array
  1247. */
  1248. public function getValidValues($data, $suppressArrayNotation = false)
  1249. {
  1250. $values = array();
  1251. $eBelongTo = null;
  1252. if ($this->isArray()) {
  1253. $eBelongTo = $this->getElementsBelongTo();
  1254. $data = $this->_dissolveArrayValue($data, $eBelongTo);
  1255. }
  1256. $context = $data;
  1257. foreach ($this->getElements() as $key => $element) {
  1258. if (!$element->getIgnore()) {
  1259. $check = $data;
  1260. if (($belongsTo = $element->getBelongsTo()) !== $eBelongTo) {
  1261. $check = $this->_dissolveArrayValue($data, $belongsTo);
  1262. }
  1263. if (isset($check[$key])) {
  1264. if($element->isValid($check[$key], $context)) {
  1265. $merge = array();
  1266. if ($belongsTo !== $eBelongTo && '' !== (string)$belongsTo) {
  1267. $key = $belongsTo . '[' . $key . ']';
  1268. }
  1269. $merge = $this->_attachToArray($element->getValue(), $key);
  1270. $values = $this->_array_replace_recursive($values, $merge);
  1271. }
  1272. $data = $this->_dissolveArrayUnsetKey($data, $belongsTo, $key);
  1273. }
  1274. }
  1275. }
  1276. foreach ($this->getSubForms() as $key => $form) {
  1277. $merge = array();
  1278. if (isset($data[$key]) && !$form->isArray()) {
  1279. $tmp = $form->getValidValues($data[$key]);
  1280. if (!empty($tmp)) {
  1281. $merge[$key] = $tmp;
  1282. }
  1283. } else {
  1284. $tmp = $form->getValidValues($data, true);
  1285. if (!empty($tmp)) {
  1286. $merge = $this->_attachToArray($tmp, $form->getElementsBelongTo());
  1287. }
  1288. }
  1289. $values = $this->_array_replace_recursive($values, $merge);
  1290. }
  1291. if (!$suppressArrayNotation &&
  1292. $this->isArray() &&
  1293. !empty($values) &&
  1294. !$this->_getIsRendered()) {
  1295. $values = $this->_attachToArray($values, $this->getElementsBelongTo());
  1296. }
  1297. return $values;
  1298. }
  1299. /**
  1300. * Get unfiltered element value
  1301. *
  1302. * @param string $name
  1303. * @return mixed
  1304. */
  1305. public function getUnfilteredValue($name)
  1306. {
  1307. if ($element = $this->getElement($name)) {
  1308. return $element->getUnfilteredValue();
  1309. }
  1310. return null;
  1311. }
  1312. /**
  1313. * Retrieve all unfiltered element values
  1314. *
  1315. * @return array
  1316. */
  1317. public function getUnfilteredValues()
  1318. {
  1319. $values = array();
  1320. foreach ($this->getElements() as $key => $element) {
  1321. $values[$key] = $element->getUnfilteredValue();
  1322. }
  1323. return $values;
  1324. }
  1325. /**
  1326. * Set all elements' filters
  1327. *
  1328. * @param array $filters
  1329. * @return Zend_Form
  1330. */
  1331. public function setElementFilters(array $filters)
  1332. {
  1333. foreach ($this->getElements() as $element) {
  1334. $element->setFilters($filters);
  1335. }
  1336. return $this;
  1337. }
  1338. /**
  1339. * Set name of array elements belong to
  1340. *
  1341. * @param string $array
  1342. * @return Zend_Form
  1343. */
  1344. public function setElementsBelongTo($array)
  1345. {
  1346. $origName = $this->getElementsBelongTo();
  1347. $name = $this->filterName($array, true);
  1348. if ('' === $name) {
  1349. $name = null;
  1350. }
  1351. $this->_elementsBelongTo = $name;
  1352. if (null === $name) {
  1353. $this->setIsArray(false);
  1354. if (null !== $origName) {
  1355. $this->_setElementsBelongTo();
  1356. }
  1357. } else {
  1358. $this->setIsArray(true);
  1359. $this->_setElementsBelongTo();
  1360. }
  1361. return $this;
  1362. }
  1363. /**
  1364. * Set array to which elements belong
  1365. *
  1366. * @param string $name Element name
  1367. * @return void
  1368. */
  1369. protected function _setElementsBelongTo($name = null)
  1370. {
  1371. $array = $this->getElementsBelongTo();
  1372. if (null === $array) {
  1373. return;
  1374. }
  1375. if (null === $name) {
  1376. foreach ($this->getElements() as $element) {
  1377. $element->setBelongsTo($array);
  1378. }
  1379. } else {
  1380. if (null !== ($element = $this->getElement($name))) {
  1381. $element->setBelongsTo($array);
  1382. }
  1383. }
  1384. }
  1385. /**
  1386. * Get name of array elements belong to
  1387. *
  1388. * @return string|null
  1389. */
  1390. public function getElementsBelongTo()
  1391. {
  1392. if ((null === $this->_elementsBelongTo) && $this->isArray()) {
  1393. $name = $this->getName();
  1394. if ('' !== (string)$name) {
  1395. return $name;
  1396. }
  1397. }
  1398. return $this->_elementsBelongTo;
  1399. }
  1400. /**
  1401. * Set flag indicating elements belong to array
  1402. *
  1403. * @param bool $flag Value of flag
  1404. * @return Zend_Form
  1405. */
  1406. public function setIsArray($flag)
  1407. {
  1408. $this->_isArray = (bool) $flag;
  1409. return $this;
  1410. }
  1411. /**
  1412. * Get flag indicating if elements belong to an array
  1413. *
  1414. * @return bool
  1415. */
  1416. public function isArray()
  1417. {
  1418. return $this->_isArray;
  1419. }
  1420. // Element groups:
  1421. /**
  1422. * Add a form group/subform
  1423. *
  1424. * @param Zend_Form $form
  1425. * @param string $name
  1426. * @param int $order
  1427. * @return Zend_Form
  1428. */
  1429. public function addSubForm(Zend_Form $form, $name, $order = null)
  1430. {
  1431. $name = (string) $name;
  1432. foreach ($this->_loaders as $type => $loader) {
  1433. $loaderPaths = $loader->getPaths();
  1434. foreach ($loaderPaths as $prefix => $paths) {
  1435. foreach ($paths as $path) {
  1436. $form->addPrefixPath($prefix, $path, $type);
  1437. }
  1438. }
  1439. }
  1440. if (!empty($this->_elementPrefixPaths)) {
  1441. foreach ($this->_elementPrefixPaths as $spec) {
  1442. list($prefix, $path, $type) = array_values($spec);
  1443. $form->addElementPrefixPath($prefix, $path, $type);
  1444. }
  1445. }
  1446. if (!empty($this->_displayGroupPrefixPaths)) {
  1447. foreach ($this->_displayGroupPrefixPaths as $spec) {
  1448. list($prefix, $path) = array_values($spec);
  1449. $form->addDisplayGroupPrefixPath($prefix, $path);
  1450. }
  1451. }
  1452. if (null !== $order) {
  1453. $form->setOrder($order);
  1454. }
  1455. if (($oldName = $form->getName()) &&
  1456. $oldName !== $name &&
  1457. $oldName === $form->getElementsBelongTo()) {
  1458. $form->setElementsBelongTo($name);
  1459. }
  1460. $form->setName($name);
  1461. $this->_subForms[$name] = $form;
  1462. $this->_order[$name] = $order;
  1463. $this->_orderUpdated = true;
  1464. return $this;
  1465. }
  1466. /**
  1467. * Add multiple form subForms/subforms at once
  1468. *
  1469. * @param array $subForms
  1470. * @return Zend_Form
  1471. */
  1472. public function addSubForms(array $subForms)
  1473. {
  1474. foreach ($subForms as $key => $spec) {
  1475. $name= (string) $key;
  1476. if ($spec instanceof Zend_Form) {
  1477. $this->addSubForm($spec, $name);
  1478. continue;
  1479. }
  1480. if (is_array($spec)) {
  1481. $argc = count($spec);
  1482. $order = null;
  1483. switch ($argc) {
  1484. case 0:
  1485. continue;
  1486. case (1 <= $argc):
  1487. $subForm = array_shift($spec);
  1488. case (2 <= $argc):
  1489. $name = array_shift($spec);
  1490. case (3 <= $argc):
  1491. $order = array_shift($spec);
  1492. default:
  1493. $this->addSubForm($subForm, $name, $order);
  1494. }
  1495. }
  1496. }
  1497. return $this;
  1498. }
  1499. /**
  1500. * Set multiple form subForms/subforms (overwrites)
  1501. *
  1502. * @param array $subForms
  1503. * @return Zend_Form
  1504. */
  1505. public function setSubForms(array $subForms)
  1506. {
  1507. $this->clearSubForms();
  1508. return $this->addSubForms($subForms);
  1509. }
  1510. /**
  1511. * Retrieve a form subForm/subform
  1512. *
  1513. * @param string $name
  1514. * @return Zend_Form|null
  1515. */
  1516. public function getSubForm($name)
  1517. {
  1518. $name = (string) $name;
  1519. if (isset($this->_subForms[$name])) {
  1520. return $this->_subForms[$name];
  1521. }
  1522. return null;
  1523. }
  1524. /**
  1525. * Retrieve all form subForms/subforms
  1526. *
  1527. * @return array
  1528. */
  1529. public function getSubForms()
  1530. {
  1531. return $this->_subForms;
  1532. }
  1533. /**
  1534. * Remove form subForm/subform
  1535. *
  1536. * @param string $name
  1537. * @return boolean
  1538. */
  1539. public function removeSubForm($name)
  1540. {
  1541. $name = (string) $name;
  1542. if (array_key_exists($name, $this->_subForms)) {
  1543. unset($this->_subForms[$name]);
  1544. if (array_key_exists($name, $this->_order)) {
  1545. unset($this->_order[$name]);
  1546. $this->_orderUpdated = true;
  1547. }
  1548. return true;
  1549. }
  1550. return false;
  1551. }
  1552. /**
  1553. * Remove all form subForms/subforms
  1554. *
  1555. * @return Zend_Form
  1556. */
  1557. public function clearSubForms()
  1558. {
  1559. foreach (array_keys($this->_subForms) as $key) {
  1560. if (array_key_exists($key, $this->_order)) {
  1561. unset($this->_order[$key]);
  1562. }
  1563. }
  1564. $this->_subForms = array();
  1565. $this->_orderUpdated = true;
  1566. return $this;
  1567. }
  1568. // Display groups:
  1569. /**
  1570. * Set default display group class
  1571. *
  1572. * @param string $class
  1573. * @return Zend_Form
  1574. */
  1575. public function setDefaultDisplayGroupClass($class)
  1576. {
  1577. $this->_defaultDisplayGroupClass = (string) $class;
  1578. return $this;
  1579. }
  1580. /**
  1581. * Retrieve default display group class
  1582. *
  1583. * @return string
  1584. */
  1585. public function getDefaultDisplayGroupClass()
  1586. {
  1587. return $this->_defaultDisplayGroupClass;
  1588. }
  1589. /**
  1590. * Add a display group
  1591. *
  1592. * Groups named elements for display purposes.
  1593. *
  1594. * If a referenced element does not yet exist in the form, it is omitted.
  1595. *
  1596. * @param array $elements
  1597. * @param string $name
  1598. * @param array|Zend_Config $options
  1599. * @return Zend_Form
  1600. * @throws Zend_Form_Exception if no valid elements provided
  1601. */
  1602. public function addDisplayGroup(array $elements, $name, $options = null)
  1603. {
  1604. $group = array();
  1605. foreach ($elements as $element) {
  1606. if($element instanceof Zend_Form_Element) {
  1607. $elementName = $element->getName();
  1608. if (!isset($this->_elements[$elementName])) {
  1609. $this->addElement($element);
  1610. }
  1611. $element = $elementName;
  1612. }
  1613. if (isset($this->_elements[$element])) {
  1614. $add = $this->getElement($element);
  1615. if (null !== $add) {
  1616. $group[] = $add;
  1617. }
  1618. }
  1619. }
  1620. if (empty($group)) {
  1621. require_once 'Zend/Form/Exception.php';
  1622. throw new Zend_Form_Exception('No valid elements specified for display group');
  1623. }
  1624. $name = (string) $name;
  1625. if (is_array($options)) {
  1626. $options['form'] = $this;
  1627. $options['elements'] = $group;
  1628. } elseif ($options instanceof Zend_Config) {
  1629. $options = $options->toArray();
  1630. $options['form'] = $this;
  1631. $options['elements'] = $group;
  1632. } else {
  1633. $options = array(
  1634. 'form' => $this,
  1635. 'elements' => $group,
  1636. );
  1637. }
  1638. if (isset($options['displayGroupClass'])) {
  1639. $class = $options['displayGroupClass'];
  1640. unset($options['displayGroupClass']);
  1641. } else {
  1642. $class = $this->getDefaultDisplayGroupClass();
  1643. }
  1644. if (!class_exists($class)) {
  1645. require_once 'Zend/Loader.php';
  1646. Zend_Loader::loadClass($class);
  1647. }
  1648. $this->_displayGroups[$name] = new $class(
  1649. $name,
  1650. $this->getPluginLoader(self::DECORATOR),
  1651. $options
  1652. );
  1653. if (!empty($this->_displayGroupPrefixPaths)) {
  1654. $this->_displayGroups[$name]->addPrefixPaths($this->_displayGroupPrefixPaths);
  1655. }
  1656. $this->_order[$name] = $this->_displayGroups[$name]->getOrder();
  1657. $this->_orderUpdated = true;
  1658. return $this;
  1659. }
  1660. /**
  1661. * Add a display group object (used with cloning)
  1662. *
  1663. * @param Zend_Form_DisplayGroup $group
  1664. * @param string|null $name
  1665. * @return Zend_Form
  1666. */
  1667. protected function _addDisplayGroupObject(Zend_Form_DisplayGroup $group, $name = null)
  1668. {
  1669. if (null === $name) {
  1670. $name = $group->getName();
  1671. if ('' === (string)$name) {
  1672. require_once 'Zend/Form/Exception.php';
  1673. throw new Zend_Form_Exception('Invalid display group added; requires name');
  1674. }
  1675. }
  1676. $this->_displayGroups[$name] = $group;
  1677. $group->setForm($this);
  1678. if (!empty($this->_displayGroupPrefixPaths)) {
  1679. $this->_displayGroups[$name]->addPrefixPaths($this->_displayGroupPrefixPaths);
  1680. }
  1681. $this->_order[$name] = $this->_displayGroups[$name]->getOrder();
  1682. $this->_orderUpdated = true;
  1683. return $this;
  1684. }
  1685. /**
  1686. * Add multiple display groups at once
  1687. *
  1688. * @param array $groups
  1689. * @return Zend_Form
  1690. */
  1691. public function addDisplayGroups(array $groups)
  1692. {
  1693. foreach ($groups as $key => $spec) {
  1694. $name = null;
  1695. if (!is_numeric($key)) {
  1696. $name = $key;
  1697. }
  1698. if ($spec instanceof Zend_Form_DisplayGroup) {
  1699. $this->_addDisplayGroupObject($spec);
  1700. }
  1701. if (!is_array($spec) || empty($spec)) {
  1702. continue;
  1703. }
  1704. $argc = count($spec);
  1705. $options = array();
  1706. if (isset($spec['elements'])) {
  1707. $elements = $spec['elements'];
  1708. if (isset($spec['name'])) {
  1709. $name = $spec['name'];
  1710. }
  1711. if (isset($spec['options'])) {
  1712. $options = $spec['options'];
  1713. }
  1714. $this->addDisplayGroup($elements, $name, $options);
  1715. } else {
  1716. switch ($argc) {
  1717. case (1 <= $argc):
  1718. $elements = array_shift($spec);
  1719. if (!is_array($elements) && (null !== $name)) {
  1720. $elements = array_merge((array) $elements, $spec);
  1721. $this->addDisplayGroup($elements, $name);
  1722. break;
  1723. }
  1724. case (2 <= $argc):
  1725. if (null !== $name) {
  1726. $options = array_shift($spec);
  1727. $this->addDisplayGroup($elements, $name, $options);
  1728. break;
  1729. }
  1730. $name = array_shift($spec);
  1731. case (3 <= $argc):
  1732. $options = array_shift($spec);
  1733. default:
  1734. $this->addDisplayGroup($elements, $name, $options);
  1735. }
  1736. }
  1737. }
  1738. return $this;
  1739. }
  1740. /**
  1741. * Add multiple display groups (overwrites)
  1742. *
  1743. * @param array $groups
  1744. * @return Zend_Form
  1745. */
  1746. public function setDisplayGroups(array $groups)
  1747. {
  1748. return $this->clearDisplayGroups()
  1749. ->addDisplayGroups($groups);
  1750. }
  1751. /**
  1752. * Return a display group
  1753. *
  1754. * @param string $name
  1755. * @return Zend_Form_DisplayGroup|null
  1756. */
  1757. public function getDisplayGroup($name)
  1758. {
  1759. $name = (string) $name;
  1760. if (isset($this->_displayGroups[$name])) {
  1761. return $this->_displayGroups[$name];
  1762. }
  1763. return null;
  1764. }
  1765. /**
  1766. * Return all display groups
  1767. *
  1768. * @return array
  1769. */
  1770. public function getDisplayGroups()
  1771. {
  1772. return $this->_displayGroups;
  1773. }
  1774. /**
  1775. * Remove a display group by name
  1776. *
  1777. * @param string $name
  1778. * @return boolean
  1779. */
  1780. public function removeDisplayGroup($name)
  1781. {
  1782. $name = (string) $name;
  1783. if (array_key_exists($name, $this->_displayGroups)) {
  1784. foreach ($this->_displayGroups[$name] as $key => $element) {
  1785. if (array_key_exists($key, $this->_elements)) {
  1786. $this->_order[$key] = $element->getOrder();
  1787. $this->_orderUpdated = true;
  1788. }
  1789. }
  1790. unset($this->_displayGroups[$name]);
  1791. if (array_key_exists($name, $this->_order)) {
  1792. unset($this->_order[$name]);
  1793. $this->_orderUpdated = true;
  1794. }
  1795. return true;
  1796. }
  1797. return false;
  1798. }
  1799. /**
  1800. * Remove all display groups
  1801. *
  1802. * @return Zend_Form
  1803. */
  1804. public function clearDisplayGroups()
  1805. {
  1806. foreach ($this->_displayGroups as $key => $group) {
  1807. if (array_key_exists($key, $this->_order)) {
  1808. unset($this->_order[$key]);
  1809. }
  1810. foreach ($group as $name => $element) {
  1811. if (isset($this->_elements[$name])) {
  1812. $this->_order[$name] = $element->getOrder();
  1813. }
  1814. $this->_order[$name] = $element->getOrder();
  1815. }
  1816. }
  1817. $this->_displayGroups = array();
  1818. $this->_orderUpdated = true;
  1819. return $this;
  1820. }
  1821. // Processing
  1822. /**
  1823. * Populate form
  1824. *
  1825. * Proxies to {@link setDefaults()}
  1826. *
  1827. * @param array $values
  1828. * @return Zend_Form
  1829. */
  1830. public function populate(array $values)
  1831. {
  1832. return $this->setDefaults($values);
  1833. }
  1834. /**
  1835. * Determine array key name from given value
  1836. *
  1837. * Given a value such as foo[bar][baz], returns the last element (in this case, 'baz').
  1838. *
  1839. * @param string $value
  1840. * @return string
  1841. */
  1842. protected function _getArrayName($value)
  1843. {
  1844. if (!is_string($value) || '' === $value) {
  1845. return $value;
  1846. }
  1847. if (!strstr($value, '[')) {
  1848. return $value;
  1849. }
  1850. $endPos = strlen($value) - 1;
  1851. if (']' != $value[$endPos]) {
  1852. return $value;
  1853. }
  1854. $start = strrpos($value, '[') + 1;
  1855. $name = substr($value, $start, $endPos - $start);
  1856. return $name;
  1857. }
  1858. /**
  1859. * Extract the value by walking the array using given array path.
  1860. *
  1861. * Given an array path such as foo[bar][baz], returns the value of the last
  1862. * element (in this case, 'baz').
  1863. *
  1864. * @param array $value Array to walk
  1865. * @param string $arrayPath Array notation path of the part to extract
  1866. * @return string
  1867. */
  1868. protected function _dissolveArrayValue($value, $arrayPath)
  1869. {
  1870. // As long as we have more levels
  1871. while ($arrayPos = strpos($arrayPath, '[')) {
  1872. // Get the next key in the path
  1873. $arrayKey = trim(substr($arrayPath, 0, $arrayPos), ']');
  1874. // Set the potentially final value or the next search point in the array
  1875. if (isset($value[$arrayKey])) {
  1876. $value = $value[$arrayKey];
  1877. }
  1878. // Set the next search point in the path
  1879. $arrayPath = trim(substr($arrayPath, $arrayPos + 1), ']');
  1880. }
  1881. if (isset($value[$arrayPath])) {
  1882. $value = $value[$arrayPath];
  1883. }
  1884. return $value;
  1885. }
  1886. /**
  1887. * Given an array, an optional arrayPath and a key this method
  1888. * dissolves the arrayPath and unsets the key within the array
  1889. * if it exists.
  1890. *
  1891. * @param array $array
  1892. * @param string|null $arrayPath
  1893. * @param string $key
  1894. * @return array
  1895. */
  1896. protected function _dissolveArrayUnsetKey($array, $arrayPath, $key)
  1897. {
  1898. $unset =& $array;
  1899. $path = trim(strtr((string)$arrayPath, array('[' => '/', ']' => '')), '/');
  1900. $segs = ('' !== $path) ? explode('/', $path) : array();
  1901. foreach ($segs as $seg) {
  1902. if (!array_key_exists($seg, (array)$unset)) {
  1903. return $array;
  1904. }
  1905. $unset =& $unset[$seg];
  1906. }
  1907. if (array_key_exists($key, (array)$unset)) {
  1908. unset($unset[$key]);
  1909. }
  1910. return $array;
  1911. }
  1912. /**
  1913. * Converts given arrayPath to an array and attaches given value at the end of it.
  1914. *
  1915. * @param mixed $value The value to attach
  1916. * @param string $arrayPath Given array path to convert and attach to.
  1917. * @return array
  1918. */
  1919. protected function _attachToArray($value, $arrayPath)
  1920. {
  1921. // As long as we have more levels
  1922. while ($arrayPos = strrpos($arrayPath, '[')) {
  1923. // Get the next key in the path
  1924. $arrayKey = trim(substr($arrayPath, $arrayPos + 1), ']');
  1925. // Attach
  1926. $value = array($arrayKey => $value);
  1927. // Set the next search point in the path
  1928. $arrayPath = trim(substr($arrayPath, 0, $arrayPos), ']');
  1929. }
  1930. $value = array($arrayPath => $value);
  1931. return $value;
  1932. }
  1933. /**
  1934. * Returns a one dimensional numerical indexed array with the
  1935. * Elements, SubForms and Elements from DisplayGroups as Values.
  1936. *
  1937. * Subitems are inserted based on their order Setting if set,
  1938. * otherwise they are appended, the resulting numerical index
  1939. * may differ from the order value.
  1940. *
  1941. * @access protected
  1942. * @return array
  1943. */
  1944. public function getElementsAndSubFormsOrdered()
  1945. {
  1946. $ordered = array();
  1947. foreach ($this->_order as $name => $order) {
  1948. $order = isset($order) ? $order : count($ordered);
  1949. if ($this->$name instanceof Zend_Form_Element ||
  1950. $this->$name instanceof Zend_Form) {
  1951. array_splice($ordered, $order, 0, array($this->$name));
  1952. } else if ($this->$name instanceof Zend_Form_DisplayGroup) {
  1953. $subordered = array();
  1954. foreach ($this->$name->getElements() as $element) {
  1955. $suborder = $element->getOrder();
  1956. $suborder = (null !== $suborder) ? $suborder : count($subordered);
  1957. array_splice($subordered, $suborder, 0, array($element));
  1958. }
  1959. if (!empty($subordered)) {
  1960. array_splice($ordered, $order, 0, $subordered);
  1961. }
  1962. }
  1963. }
  1964. return $ordered;
  1965. }
  1966. /**
  1967. * This is a helper function until php 5.3 is widespreaded
  1968. *
  1969. * @param array $into
  1970. * @access protected
  1971. * @return void
  1972. */
  1973. protected function _array_replace_recursive(array $into)
  1974. {
  1975. $fromArrays = array_slice(func_get_args(),1);
  1976. foreach ($fromArrays as $from) {
  1977. foreach ($from as $key => $value) {
  1978. if (is_array($value)) {
  1979. if (!isset($into[$key])) {
  1980. $into[$key] = array();
  1981. }
  1982. $into[$key] = $this->_array_replace_recursive($into[$key], $from[$key]);
  1983. } else {
  1984. $into[$key] = $value;
  1985. }
  1986. }
  1987. }
  1988. return $into;
  1989. }
  1990. /**
  1991. * Validate the form
  1992. *
  1993. * @param array $data
  1994. * @return boolean
  1995. */
  1996. public function isValid($data)
  1997. {
  1998. if (!is_array($data)) {
  1999. require_once 'Zend/Form/Exception.php';
  2000. throw new Zend_Form_Exception(__METHOD__ . ' expects an array');
  2001. }
  2002. $translator = $this->getTranslator();
  2003. $valid = true;
  2004. $eBelongTo = null;
  2005. if ($this->isArray()) {
  2006. $eBelongTo = $this->getElementsBelongTo();
  2007. $data = $this->_dissolveArrayValue($data, $eBelongTo);
  2008. }
  2009. $context = $data;
  2010. foreach ($this->getElements() as $key => $element) {
  2011. if (null !== $translator && $this->hasTranslator()
  2012. && !$element->hasTranslator()) {
  2013. $element->setTranslator($translator);
  2014. }
  2015. $check = $data;
  2016. if (($belongsTo = $element->getBelongsTo()) !== $eBelongTo) {
  2017. $check = $this->_dissolveArrayValue($data, $belongsTo);
  2018. }
  2019. if (!isset($check[$key])) {
  2020. $valid = $element->isValid(null, $context) && $valid;
  2021. } else {
  2022. $valid = $element->isValid($check[$key], $context) && $valid;
  2023. $data = $this->_dissolveArrayUnsetKey($data, $belongsTo, $key);
  2024. }
  2025. }
  2026. foreach ($this->getSubForms() as $key => $form) {
  2027. if (null !== $translator && $this->hasTranslator()
  2028. && !$form->hasTranslator()) {
  2029. $form->setTranslator($translator);
  2030. }
  2031. if (isset($data[$key]) && !$form->isArray()) {
  2032. $valid = $form->isValid($data[$key]) && $valid;
  2033. } else {
  2034. $valid = $form->isValid($data) && $valid;
  2035. }
  2036. }
  2037. $this->_errorsExist = !$valid;
  2038. // If manually flagged as an error, return invalid status
  2039. if ($this->_errorsForced) {
  2040. return false;
  2041. }
  2042. return $valid;
  2043. }
  2044. /**
  2045. * Validate a partial form
  2046. *
  2047. * Does not check for required flags.
  2048. *
  2049. * @param array $data
  2050. * @return boolean
  2051. */
  2052. public function isValidPartial(array $data)
  2053. {
  2054. $eBelongTo = null;
  2055. if ($this->isArray()) {
  2056. $eBelongTo = $this->getElementsBelongTo();
  2057. $data = $this->_dissolveArrayValue($data, $eBelongTo);
  2058. }
  2059. $translator = $this->getTranslator();
  2060. $valid = true;
  2061. $context = $data;
  2062. foreach ($this->getElements() as $key => $element) {
  2063. $check = $data;
  2064. if (($belongsTo = $element->getBelongsTo()) !== $eBelongTo) {
  2065. $check = $this->_dissolveArrayValue($data, $belongsTo);
  2066. }
  2067. if (isset($check[$key])) {
  2068. if (null !== $translator && !$element->hasTranslator()) {
  2069. $element->setTranslator($translator);
  2070. }
  2071. $valid = $element->isValid($check[$key], $context) && $valid;
  2072. $data = $this->_dissolveArrayUnsetKey($data, $belongsTo, $key);
  2073. }
  2074. }
  2075. foreach ($this->getSubForms() as $key => $form) {
  2076. if (null !== $translator && !$form->hasTranslator()) {
  2077. $form->setTranslator($translator);
  2078. }
  2079. if (isset($data[$key]) && !$form->isArray()) {
  2080. $valid = $form->isValidPartial($data[$key]) && $valid;
  2081. } else {
  2082. $valid = $form->isValidPartial($data) && $valid;
  2083. }
  2084. }
  2085. $this->_errorsExist = !$valid;
  2086. return $valid;
  2087. }
  2088. /**
  2089. * Process submitted AJAX data
  2090. *
  2091. * Checks if provided $data is valid, via {@link isValidPartial()}. If so,
  2092. * it returns JSON-encoded boolean true. If not, it returns JSON-encoded
  2093. * error messages (as returned by {@link getMessages()}).
  2094. *
  2095. * @param array $data
  2096. * @return string JSON-encoded boolean true or error messages
  2097. */
  2098. public function processAjax(array $data)
  2099. {
  2100. require_once 'Zend/Json.php';
  2101. if ($this->isValidPartial($data)) {
  2102. return Zend_Json::encode(true);
  2103. }
  2104. $messages = $this->getMessages();
  2105. return Zend_Json::encode($messages);
  2106. }
  2107. /**
  2108. * Add a custom error message to return in the event of failed validation
  2109. *
  2110. * @param string $message
  2111. * @return Zend_Form
  2112. */
  2113. public function addErrorMessage($message)
  2114. {
  2115. $this->_errorMessages[] = (string) $message;
  2116. return $this;
  2117. }
  2118. /**
  2119. * Add multiple custom error messages to return in the event of failed validation
  2120. *
  2121. * @param array $messages
  2122. * @return Zend_Form
  2123. */
  2124. public function addErrorMessages(array $messages)
  2125. {
  2126. foreach ($messages as $message) {
  2127. $this->addErrorMessage($message);
  2128. }
  2129. return $this;
  2130. }
  2131. /**
  2132. * Same as addErrorMessages(), but clears custom error message stack first
  2133. *
  2134. * @param array $messages
  2135. * @return Zend_Form
  2136. */
  2137. public function setErrorMessages(array $messages)
  2138. {
  2139. $this->clearErrorMessages();
  2140. return $this->addErrorMessages($messages);
  2141. }
  2142. /**
  2143. * Retrieve custom error messages
  2144. *
  2145. * @return array
  2146. */
  2147. public function getErrorMessages()
  2148. {
  2149. return $this->_errorMessages;
  2150. }
  2151. /**
  2152. * Clear custom error messages stack
  2153. *
  2154. * @return Zend_Form
  2155. */
  2156. public function clearErrorMessages()
  2157. {
  2158. $this->_errorMessages = array();
  2159. return $this;
  2160. }
  2161. /**
  2162. * Mark the element as being in a failed validation state
  2163. *
  2164. * @return Zend_Form
  2165. */
  2166. public function markAsError()
  2167. {
  2168. $this->_errorsExist = true;
  2169. $this->_errorsForced = true;
  2170. return $this;
  2171. }
  2172. /**
  2173. * Add an error message and mark element as failed validation
  2174. *
  2175. * @param string $message
  2176. * @return Zend_Form
  2177. */
  2178. public function addError($message)
  2179. {
  2180. $this->addErrorMessage($message);
  2181. $this->markAsError();
  2182. return $this;
  2183. }
  2184. /**
  2185. * Add multiple error messages and flag element as failed validation
  2186. *
  2187. * @param array $messages
  2188. * @return Zend_Form
  2189. */
  2190. public function addErrors(array $messages)
  2191. {
  2192. foreach ($messages as $message) {
  2193. $this->addError($message);
  2194. }
  2195. return $this;
  2196. }
  2197. /**
  2198. * Overwrite any previously set error messages and flag as failed validation
  2199. *
  2200. * @param array $messages
  2201. * @return Zend_Form
  2202. */
  2203. public function setErrors(array $messages)
  2204. {
  2205. $this->clearErrorMessages();
  2206. return $this->addErrors($messages);
  2207. }
  2208. public function persistData()
  2209. {
  2210. }
  2211. /**
  2212. * Are there errors in the form?
  2213. *
  2214. * @return bool
  2215. */
  2216. public function isErrors()
  2217. {
  2218. return $this->_errorsExist;
  2219. }
  2220. /**
  2221. * Get error codes for all elements failing validation
  2222. *
  2223. * @param string $name
  2224. * @return array
  2225. */
  2226. public function getErrors($name = null, $suppressArrayNotation = false)
  2227. {
  2228. $errors = array();
  2229. if (null !== $name) {
  2230. if (isset($this->_elements[$name])) {
  2231. return $this->getElement($name)->getErrors();
  2232. } else if (isset($this->_subForms[$name])) {
  2233. return $this->getSubForm($name)->getErrors(null, true);
  2234. }
  2235. }
  2236. foreach ($this->_elements as $key => $element) {
  2237. $errors[$key] = $element->getErrors();
  2238. }
  2239. foreach ($this->getSubForms() as $key => $subForm) {
  2240. $merge = array();
  2241. if (!$subForm->isArray()) {
  2242. $merge[$key] = $subForm->getErrors();
  2243. } else {
  2244. $merge = $this->_attachToArray($subForm->getErrors(null, true),
  2245. $subForm->getElementsBelongTo());
  2246. }
  2247. $errors = $this->_array_replace_recursive($errors, $merge);
  2248. }
  2249. if (!$suppressArrayNotation &&
  2250. $this->isArray() &&
  2251. !$this->_getIsRendered()) {
  2252. $errors = $this->_attachToArray($errors, $this->getElementsBelongTo());
  2253. }
  2254. return $errors;
  2255. }
  2256. /**
  2257. * Retrieve error messages from elements failing validations
  2258. *
  2259. * @param string $name
  2260. * @param bool $suppressArrayNotation
  2261. * @return array
  2262. */
  2263. public function getMessages($name = null, $suppressArrayNotation = false)
  2264. {
  2265. if (null !== $name) {
  2266. if (isset($this->_elements[$name])) {
  2267. return $this->getElement($name)->getMessages();
  2268. } else if (isset($this->_subForms[$name])) {
  2269. return $this->getSubForm($name)->getMessages(null, true);
  2270. }
  2271. foreach ($this->getSubForms() as $key => $subForm) {
  2272. if ($subForm->isArray()) {
  2273. $belongTo = $subForm->getElementsBelongTo();
  2274. if ($name == $this->_getArrayName($belongTo)) {
  2275. return $subForm->getMessages(null, true);
  2276. }
  2277. }
  2278. }
  2279. }
  2280. $customMessages = $this->_getErrorMessages();
  2281. if ($this->isErrors() && !empty($customMessages)) {
  2282. return $customMessages;
  2283. }
  2284. $messages = array();
  2285. foreach ($this->getElements() as $name => $element) {
  2286. $eMessages = $element->getMessages();
  2287. if (!empty($eMessages)) {
  2288. $messages[$name] = $eMessages;
  2289. }
  2290. }
  2291. foreach ($this->getSubForms() as $key => $subForm) {
  2292. $merge = $subForm->getMessages(null, true);
  2293. if (!empty($merge)) {
  2294. if (!$subForm->isArray()) {
  2295. $merge = array($key => $merge);
  2296. } else {
  2297. $merge = $this->_attachToArray($merge,
  2298. $subForm->getElementsBelongTo());
  2299. }
  2300. $messages = $this->_array_replace_recursive($messages, $merge);
  2301. }
  2302. }
  2303. if (!$suppressArrayNotation &&
  2304. $this->isArray() &&
  2305. !$this->_getIsRendered()) {
  2306. $messages = $this->_attachToArray($messages, $this->getElementsBelongTo());
  2307. }
  2308. return $messages;
  2309. }
  2310. /**
  2311. * Retrieve translated custom error messages
  2312. * Proxies to {@link _getErrorMessages()}.
  2313. *
  2314. * @return array
  2315. */
  2316. public function getCustomMessages()
  2317. {
  2318. return $this->_getErrorMessages();
  2319. }
  2320. // Rendering
  2321. /**
  2322. * Set view object
  2323. *
  2324. * @param Zend_View_Interface $view
  2325. * @return Zend_Form
  2326. */
  2327. public function setView(Zend_View_Interface $view = null)
  2328. {
  2329. $this->_view = $view;
  2330. return $this;
  2331. }
  2332. /**
  2333. * Retrieve view object
  2334. *
  2335. * If none registered, attempts to pull from ViewRenderer.
  2336. *
  2337. * @return Zend_View_Interface|null
  2338. */
  2339. public function getView()
  2340. {
  2341. if (null === $this->_view) {
  2342. require_once 'Zend/Controller/Action/HelperBroker.php';
  2343. $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
  2344. $this->setView($viewRenderer->view);
  2345. }
  2346. return $this->_view;
  2347. }
  2348. /**
  2349. * Instantiate a decorator based on class name or class name fragment
  2350. *
  2351. * @param string $name
  2352. * @param null|array $options
  2353. * @return Zend_Form_Decorator_Interface
  2354. */
  2355. protected function _getDecorator($name, $options)
  2356. {
  2357. $class = $this->getPluginLoader(self::DECORATOR)->load($name);
  2358. if (null === $options) {
  2359. $decorator = new $class;
  2360. } else {
  2361. $decorator = new $class($options);
  2362. }
  2363. return $decorator;
  2364. }
  2365. /**
  2366. * Add a decorator for rendering the element
  2367. *
  2368. * @param string|Zend_Form_Decorator_Interface $decorator
  2369. * @param array|Zend_Config $options Options with which to initialize decorator
  2370. * @return Zend_Form
  2371. */
  2372. public function addDecorator($decorator, $options = null)
  2373. {
  2374. if ($decorator instanceof Zend_Form_Decorator_Interface) {
  2375. $name = get_class($decorator);
  2376. } elseif (is_string($decorator)) {
  2377. $name = $decorator;
  2378. $decorator = array(
  2379. 'decorator' => $name,
  2380. 'options' => $options,
  2381. );
  2382. } elseif (is_array($decorator)) {
  2383. foreach ($decorator as $name => $spec) {
  2384. break;
  2385. }
  2386. if (is_numeric($name)) {
  2387. require_once 'Zend/Form/Exception.php';
  2388. throw new Zend_Form_Exception('Invalid alias provided to addDecorator; must be alphanumeric string');
  2389. }
  2390. if (is_string($spec)) {
  2391. $decorator = array(
  2392. 'decorator' => $spec,
  2393. 'options' => $options,
  2394. );
  2395. } elseif ($spec instanceof Zend_Form_Decorator_Interface) {
  2396. $decorator = $spec;
  2397. }
  2398. } else {
  2399. require_once 'Zend/Form/Exception.php';
  2400. throw new Zend_Form_Exception('Invalid decorator provided to addDecorator; must be string or Zend_Form_Decorator_Interface');
  2401. }
  2402. $this->_decorators[$name] = $decorator;
  2403. return $this;
  2404. }
  2405. /**
  2406. * Add many decorators at once
  2407. *
  2408. * @param array $decorators
  2409. * @return Zend_Form
  2410. */
  2411. public function addDecorators(array $decorators)
  2412. {
  2413. foreach ($decorators as $decoratorName => $decoratorInfo) {
  2414. if (is_string($decoratorInfo) ||
  2415. $decoratorInfo instanceof Zend_Form_Decorator_Interface) {
  2416. if (!is_numeric($decoratorName)) {
  2417. $this->addDecorator(array($decoratorName => $decoratorInfo));
  2418. } else {
  2419. $this->addDecorator($decoratorInfo);
  2420. }
  2421. } elseif (is_array($decoratorInfo)) {
  2422. $argc = count($decoratorInfo);
  2423. $options = array();
  2424. if (isset($decoratorInfo['decorator'])) {
  2425. $decorator = $decoratorInfo['decorator'];
  2426. if (isset($decoratorInfo['options'])) {
  2427. $options = $decoratorInfo['options'];
  2428. }
  2429. $this->addDecorator($decorator, $options);
  2430. } else {
  2431. switch (true) {
  2432. case (0 == $argc):
  2433. break;
  2434. case (1 <= $argc):
  2435. $decorator = array_shift($decoratorInfo);
  2436. case (2 <= $argc):
  2437. $options = array_shift($decoratorInfo);
  2438. default:
  2439. $this->addDecorator($decorator, $options);
  2440. break;
  2441. }
  2442. }
  2443. } else {
  2444. require_once 'Zend/Form/Exception.php';
  2445. throw new Zend_Form_Exception('Invalid decorator passed to addDecorators()');
  2446. }
  2447. }
  2448. return $this;
  2449. }
  2450. /**
  2451. * Overwrite all decorators
  2452. *
  2453. * @param array $decorators
  2454. * @return Zend_Form
  2455. */
  2456. public function setDecorators(array $decorators)
  2457. {
  2458. $this->clearDecorators();
  2459. return $this->addDecorators($decorators);
  2460. }
  2461. /**
  2462. * Retrieve a registered decorator
  2463. *
  2464. * @param string $name
  2465. * @return false|Zend_Form_Decorator_Abstract
  2466. */
  2467. public function getDecorator($name)
  2468. {
  2469. if (!isset($this->_decorators[$name])) {
  2470. $len = strlen($name);
  2471. foreach ($this->_decorators as $localName => $decorator) {
  2472. if ($len > strlen($localName)) {
  2473. continue;
  2474. }
  2475. if (0 === substr_compare($localName, $name, -$len, $len, true)) {
  2476. if (is_array($decorator)) {
  2477. return $this->_loadDecorator($decorator, $localName);
  2478. }
  2479. return $decorator;
  2480. }
  2481. }
  2482. return false;
  2483. }
  2484. if (is_array($this->_decorators[$name])) {
  2485. return $this->_loadDecorator($this->_decorators[$name], $name);
  2486. }
  2487. return $this->_decorators[$name];
  2488. }
  2489. /**
  2490. * Retrieve all decorators
  2491. *
  2492. * @return array
  2493. */
  2494. public function getDecorators()
  2495. {
  2496. foreach ($this->_decorators as $key => $value) {
  2497. if (is_array($value)) {
  2498. $this->_loadDecorator($value, $key);
  2499. }
  2500. }
  2501. return $this->_decorators;
  2502. }
  2503. /**
  2504. * Remove a single decorator
  2505. *
  2506. * @param string $name
  2507. * @return bool
  2508. */
  2509. public function removeDecorator($name)
  2510. {
  2511. $decorator = $this->getDecorator($name);
  2512. if ($decorator) {
  2513. if (array_key_exists($name, $this->_decorators)) {
  2514. unset($this->_decorators[$name]);
  2515. } else {
  2516. $class = get_class($decorator);
  2517. if (!array_key_exists($class, $this->_decorators)) {
  2518. return false;
  2519. }
  2520. unset($this->_decorators[$class]);
  2521. }
  2522. return true;
  2523. }
  2524. return false;
  2525. }
  2526. /**
  2527. * Clear all decorators
  2528. *
  2529. * @return Zend_Form
  2530. */
  2531. public function clearDecorators()
  2532. {
  2533. $this->_decorators = array();
  2534. return $this;
  2535. }
  2536. /**
  2537. * Set all element decorators as specified
  2538. *
  2539. * @param array $decorators
  2540. * @param array|null $elements Specific elements to decorate or exclude from decoration
  2541. * @param bool $include Whether $elements is an inclusion or exclusion list
  2542. * @return Zend_Form
  2543. */
  2544. public function setElementDecorators(array $decorators, array $elements = null, $include = true)
  2545. {
  2546. if (is_array($elements)) {
  2547. if ($include) {
  2548. $elementObjs = array();
  2549. foreach ($elements as $name) {
  2550. if (null !== ($element = $this->getElement($name))) {
  2551. $elementObjs[] = $element;
  2552. }
  2553. }
  2554. } else {
  2555. $elementObjs = $this->getElements();
  2556. foreach ($elements as $name) {
  2557. if (array_key_exists($name, $elementObjs)) {
  2558. unset($elementObjs[$name]);
  2559. }
  2560. }
  2561. }
  2562. } else {
  2563. $elementObjs = $this->getElements();
  2564. }
  2565. foreach ($elementObjs as $element) {
  2566. $element->setDecorators($decorators);
  2567. }
  2568. $this->_elementDecorators = $decorators;
  2569. return $this;
  2570. }
  2571. /**
  2572. * Set all display group decorators as specified
  2573. *
  2574. * @param array $decorators
  2575. * @return Zend_Form
  2576. */
  2577. public function setDisplayGroupDecorators(array $decorators)
  2578. {
  2579. foreach ($this->getDisplayGroups() as $group) {
  2580. $group->setDecorators($decorators);
  2581. }
  2582. return $this;
  2583. }
  2584. /**
  2585. * Set all subform decorators as specified
  2586. *
  2587. * @param array $decorators
  2588. * @return Zend_Form
  2589. */
  2590. public function setSubFormDecorators(array $decorators)
  2591. {
  2592. foreach ($this->getSubForms() as $form) {
  2593. $form->setDecorators($decorators);
  2594. }
  2595. return $this;
  2596. }
  2597. /**
  2598. * Render form
  2599. *
  2600. * @param Zend_View_Interface $view
  2601. * @return string
  2602. */
  2603. public function render(Zend_View_Interface $view = null)
  2604. {
  2605. if (null !== $view) {
  2606. $this->setView($view);
  2607. }
  2608. $content = '';
  2609. foreach ($this->getDecorators() as $decorator) {
  2610. $decorator->setElement($this);
  2611. $content = $decorator->render($content);
  2612. }
  2613. $this->_setIsRendered();
  2614. return $content;
  2615. }
  2616. /**
  2617. * Serialize as string
  2618. *
  2619. * Proxies to {@link render()}.
  2620. *
  2621. * @return string
  2622. */
  2623. public function __toString()
  2624. {
  2625. try {
  2626. $return = $this->render();
  2627. return $return;
  2628. } catch (Exception $e) {
  2629. $message = "Exception caught by form: " . $e->getMessage()
  2630. . "\nStack Trace:\n" . $e->getTraceAsString();
  2631. trigger_error($message, E_USER_WARNING);
  2632. return '';
  2633. }
  2634. }
  2635. // Localization:
  2636. /**
  2637. * Set translator object
  2638. *
  2639. * @param Zend_Translate|Zend_Translate_Adapter|null $translator
  2640. * @return Zend_Form
  2641. */
  2642. public function setTranslator($translator = null)
  2643. {
  2644. if (null === $translator) {
  2645. $this->_translator = null;
  2646. } elseif ($translator instanceof Zend_Translate_Adapter) {
  2647. $this->_translator = $translator;
  2648. } elseif ($translator instanceof Zend_Translate) {
  2649. $this->_translator = $translator->getAdapter();
  2650. } else {
  2651. require_once 'Zend/Form/Exception.php';
  2652. throw new Zend_Form_Exception('Invalid translator specified');
  2653. }
  2654. return $this;
  2655. }
  2656. /**
  2657. * Set global default translator object
  2658. *
  2659. * @param Zend_Translate|Zend_Translate_Adapter|null $translator
  2660. * @return void
  2661. */
  2662. public static function setDefaultTranslator($translator = null)
  2663. {
  2664. if (null === $translator) {
  2665. self::$_translatorDefault = null;
  2666. } elseif ($translator instanceof Zend_Translate_Adapter) {
  2667. self::$_translatorDefault = $translator;
  2668. } elseif ($translator instanceof Zend_Translate) {
  2669. self::$_translatorDefault = $translator->getAdapter();
  2670. } else {
  2671. require_once 'Zend/Form/Exception.php';
  2672. throw new Zend_Form_Exception('Invalid translator specified');
  2673. }
  2674. }
  2675. /**
  2676. * Retrieve translator object
  2677. *
  2678. * @return Zend_Translate|null
  2679. */
  2680. public function getTranslator()
  2681. {
  2682. if ($this->translatorIsDisabled()) {
  2683. return null;
  2684. }
  2685. if (null === $this->_translator) {
  2686. return self::getDefaultTranslator();
  2687. }
  2688. return $this->_translator;
  2689. }
  2690. /**
  2691. * Does this form have its own specific translator?
  2692. *
  2693. * @return bool
  2694. */
  2695. public function hasTranslator()
  2696. {
  2697. return (bool)$this->_translator;
  2698. }
  2699. /**
  2700. * Get global default translator object
  2701. *
  2702. * @return null|Zend_Translate
  2703. */
  2704. public static function getDefaultTranslator()
  2705. {
  2706. if (null === self::$_translatorDefault) {
  2707. require_once 'Zend/Registry.php';
  2708. if (Zend_Registry::isRegistered('Zend_Translate')) {
  2709. $translator = Zend_Registry::get('Zend_Translate');
  2710. if ($translator instanceof Zend_Translate_Adapter) {
  2711. return $translator;
  2712. } elseif ($translator instanceof Zend_Translate) {
  2713. return $translator->getAdapter();
  2714. }
  2715. }
  2716. }
  2717. return self::$_translatorDefault;
  2718. }
  2719. /**
  2720. * Is there a default translation object set?
  2721. *
  2722. * @return boolean
  2723. */
  2724. public static function hasDefaultTranslator()
  2725. {
  2726. return (bool)self::$_translatorDefault;
  2727. }
  2728. /**
  2729. * Indicate whether or not translation should be disabled
  2730. *
  2731. * @param bool $flag
  2732. * @return Zend_Form
  2733. */
  2734. public function setDisableTranslator($flag)
  2735. {
  2736. $this->_translatorDisabled = (bool) $flag;
  2737. return $this;
  2738. }
  2739. /**
  2740. * Is translation disabled?
  2741. *
  2742. * @return bool
  2743. */
  2744. public function translatorIsDisabled()
  2745. {
  2746. return $this->_translatorDisabled;
  2747. }
  2748. /**
  2749. * Overloading: access to elements, form groups, and display groups
  2750. *
  2751. * @param string $name
  2752. * @return Zend_Form_Element|Zend_Form|null
  2753. */
  2754. public function __get($name)
  2755. {
  2756. if (isset($this->_elements[$name])) {
  2757. return $this->_elements[$name];
  2758. } elseif (isset($this->_subForms[$name])) {
  2759. return $this->_subForms[$name];
  2760. } elseif (isset($this->_displayGroups[$name])) {
  2761. return $this->_displayGroups[$name];
  2762. }
  2763. return null;
  2764. }
  2765. /**
  2766. * Overloading: access to elements, form groups, and display groups
  2767. *
  2768. * @param string $name
  2769. * @param Zend_Form_Element|Zend_Form $value
  2770. * @return void
  2771. * @throws Zend_Form_Exception for invalid $value
  2772. */
  2773. public function __set($name, $value)
  2774. {
  2775. if ($value instanceof Zend_Form_Element) {
  2776. $this->addElement($value, $name);
  2777. return;
  2778. } elseif ($value instanceof Zend_Form) {
  2779. $this->addSubForm($value, $name);
  2780. return;
  2781. } elseif (is_array($value)) {
  2782. $this->addDisplayGroup($value, $name);
  2783. return;
  2784. }
  2785. require_once 'Zend/Form/Exception.php';
  2786. if (is_object($value)) {
  2787. $type = get_class($value);
  2788. } else {
  2789. $type = gettype($value);
  2790. }
  2791. throw new Zend_Form_Exception('Only form elements and groups may be overloaded; variable of type "' . $type . '" provided');
  2792. }
  2793. /**
  2794. * Overloading: access to elements, form groups, and display groups
  2795. *
  2796. * @param string $name
  2797. * @return boolean
  2798. */
  2799. public function __isset($name)
  2800. {
  2801. if (isset($this->_elements[$name])
  2802. || isset($this->_subForms[$name])
  2803. || isset($this->_displayGroups[$name]))
  2804. {
  2805. return true;
  2806. }
  2807. return false;
  2808. }
  2809. /**
  2810. * Overloading: access to elements, form groups, and display groups
  2811. *
  2812. * @param string $name
  2813. * @return void
  2814. */
  2815. public function __unset($name)
  2816. {
  2817. if (isset($this->_elements[$name])) {
  2818. unset($this->_elements[$name]);
  2819. } elseif (isset($this->_subForms[$name])) {
  2820. unset($this->_subForms[$name]);
  2821. } elseif (isset($this->_displayGroups[$name])) {
  2822. unset($this->_displayGroups[$name]);
  2823. }
  2824. }
  2825. /**
  2826. * Overloading: allow rendering specific decorators
  2827. *
  2828. * Call renderDecoratorName() to render a specific decorator.
  2829. *
  2830. * @param string $method
  2831. * @param array $args
  2832. * @return string
  2833. * @throws Zend_Form_Exception for invalid decorator or invalid method call
  2834. */
  2835. public function __call($method, $args)
  2836. {
  2837. if ('render' == substr($method, 0, 6)) {
  2838. $decoratorName = substr($method, 6);
  2839. if (false !== ($decorator = $this->getDecorator($decoratorName))) {
  2840. $decorator->setElement($this);
  2841. $seed = '';
  2842. if (0 < count($args)) {
  2843. $seed = array_shift($args);
  2844. }
  2845. if ($decoratorName === 'FormElements' ||
  2846. $decoratorName === 'PrepareElements') {
  2847. $this->_setIsRendered();
  2848. }
  2849. return $decorator->render($seed);
  2850. }
  2851. require_once 'Zend/Form/Exception.php';
  2852. throw new Zend_Form_Exception(sprintf('Decorator by name %s does not exist', $decoratorName));
  2853. }
  2854. require_once 'Zend/Form/Exception.php';
  2855. throw new Zend_Form_Exception(sprintf('Method %s does not exist', $method));
  2856. }
  2857. // Interfaces: Iterator, Countable
  2858. /**
  2859. * Current element/subform/display group
  2860. *
  2861. * @return Zend_Form_Element|Zend_Form_DisplayGroup|Zend_Form
  2862. */
  2863. public function current()
  2864. {
  2865. $this->_sort();
  2866. current($this->_order);
  2867. $key = key($this->_order);
  2868. if (isset($this->_elements[$key])) {
  2869. return $this->getElement($key);
  2870. } elseif (isset($this->_subForms[$key])) {
  2871. return $this->getSubForm($key);
  2872. } elseif (isset($this->_displayGroups[$key])) {
  2873. return $this->getDisplayGroup($key);
  2874. } else {
  2875. require_once 'Zend/Form/Exception.php';
  2876. throw new Zend_Form_Exception(sprintf('Corruption detected in form; invalid key ("%s") found in internal iterator', (string) $key));
  2877. }
  2878. }
  2879. /**
  2880. * Current element/subform/display group name
  2881. *
  2882. * @return string
  2883. */
  2884. public function key()
  2885. {
  2886. $this->_sort();
  2887. return key($this->_order);
  2888. }
  2889. /**
  2890. * Move pointer to next element/subform/display group
  2891. *
  2892. * @return void
  2893. */
  2894. public function next()
  2895. {
  2896. $this->_sort();
  2897. next($this->_order);
  2898. }
  2899. /**
  2900. * Move pointer to beginning of element/subform/display group loop
  2901. *
  2902. * @return void
  2903. */
  2904. public function rewind()
  2905. {
  2906. $this->_sort();
  2907. reset($this->_order);
  2908. }
  2909. /**
  2910. * Determine if current element/subform/display group is valid
  2911. *
  2912. * @return bool
  2913. */
  2914. public function valid()
  2915. {
  2916. $this->_sort();
  2917. return (current($this->_order) !== false);
  2918. }
  2919. /**
  2920. * Count of elements/subforms that are iterable
  2921. *
  2922. * @return int
  2923. */
  2924. public function count()
  2925. {
  2926. return count($this->_order);
  2927. }
  2928. /**
  2929. * Set flag to disable loading default decorators
  2930. *
  2931. * @param bool $flag
  2932. * @return Zend_Form
  2933. */
  2934. public function setDisableLoadDefaultDecorators($flag)
  2935. {
  2936. $this->_disableLoadDefaultDecorators = (bool) $flag;
  2937. return $this;
  2938. }
  2939. /**
  2940. * Should we load the default decorators?
  2941. *
  2942. * @return bool
  2943. */
  2944. public function loadDefaultDecoratorsIsDisabled()
  2945. {
  2946. return $this->_disableLoadDefaultDecorators;
  2947. }
  2948. /**
  2949. * Load the default decorators
  2950. *
  2951. * @return Zend_Form
  2952. */
  2953. public function loadDefaultDecorators()
  2954. {
  2955. if ($this->loadDefaultDecoratorsIsDisabled()) {
  2956. return $this;
  2957. }
  2958. $decorators = $this->getDecorators();
  2959. if (empty($decorators)) {
  2960. $this->addDecorator('FormElements')
  2961. ->addDecorator('HtmlTag', array('tag' => 'dl', 'class' => 'zend_form'))
  2962. ->addDecorator('Form');
  2963. }
  2964. return $this;
  2965. }
  2966. /**
  2967. * Remove an element from iteration
  2968. *
  2969. * @param string $name Element/group/form name
  2970. * @return void
  2971. */
  2972. public function removeFromIteration($name)
  2973. {
  2974. if (array_key_exists($name, $this->_order)) {
  2975. unset($this->_order[$name]);
  2976. $this->_orderUpdated = true;
  2977. }
  2978. }
  2979. /**
  2980. * Sort items according to their order
  2981. *
  2982. * @return void
  2983. */
  2984. protected function _sort()
  2985. {
  2986. if ($this->_orderUpdated) {
  2987. $items = array();
  2988. $index = 0;
  2989. foreach ($this->_order as $key => $order) {
  2990. if (null === $order) {
  2991. if (null === ($order = $this->{$key}->getOrder())) {
  2992. while (array_search($index, $this->_order, true)) {
  2993. ++$index;
  2994. }
  2995. $items[$index] = $key;
  2996. ++$index;
  2997. } else {
  2998. $items[$order] = $key;
  2999. }
  3000. } else {
  3001. $items[$order] = $key;
  3002. }
  3003. }
  3004. $items = array_flip($items);
  3005. asort($items);
  3006. $this->_order = $items;
  3007. $this->_orderUpdated = false;
  3008. }
  3009. }
  3010. /**
  3011. * Lazy-load a decorator
  3012. *
  3013. * @param array $decorator Decorator type and options
  3014. * @param mixed $name Decorator name or alias
  3015. * @return Zend_Form_Decorator_Interface
  3016. */
  3017. protected function _loadDecorator(array $decorator, $name)
  3018. {
  3019. $sameName = false;
  3020. if ($name == $decorator['decorator']) {
  3021. $sameName = true;
  3022. }
  3023. $instance = $this->_getDecorator($decorator['decorator'], $decorator['options']);
  3024. if ($sameName) {
  3025. $newName = get_class($instance);
  3026. $decoratorNames = array_keys($this->_decorators);
  3027. $order = array_flip($decoratorNames);
  3028. $order[$newName] = $order[$name];
  3029. $decoratorsExchange = array();
  3030. unset($order[$name]);
  3031. asort($order);
  3032. foreach ($order as $key => $index) {
  3033. if ($key == $newName) {
  3034. $decoratorsExchange[$key] = $instance;
  3035. continue;
  3036. }
  3037. $decoratorsExchange[$key] = $this->_decorators[$key];
  3038. }
  3039. $this->_decorators = $decoratorsExchange;
  3040. } else {
  3041. $this->_decorators[$name] = $instance;
  3042. }
  3043. return $instance;
  3044. }
  3045. /**
  3046. * Retrieve optionally translated custom error messages
  3047. *
  3048. * @return array
  3049. */
  3050. protected function _getErrorMessages()
  3051. {
  3052. $messages = $this->getErrorMessages();
  3053. $translator = $this->getTranslator();
  3054. if (null !== $translator) {
  3055. foreach ($messages as $key => $message) {
  3056. $messages[$key] = $translator->translate($message);
  3057. }
  3058. }
  3059. return $messages;
  3060. }
  3061. }