PageRenderTime 63ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/src/application/libraries/Zend/Form.php

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