Element.php 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240
  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-2010 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. */
  20. /** @see Zend_Filter */
  21. require_once 'Zend/Filter.php';
  22. /** @see Zend_Form */
  23. require_once 'Zend/Form.php';
  24. /** @see Zend_Validate_Interface */
  25. require_once 'Zend/Validate/Interface.php';
  26. /**
  27. * Zend_Form_Element
  28. *
  29. * @category Zend
  30. * @package Zend_Form
  31. * @subpackage Element
  32. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  33. * @license http://framework.zend.com/license/new-bsd New BSD License
  34. * @version $Id$
  35. */
  36. class Zend_Form_Element implements Zend_Validate_Interface
  37. {
  38. /**
  39. * Element Constants
  40. */
  41. const DECORATOR = 'DECORATOR';
  42. const FILTER = 'FILTER';
  43. const VALIDATE = 'VALIDATE';
  44. /**
  45. * Default view helper to use
  46. * @var string
  47. */
  48. public $helper = 'formText';
  49. /**
  50. * 'Allow empty' flag
  51. * @var bool
  52. */
  53. protected $_allowEmpty = true;
  54. /**
  55. * Flag indicating whether or not to insert NotEmpty validator when element is required
  56. * @var bool
  57. */
  58. protected $_autoInsertNotEmptyValidator = true;
  59. /**
  60. * Array to which element belongs
  61. * @var string
  62. */
  63. protected $_belongsTo;
  64. /**
  65. * Element decorators
  66. * @var array
  67. */
  68. protected $_decorators = array();
  69. /**
  70. * Element description
  71. * @var string
  72. */
  73. protected $_description;
  74. /**
  75. * Should we disable loading the default decorators?
  76. * @var bool
  77. */
  78. protected $_disableLoadDefaultDecorators = false;
  79. /**
  80. * Custom error messages
  81. * @var array
  82. */
  83. protected $_errorMessages = array();
  84. /**
  85. * Validation errors
  86. * @var array
  87. */
  88. protected $_errors = array();
  89. /**
  90. * Separator to use when concatenating aggregate error messages (for
  91. * elements having array values)
  92. * @var string
  93. */
  94. protected $_errorMessageSeparator = '; ';
  95. /**
  96. * Element filters
  97. * @var array
  98. */
  99. protected $_filters = array();
  100. /**
  101. * Ignore flag (used when retrieving values at form level)
  102. * @var bool
  103. */
  104. protected $_ignore = false;
  105. /**
  106. * Does the element represent an array?
  107. * @var bool
  108. */
  109. protected $_isArray = false;
  110. /**
  111. * Is the error marked as in an invalid state?
  112. * @var bool
  113. */
  114. protected $_isError = false;
  115. /**
  116. * Has the element been manually marked as invalid?
  117. * @var bool
  118. */
  119. protected $_isErrorForced = false;
  120. /**
  121. * Element label
  122. * @var string
  123. */
  124. protected $_label;
  125. /**
  126. * Plugin loaders for filter and validator chains
  127. * @var array
  128. */
  129. protected $_loaders = array();
  130. /**
  131. * Formatted validation error messages
  132. * @var array
  133. */
  134. protected $_messages = array();
  135. /**
  136. * Element name
  137. * @var string
  138. */
  139. protected $_name;
  140. /**
  141. * Order of element
  142. * @var int
  143. */
  144. protected $_order;
  145. /**
  146. * Required flag
  147. * @var bool
  148. */
  149. protected $_required = false;
  150. /**
  151. * @var Zend_Translate
  152. */
  153. protected $_translator;
  154. /**
  155. * Is translation disabled?
  156. * @var bool
  157. */
  158. protected $_translatorDisabled = false;
  159. /**
  160. * Element type
  161. * @var string
  162. */
  163. protected $_type;
  164. /**
  165. * Array of initialized validators
  166. * @var array Validators
  167. */
  168. protected $_validators = array();
  169. /**
  170. * Array of un-initialized validators
  171. * @var array
  172. */
  173. protected $_validatorRules = array();
  174. /**
  175. * Element value
  176. * @var mixed
  177. */
  178. protected $_value;
  179. /**
  180. * @var Zend_View_Interface
  181. */
  182. protected $_view;
  183. /**
  184. * Is a specific decorator being rendered via the magic renderDecorator()?
  185. *
  186. * This is to allow execution of logic inside the render() methods of child
  187. * elements during the magic call while skipping the parent render() method.
  188. *
  189. * @var bool
  190. */
  191. protected $_isPartialRendering = false;
  192. /**
  193. * Constructor
  194. *
  195. * $spec may be:
  196. * - string: name of element
  197. * - array: options with which to configure element
  198. * - Zend_Config: Zend_Config with options for configuring element
  199. *
  200. * @param string|array|Zend_Config $spec
  201. * @param array|Zend_Config $options
  202. * @return void
  203. * @throws Zend_Form_Exception if no element name after initialization
  204. */
  205. public function __construct($spec, $options = null)
  206. {
  207. if (is_string($spec)) {
  208. $this->setName($spec);
  209. } elseif (is_array($spec)) {
  210. $this->setOptions($spec);
  211. } elseif ($spec instanceof Zend_Config) {
  212. $this->setConfig($spec);
  213. }
  214. if (is_string($spec) && is_array($options)) {
  215. $this->setOptions($options);
  216. } elseif (is_string($spec) && ($options instanceof Zend_Config)) {
  217. $this->setConfig($options);
  218. }
  219. if (null === $this->getName()) {
  220. require_once 'Zend/Form/Exception.php';
  221. throw new Zend_Form_Exception('Zend_Form_Element requires each element to have a name');
  222. }
  223. /**
  224. * Extensions
  225. */
  226. $this->init();
  227. /**
  228. * Register ViewHelper decorator by default
  229. */
  230. $this->loadDefaultDecorators();
  231. }
  232. /**
  233. * Initialize object; used by extending classes
  234. *
  235. * @return void
  236. */
  237. public function init()
  238. {
  239. }
  240. /**
  241. * Set flag to disable loading default decorators
  242. *
  243. * @param bool $flag
  244. * @return Zend_Form_Element
  245. */
  246. public function setDisableLoadDefaultDecorators($flag)
  247. {
  248. $this->_disableLoadDefaultDecorators = (bool) $flag;
  249. return $this;
  250. }
  251. /**
  252. * Should we load the default decorators?
  253. *
  254. * @return bool
  255. */
  256. public function loadDefaultDecoratorsIsDisabled()
  257. {
  258. return $this->_disableLoadDefaultDecorators;
  259. }
  260. /**
  261. * Load default decorators
  262. *
  263. * @return void
  264. */
  265. public function loadDefaultDecorators()
  266. {
  267. if ($this->loadDefaultDecoratorsIsDisabled()) {
  268. return;
  269. }
  270. $decorators = $this->getDecorators();
  271. if (empty($decorators)) {
  272. $this->addDecorator('ViewHelper')
  273. ->addDecorator('Errors')
  274. ->addDecorator('Description', array('tag' => 'p', 'class' => 'description'))
  275. ->addDecorator('HtmlTag', array('tag' => 'dd',
  276. 'id' => $this->getName() . '-element'))
  277. ->addDecorator('Label', array('tag' => 'dt'));
  278. }
  279. }
  280. /**
  281. * Set object state from options array
  282. *
  283. * @param array $options
  284. * @return Zend_Form_Element
  285. */
  286. public function setOptions(array $options)
  287. {
  288. if (isset($options['prefixPath'])) {
  289. $this->addPrefixPaths($options['prefixPath']);
  290. unset($options['prefixPath']);
  291. }
  292. if (isset($options['disableTranslator'])) {
  293. $this->setDisableTranslator($options['disableTranslator']);
  294. unset($options['disableTranslator']);
  295. }
  296. unset($options['options']);
  297. unset($options['config']);
  298. foreach ($options as $key => $value) {
  299. $method = 'set' . ucfirst($key);
  300. if (in_array($method, array('setTranslator', 'setPluginLoader', 'setView'))) {
  301. if (!is_object($value)) {
  302. continue;
  303. }
  304. }
  305. if (method_exists($this, $method)) {
  306. // Setter exists; use it
  307. $this->$method($value);
  308. } else {
  309. // Assume it's metadata
  310. $this->setAttrib($key, $value);
  311. }
  312. }
  313. return $this;
  314. }
  315. /**
  316. * Set object state from Zend_Config object
  317. *
  318. * @param Zend_Config $config
  319. * @return Zend_Form_Element
  320. */
  321. public function setConfig(Zend_Config $config)
  322. {
  323. return $this->setOptions($config->toArray());
  324. }
  325. // Localization:
  326. /**
  327. * Set translator object for localization
  328. *
  329. * @param Zend_Translate|null $translator
  330. * @return Zend_Form_Element
  331. */
  332. public function setTranslator($translator = null)
  333. {
  334. if (null === $translator) {
  335. $this->_translator = null;
  336. } elseif ($translator instanceof Zend_Translate_Adapter) {
  337. $this->_translator = $translator;
  338. } elseif ($translator instanceof Zend_Translate) {
  339. $this->_translator = $translator->getAdapter();
  340. } else {
  341. require_once 'Zend/Form/Exception.php';
  342. throw new Zend_Form_Exception('Invalid translator specified');
  343. }
  344. return $this;
  345. }
  346. /**
  347. * Retrieve localization translator object
  348. *
  349. * @return Zend_Translate_Adapter|null
  350. */
  351. public function getTranslator()
  352. {
  353. if ($this->translatorIsDisabled()) {
  354. return null;
  355. }
  356. if (null === $this->_translator) {
  357. return Zend_Form::getDefaultTranslator();
  358. }
  359. return $this->_translator;
  360. }
  361. /**
  362. * Does this element have its own specific translator?
  363. *
  364. * @return bool
  365. */
  366. public function hasTranslator()
  367. {
  368. return (bool)$this->_translator;
  369. }
  370. /**
  371. * Indicate whether or not translation should be disabled
  372. *
  373. * @param bool $flag
  374. * @return Zend_Form_Element
  375. */
  376. public function setDisableTranslator($flag)
  377. {
  378. $this->_translatorDisabled = (bool) $flag;
  379. return $this;
  380. }
  381. /**
  382. * Is translation disabled?
  383. *
  384. * @return bool
  385. */
  386. public function translatorIsDisabled()
  387. {
  388. return $this->_translatorDisabled;
  389. }
  390. // Metadata
  391. /**
  392. * Filter a name to only allow valid variable characters
  393. *
  394. * @param string $value
  395. * @param bool $allowBrackets
  396. * @return string
  397. */
  398. public function filterName($value, $allowBrackets = false)
  399. {
  400. $charset = '^a-zA-Z0-9_\x7f-\xff';
  401. if ($allowBrackets) {
  402. $charset .= '\[\]';
  403. }
  404. return preg_replace('/[' . $charset . ']/', '', (string) $value);
  405. }
  406. /**
  407. * Set element name
  408. *
  409. * @param string $name
  410. * @return Zend_Form_Element
  411. */
  412. public function setName($name)
  413. {
  414. $name = $this->filterName($name);
  415. if ('' === $name) {
  416. require_once 'Zend/Form/Exception.php';
  417. throw new Zend_Form_Exception('Invalid name provided; must contain only valid variable characters and be non-empty');
  418. }
  419. $this->_name = $name;
  420. return $this;
  421. }
  422. /**
  423. * Return element name
  424. *
  425. * @return string
  426. */
  427. public function getName()
  428. {
  429. return $this->_name;
  430. }
  431. /**
  432. * Get fully qualified name
  433. *
  434. * Places name as subitem of array and/or appends brackets.
  435. *
  436. * @return string
  437. */
  438. public function getFullyQualifiedName()
  439. {
  440. $name = $this->getName();
  441. if (null !== ($belongsTo = $this->getBelongsTo())) {
  442. $name = $belongsTo . '[' . $name . ']';
  443. }
  444. if ($this->isArray()) {
  445. $name .= '[]';
  446. }
  447. return $name;
  448. }
  449. /**
  450. * Get element id
  451. *
  452. * @return string
  453. */
  454. public function getId()
  455. {
  456. if (isset($this->id)) {
  457. return $this->id;
  458. }
  459. $id = $this->getFullyQualifiedName();
  460. // Bail early if no array notation detected
  461. if (!strstr($id, '[')) {
  462. return $id;
  463. }
  464. // Strip array notation
  465. if ('[]' == substr($id, -2)) {
  466. $id = substr($id, 0, strlen($id) - 2);
  467. }
  468. $id = str_replace('][', '-', $id);
  469. $id = str_replace(array(']', '['), '-', $id);
  470. $id = trim($id, '-');
  471. return $id;
  472. }
  473. /**
  474. * Set element value
  475. *
  476. * @param mixed $value
  477. * @return Zend_Form_Element
  478. */
  479. public function setValue($value)
  480. {
  481. $this->_value = $value;
  482. return $this;
  483. }
  484. /**
  485. * Filter a value
  486. *
  487. * @param string $value
  488. * @param string $key
  489. * @return void
  490. */
  491. protected function _filterValue(&$value, &$key)
  492. {
  493. foreach ($this->getFilters() as $filter) {
  494. $value = $filter->filter($value);
  495. }
  496. }
  497. /**
  498. * Retrieve filtered element value
  499. *
  500. * @return mixed
  501. */
  502. public function getValue()
  503. {
  504. $valueFiltered = $this->_value;
  505. if ($this->isArray() && is_array($valueFiltered)) {
  506. array_walk_recursive($valueFiltered, array($this, '_filterValue'));
  507. } else {
  508. $this->_filterValue($valueFiltered, $valueFiltered);
  509. }
  510. return $valueFiltered;
  511. }
  512. /**
  513. * Retrieve unfiltered element value
  514. *
  515. * @return mixed
  516. */
  517. public function getUnfilteredValue()
  518. {
  519. return $this->_value;
  520. }
  521. /**
  522. * Set element label
  523. *
  524. * @param string $label
  525. * @return Zend_Form_Element
  526. */
  527. public function setLabel($label)
  528. {
  529. $this->_label = (string) $label;
  530. return $this;
  531. }
  532. /**
  533. * Retrieve element label
  534. *
  535. * @return string
  536. */
  537. public function getLabel()
  538. {
  539. $translator = $this->getTranslator();
  540. if (null !== $translator) {
  541. return $translator->translate($this->_label);
  542. }
  543. return $this->_label;
  544. }
  545. /**
  546. * Set element order
  547. *
  548. * @param int $order
  549. * @return Zend_Form_Element
  550. */
  551. public function setOrder($order)
  552. {
  553. $this->_order = (int) $order;
  554. return $this;
  555. }
  556. /**
  557. * Retrieve element order
  558. *
  559. * @return int
  560. */
  561. public function getOrder()
  562. {
  563. return $this->_order;
  564. }
  565. /**
  566. * Set required flag
  567. *
  568. * @param bool $flag Default value is true
  569. * @return Zend_Form_Element
  570. */
  571. public function setRequired($flag = true)
  572. {
  573. $this->_required = (bool) $flag;
  574. return $this;
  575. }
  576. /**
  577. * Is the element required?
  578. *
  579. * @return bool
  580. */
  581. public function isRequired()
  582. {
  583. return $this->_required;
  584. }
  585. /**
  586. * Set flag indicating whether a NotEmpty validator should be inserted when element is required
  587. *
  588. * @param bool $flag
  589. * @return Zend_Form_Element
  590. */
  591. public function setAutoInsertNotEmptyValidator($flag)
  592. {
  593. $this->_autoInsertNotEmptyValidator = (bool) $flag;
  594. return $this;
  595. }
  596. /**
  597. * Get flag indicating whether a NotEmpty validator should be inserted when element is required
  598. *
  599. * @return bool
  600. */
  601. public function autoInsertNotEmptyValidator()
  602. {
  603. return $this->_autoInsertNotEmptyValidator;
  604. }
  605. /**
  606. * Set element description
  607. *
  608. * @param string $description
  609. * @return Zend_Form_Element
  610. */
  611. public function setDescription($description)
  612. {
  613. $this->_description = (string) $description;
  614. return $this;
  615. }
  616. /**
  617. * Retrieve element description
  618. *
  619. * @return string
  620. */
  621. public function getDescription()
  622. {
  623. return $this->_description;
  624. }
  625. /**
  626. * Set 'allow empty' flag
  627. *
  628. * When the allow empty flag is enabled and the required flag is false, the
  629. * element will validate with empty values.
  630. *
  631. * @param bool $flag
  632. * @return Zend_Form_Element
  633. */
  634. public function setAllowEmpty($flag)
  635. {
  636. $this->_allowEmpty = (bool) $flag;
  637. return $this;
  638. }
  639. /**
  640. * Get 'allow empty' flag
  641. *
  642. * @return bool
  643. */
  644. public function getAllowEmpty()
  645. {
  646. return $this->_allowEmpty;
  647. }
  648. /**
  649. * Set ignore flag (used when retrieving values at form level)
  650. *
  651. * @param bool $flag
  652. * @return Zend_Form_Element
  653. */
  654. public function setIgnore($flag)
  655. {
  656. $this->_ignore = (bool) $flag;
  657. return $this;
  658. }
  659. /**
  660. * Get ignore flag (used when retrieving values at form level)
  661. *
  662. * @return bool
  663. */
  664. public function getIgnore()
  665. {
  666. return $this->_ignore;
  667. }
  668. /**
  669. * Set flag indicating if element represents an array
  670. *
  671. * @param bool $flag
  672. * @return Zend_Form_Element
  673. */
  674. public function setIsArray($flag)
  675. {
  676. $this->_isArray = (bool) $flag;
  677. return $this;
  678. }
  679. /**
  680. * Is the element representing an array?
  681. *
  682. * @return bool
  683. */
  684. public function isArray()
  685. {
  686. return $this->_isArray;
  687. }
  688. /**
  689. * Set array to which element belongs
  690. *
  691. * @param string $array
  692. * @return Zend_Form_Element
  693. */
  694. public function setBelongsTo($array)
  695. {
  696. $array = $this->filterName($array, true);
  697. if (!empty($array)) {
  698. $this->_belongsTo = $array;
  699. }
  700. return $this;
  701. }
  702. /**
  703. * Return array name to which element belongs
  704. *
  705. * @return string
  706. */
  707. public function getBelongsTo()
  708. {
  709. return $this->_belongsTo;
  710. }
  711. /**
  712. * Return element type
  713. *
  714. * @return string
  715. */
  716. public function getType()
  717. {
  718. if (null === $this->_type) {
  719. $this->_type = get_class($this);
  720. }
  721. return $this->_type;
  722. }
  723. /**
  724. * Set element attribute
  725. *
  726. * @param string $name
  727. * @param mixed $value
  728. * @return Zend_Form_Element
  729. * @throws Zend_Form_Exception for invalid $name values
  730. */
  731. public function setAttrib($name, $value)
  732. {
  733. $name = (string) $name;
  734. if ('_' == $name[0]) {
  735. require_once 'Zend/Form/Exception.php';
  736. throw new Zend_Form_Exception(sprintf('Invalid attribute "%s"; must not contain a leading underscore', $name));
  737. }
  738. if (null === $value) {
  739. unset($this->$name);
  740. } else {
  741. $this->$name = $value;
  742. }
  743. return $this;
  744. }
  745. /**
  746. * Set multiple attributes at once
  747. *
  748. * @param array $attribs
  749. * @return Zend_Form_Element
  750. */
  751. public function setAttribs(array $attribs)
  752. {
  753. foreach ($attribs as $key => $value) {
  754. $this->setAttrib($key, $value);
  755. }
  756. return $this;
  757. }
  758. /**
  759. * Retrieve element attribute
  760. *
  761. * @param string $name
  762. * @return string
  763. */
  764. public function getAttrib($name)
  765. {
  766. $name = (string) $name;
  767. if (isset($this->$name)) {
  768. return $this->$name;
  769. }
  770. return null;
  771. }
  772. /**
  773. * Return all attributes
  774. *
  775. * @return array
  776. */
  777. public function getAttribs()
  778. {
  779. $attribs = get_object_vars($this);
  780. foreach ($attribs as $key => $value) {
  781. if ('_' == substr($key, 0, 1)) {
  782. unset($attribs[$key]);
  783. }
  784. }
  785. return $attribs;
  786. }
  787. /**
  788. * Overloading: retrieve object property
  789. *
  790. * Prevents access to properties beginning with '_'.
  791. *
  792. * @param string $key
  793. * @return mixed
  794. */
  795. public function __get($key)
  796. {
  797. if ('_' == $key[0]) {
  798. require_once 'Zend/Form/Exception.php';
  799. throw new Zend_Form_Exception(sprintf('Cannot retrieve value for protected/private property "%s"', $key));
  800. }
  801. if (!isset($this->$key)) {
  802. return null;
  803. }
  804. return $this->$key;
  805. }
  806. /**
  807. * Overloading: set object property
  808. *
  809. * @param string $key
  810. * @param mixed $value
  811. * @return voide
  812. */
  813. public function __set($key, $value)
  814. {
  815. $this->setAttrib($key, $value);
  816. }
  817. /**
  818. * Overloading: allow rendering specific decorators
  819. *
  820. * Call renderDecoratorName() to render a specific decorator.
  821. *
  822. * @param string $method
  823. * @param array $args
  824. * @return string
  825. * @throws Zend_Form_Exception for invalid decorator or invalid method call
  826. */
  827. public function __call($method, $args)
  828. {
  829. if ('render' == substr($method, 0, 6)) {
  830. $this->_isPartialRendering = true;
  831. $this->render();
  832. $this->_isPartialRendering = false;
  833. $decoratorName = substr($method, 6);
  834. if (false !== ($decorator = $this->getDecorator($decoratorName))) {
  835. $decorator->setElement($this);
  836. $seed = '';
  837. if (0 < count($args)) {
  838. $seed = array_shift($args);
  839. }
  840. return $decorator->render($seed);
  841. }
  842. require_once 'Zend/Form/Element/Exception.php';
  843. throw new Zend_Form_Element_Exception(sprintf('Decorator by name %s does not exist', $decoratorName));
  844. }
  845. require_once 'Zend/Form/Element/Exception.php';
  846. throw new Zend_Form_Element_Exception(sprintf('Method %s does not exist', $method));
  847. }
  848. // Loaders
  849. /**
  850. * Set plugin loader to use for validator or filter chain
  851. *
  852. * @param Zend_Loader_PluginLoader_Interface $loader
  853. * @param string $type 'decorator', 'filter', or 'validate'
  854. * @return Zend_Form_Element
  855. * @throws Zend_Form_Exception on invalid type
  856. */
  857. public function setPluginLoader(Zend_Loader_PluginLoader_Interface $loader, $type)
  858. {
  859. $type = strtoupper($type);
  860. switch ($type) {
  861. case self::DECORATOR:
  862. case self::FILTER:
  863. case self::VALIDATE:
  864. $this->_loaders[$type] = $loader;
  865. return $this;
  866. default:
  867. require_once 'Zend/Form/Exception.php';
  868. throw new Zend_Form_Exception(sprintf('Invalid type "%s" provided to setPluginLoader()', $type));
  869. }
  870. }
  871. /**
  872. * Retrieve plugin loader for validator or filter chain
  873. *
  874. * Instantiates with default rules if none available for that type. Use
  875. * 'decorator', 'filter', or 'validate' for $type.
  876. *
  877. * @param string $type
  878. * @return Zend_Loader_PluginLoader
  879. * @throws Zend_Loader_Exception on invalid type.
  880. */
  881. public function getPluginLoader($type)
  882. {
  883. $type = strtoupper($type);
  884. switch ($type) {
  885. case self::FILTER:
  886. case self::VALIDATE:
  887. $prefixSegment = ucfirst(strtolower($type));
  888. $pathSegment = $prefixSegment;
  889. case self::DECORATOR:
  890. if (!isset($prefixSegment)) {
  891. $prefixSegment = 'Form_Decorator';
  892. $pathSegment = 'Form/Decorator';
  893. }
  894. if (!isset($this->_loaders[$type])) {
  895. require_once 'Zend/Loader/PluginLoader.php';
  896. $this->_loaders[$type] = new Zend_Loader_PluginLoader(
  897. array('Zend_' . $prefixSegment . '_' => 'Zend/' . $pathSegment . '/')
  898. );
  899. }
  900. return $this->_loaders[$type];
  901. default:
  902. require_once 'Zend/Form/Exception.php';
  903. throw new Zend_Form_Exception(sprintf('Invalid type "%s" provided to getPluginLoader()', $type));
  904. }
  905. }
  906. /**
  907. * Add prefix path for plugin loader
  908. *
  909. * If no $type specified, assumes it is a base path for both filters and
  910. * validators, and sets each according to the following rules:
  911. * - decorators: $prefix = $prefix . '_Decorator'
  912. * - filters: $prefix = $prefix . '_Filter'
  913. * - validators: $prefix = $prefix . '_Validate'
  914. *
  915. * Otherwise, the path prefix is set on the appropriate plugin loader.
  916. *
  917. * @param string $prefix
  918. * @param string $path
  919. * @param string $type
  920. * @return Zend_Form_Element
  921. * @throws Zend_Form_Exception for invalid type
  922. */
  923. public function addPrefixPath($prefix, $path, $type = null)
  924. {
  925. $type = strtoupper($type);
  926. switch ($type) {
  927. case self::DECORATOR:
  928. case self::FILTER:
  929. case self::VALIDATE:
  930. $loader = $this->getPluginLoader($type);
  931. $loader->addPrefixPath($prefix, $path);
  932. return $this;
  933. case null:
  934. $prefix = rtrim($prefix, '_');
  935. $path = rtrim($path, DIRECTORY_SEPARATOR);
  936. foreach (array(self::DECORATOR, self::FILTER, self::VALIDATE) as $type) {
  937. $cType = ucfirst(strtolower($type));
  938. $pluginPath = $path . DIRECTORY_SEPARATOR . $cType . DIRECTORY_SEPARATOR;
  939. $pluginPrefix = $prefix . '_' . $cType;
  940. $loader = $this->getPluginLoader($type);
  941. $loader->addPrefixPath($pluginPrefix, $pluginPath);
  942. }
  943. return $this;
  944. default:
  945. require_once 'Zend/Form/Exception.php';
  946. throw new Zend_Form_Exception(sprintf('Invalid type "%s" provided to getPluginLoader()', $type));
  947. }
  948. }
  949. /**
  950. * Add many prefix paths at once
  951. *
  952. * @param array $spec
  953. * @return Zend_Form_Element
  954. */
  955. public function addPrefixPaths(array $spec)
  956. {
  957. if (isset($spec['prefix']) && isset($spec['path'])) {
  958. return $this->addPrefixPath($spec['prefix'], $spec['path']);
  959. }
  960. foreach ($spec as $type => $paths) {
  961. if (is_numeric($type) && is_array($paths)) {
  962. $type = null;
  963. if (isset($paths['prefix']) && isset($paths['path'])) {
  964. if (isset($paths['type'])) {
  965. $type = $paths['type'];
  966. }
  967. $this->addPrefixPath($paths['prefix'], $paths['path'], $type);
  968. }
  969. } elseif (!is_numeric($type)) {
  970. if (!isset($paths['prefix']) || !isset($paths['path'])) {
  971. foreach ($paths as $prefix => $spec) {
  972. if (is_array($spec)) {
  973. foreach ($spec as $path) {
  974. if (!is_string($path)) {
  975. continue;
  976. }
  977. $this->addPrefixPath($prefix, $path, $type);
  978. }
  979. } elseif (is_string($spec)) {
  980. $this->addPrefixPath($prefix, $spec, $type);
  981. }
  982. }
  983. } else {
  984. $this->addPrefixPath($paths['prefix'], $paths['path'], $type);
  985. }
  986. }
  987. }
  988. return $this;
  989. }
  990. // Validation
  991. /**
  992. * Add validator to validation chain
  993. *
  994. * Note: will overwrite existing validators if they are of the same class.
  995. *
  996. * @param string|Zend_Validate_Interface $validator
  997. * @param bool $breakChainOnFailure
  998. * @param array $options
  999. * @return Zend_Form_Element
  1000. * @throws Zend_Form_Exception if invalid validator type
  1001. */
  1002. public function addValidator($validator, $breakChainOnFailure = false, $options = array())
  1003. {
  1004. if ($validator instanceof Zend_Validate_Interface) {
  1005. $name = get_class($validator);
  1006. if (!isset($validator->zfBreakChainOnFailure)) {
  1007. $validator->zfBreakChainOnFailure = $breakChainOnFailure;
  1008. }
  1009. } elseif (is_string($validator)) {
  1010. $name = $validator;
  1011. $validator = array(
  1012. 'validator' => $validator,
  1013. 'breakChainOnFailure' => $breakChainOnFailure,
  1014. 'options' => $options,
  1015. );
  1016. } else {
  1017. require_once 'Zend/Form/Exception.php';
  1018. throw new Zend_Form_Exception('Invalid validator provided to addValidator; must be string or Zend_Validate_Interface');
  1019. }
  1020. $this->_validators[$name] = $validator;
  1021. return $this;
  1022. }
  1023. /**
  1024. * Add multiple validators
  1025. *
  1026. * @param array $validators
  1027. * @return Zend_Form_Element
  1028. */
  1029. public function addValidators(array $validators)
  1030. {
  1031. foreach ($validators as $validatorInfo) {
  1032. if (is_string($validatorInfo)) {
  1033. $this->addValidator($validatorInfo);
  1034. } elseif ($validatorInfo instanceof Zend_Validate_Interface) {
  1035. $this->addValidator($validatorInfo);
  1036. } elseif (is_array($validatorInfo)) {
  1037. $argc = count($validatorInfo);
  1038. $breakChainOnFailure = false;
  1039. $options = array();
  1040. if (isset($validatorInfo['validator'])) {
  1041. $validator = $validatorInfo['validator'];
  1042. if (isset($validatorInfo['breakChainOnFailure'])) {
  1043. $breakChainOnFailure = $validatorInfo['breakChainOnFailure'];
  1044. }
  1045. if (isset($validatorInfo['options'])) {
  1046. $options = $validatorInfo['options'];
  1047. }
  1048. $this->addValidator($validator, $breakChainOnFailure, $options);
  1049. } else {
  1050. switch (true) {
  1051. case (0 == $argc):
  1052. break;
  1053. case (1 <= $argc):
  1054. $validator = array_shift($validatorInfo);
  1055. case (2 <= $argc):
  1056. $breakChainOnFailure = array_shift($validatorInfo);
  1057. case (3 <= $argc):
  1058. $options = array_shift($validatorInfo);
  1059. default:
  1060. $this->addValidator($validator, $breakChainOnFailure, $options);
  1061. break;
  1062. }
  1063. }
  1064. } else {
  1065. require_once 'Zend/Form/Exception.php';
  1066. throw new Zend_Form_Exception('Invalid validator passed to addValidators()');
  1067. }
  1068. }
  1069. return $this;
  1070. }
  1071. /**
  1072. * Set multiple validators, overwriting previous validators
  1073. *
  1074. * @param array $validators
  1075. * @return Zend_Form_Element
  1076. */
  1077. public function setValidators(array $validators)
  1078. {
  1079. $this->clearValidators();
  1080. return $this->addValidators($validators);
  1081. }
  1082. /**
  1083. * Retrieve a single validator by name
  1084. *
  1085. * @param string $name
  1086. * @return Zend_Validate_Interface|false False if not found, validator otherwise
  1087. */
  1088. public function getValidator($name)
  1089. {
  1090. if (!isset($this->_validators[$name])) {
  1091. $len = strlen($name);
  1092. foreach ($this->_validators as $localName => $validator) {
  1093. if ($len > strlen($localName)) {
  1094. continue;
  1095. }
  1096. if (0 === substr_compare($localName, $name, -$len, $len, true)) {
  1097. if (is_array($validator)) {
  1098. return $this->_loadValidator($validator);
  1099. }
  1100. return $validator;
  1101. }
  1102. }
  1103. return false;
  1104. }
  1105. if (is_array($this->_validators[$name])) {
  1106. return $this->_loadValidator($this->_validators[$name]);
  1107. }
  1108. return $this->_validators[$name];
  1109. }
  1110. /**
  1111. * Retrieve all validators
  1112. *
  1113. * @return array
  1114. */
  1115. public function getValidators()
  1116. {
  1117. $validators = array();
  1118. foreach ($this->_validators as $key => $value) {
  1119. if ($value instanceof Zend_Validate_Interface) {
  1120. $validators[$key] = $value;
  1121. continue;
  1122. }
  1123. $validator = $this->_loadValidator($value);
  1124. $validators[get_class($validator)] = $validator;
  1125. }
  1126. return $validators;
  1127. }
  1128. /**
  1129. * Remove a single validator by name
  1130. *
  1131. * @param string $name
  1132. * @return bool
  1133. */
  1134. public function removeValidator($name)
  1135. {
  1136. if (isset($this->_validators[$name])) {
  1137. unset($this->_validators[$name]);
  1138. } else {
  1139. $len = strlen($name);
  1140. foreach (array_keys($this->_validators) as $validator) {
  1141. if ($len > strlen($validator)) {
  1142. continue;
  1143. }
  1144. if (0 === substr_compare($validator, $name, -$len, $len, true)) {
  1145. unset($this->_validators[$validator]);
  1146. break;
  1147. }
  1148. }
  1149. }
  1150. return $this;
  1151. }
  1152. /**
  1153. * Clear all validators
  1154. *
  1155. * @return Zend_Form_Element
  1156. */
  1157. public function clearValidators()
  1158. {
  1159. $this->_validators = array();
  1160. return $this;
  1161. }
  1162. /**
  1163. * Validate element value
  1164. *
  1165. * If a translation adapter is registered, any error messages will be
  1166. * translated according to the current locale, using the given error code;
  1167. * if no matching translation is found, the original message will be
  1168. * utilized.
  1169. *
  1170. * Note: The *filtered* value is validated.
  1171. *
  1172. * @param mixed $value
  1173. * @param mixed $context
  1174. * @return boolean
  1175. */
  1176. public function isValid($value, $context = null)
  1177. {
  1178. $this->setValue($value);
  1179. $value = $this->getValue();
  1180. if ((('' === $value) || (null === $value))
  1181. && !$this->isRequired()
  1182. && $this->getAllowEmpty()
  1183. ) {
  1184. return true;
  1185. }
  1186. if ($this->isRequired()
  1187. && $this->autoInsertNotEmptyValidator()
  1188. && !$this->getValidator('NotEmpty'))
  1189. {
  1190. $validators = $this->getValidators();
  1191. $notEmpty = array('validator' => 'NotEmpty', 'breakChainOnFailure' => true);
  1192. array_unshift($validators, $notEmpty);
  1193. $this->setValidators($validators);
  1194. }
  1195. // Find the correct translator. Zend_Validate_Abstract::getDefaultTranslator()
  1196. // will get either the static translator attached to Zend_Validate_Abstract
  1197. // or the 'Zend_Translate' from Zend_Registry.
  1198. if (Zend_Validate_Abstract::hasDefaultTranslator() &&
  1199. !Zend_Form::hasDefaultTranslator())
  1200. {
  1201. $translator = Zend_Validate_Abstract::getDefaultTranslator();
  1202. if ($this->hasTranslator()) {
  1203. // only pick up this element's translator if it was attached directly.
  1204. $translator = $this->getTranslator();
  1205. }
  1206. } else {
  1207. $translator = $this->getTranslator();
  1208. }
  1209. $this->_messages = array();
  1210. $this->_errors = array();
  1211. $result = true;
  1212. $isArray = $this->isArray();
  1213. foreach ($this->getValidators() as $key => $validator) {
  1214. if (method_exists($validator, 'setTranslator')) {
  1215. if (method_exists($validator, 'hasTranslator')) {
  1216. if (!$validator->hasTranslator()) {
  1217. $validator->setTranslator($translator);
  1218. }
  1219. } else {
  1220. $validator->setTranslator($translator);
  1221. }
  1222. }
  1223. if (method_exists($validator, 'setDisableTranslator')) {
  1224. $validator->setDisableTranslator($this->translatorIsDisabled());
  1225. }
  1226. if ($isArray && is_array($value)) {
  1227. $messages = array();
  1228. $errors = array();
  1229. foreach ($value as $val) {
  1230. if (!$validator->isValid($val, $context)) {
  1231. $result = false;
  1232. if ($this->_hasErrorMessages()) {
  1233. $messages = $this->_getErrorMessages();
  1234. $errors = $messages;
  1235. } else {
  1236. $messages = array_merge($messages, $validator->getMessages());
  1237. $errors = array_merge($errors, $validator->getErrors());
  1238. }
  1239. }
  1240. }
  1241. if ($result) {
  1242. continue;
  1243. }
  1244. } elseif ($validator->isValid($value, $context)) {
  1245. continue;
  1246. } else {
  1247. $result = false;
  1248. if ($this->_hasErrorMessages()) {
  1249. $messages = $this->_getErrorMessages();
  1250. $errors = $messages;
  1251. } else {
  1252. $messages = $validator->getMessages();
  1253. $errors = array_keys($messages);
  1254. }
  1255. }
  1256. $result = false;
  1257. $this->_messages = array_merge($this->_messages, $messages);
  1258. $this->_errors = array_merge($this->_errors, $errors);
  1259. if ($validator->zfBreakChainOnFailure) {
  1260. break;
  1261. }
  1262. }
  1263. // If element manually flagged as invalid, return false
  1264. if ($this->_isErrorForced) {
  1265. return false;
  1266. }
  1267. return $result;
  1268. }
  1269. /**
  1270. * Add a custom error message to return in the event of failed validation
  1271. *
  1272. * @param string $message
  1273. * @return Zend_Form_Element
  1274. */
  1275. public function addErrorMessage($message)
  1276. {
  1277. $this->_errorMessages[] = (string) $message;
  1278. return $this;
  1279. }
  1280. /**
  1281. * Add multiple custom error messages to return in the event of failed validation
  1282. *
  1283. * @param array $messages
  1284. * @return Zend_Form_Element
  1285. */
  1286. public function addErrorMessages(array $messages)
  1287. {
  1288. foreach ($messages as $message) {
  1289. $this->addErrorMessage($message);
  1290. }
  1291. return $this;
  1292. }
  1293. /**
  1294. * Same as addErrorMessages(), but clears custom error message stack first
  1295. *
  1296. * @param array $messages
  1297. * @return Zend_Form_Element
  1298. */
  1299. public function setErrorMessages(array $messages)
  1300. {
  1301. $this->clearErrorMessages();
  1302. return $this->addErrorMessages($messages);
  1303. }
  1304. /**
  1305. * Retrieve custom error messages
  1306. *
  1307. * @return array
  1308. */
  1309. public function getErrorMessages()
  1310. {
  1311. return $this->_errorMessages;
  1312. }
  1313. /**
  1314. * Clear custom error messages stack
  1315. *
  1316. * @return Zend_Form_Element
  1317. */
  1318. public function clearErrorMessages()
  1319. {
  1320. $this->_errorMessages = array();
  1321. return $this;
  1322. }
  1323. /**
  1324. * Get errorMessageSeparator
  1325. *
  1326. * @return string
  1327. */
  1328. public function getErrorMessageSeparator()
  1329. {
  1330. return $this->_errorMessageSeparator;
  1331. }
  1332. /**
  1333. * Set errorMessageSeparator
  1334. *
  1335. * @param string $separator
  1336. * @return Zend_Form_Element
  1337. */
  1338. public function setErrorMessageSeparator($separator)
  1339. {
  1340. $this->_errorMessageSeparator = $separator;
  1341. return $this;
  1342. }
  1343. /**
  1344. * Mark the element as being in a failed validation state
  1345. *
  1346. * @return Zend_Form_Element
  1347. */
  1348. public function markAsError()
  1349. {
  1350. $messages = $this->getMessages();
  1351. $customMessages = $this->_getErrorMessages();
  1352. $messages = $messages + $customMessages;
  1353. if (empty($messages)) {
  1354. $this->_isError = true;
  1355. } else {
  1356. $this->_messages = $messages;
  1357. }
  1358. $this->_isErrorForced = true;
  1359. return $this;
  1360. }
  1361. /**
  1362. * Add an error message and mark element as failed validation
  1363. *
  1364. * @param string $message
  1365. * @return Zend_Form_Element
  1366. */
  1367. public function addError($message)
  1368. {
  1369. $this->addErrorMessage($message);
  1370. $this->markAsError();
  1371. return $this;
  1372. }
  1373. /**
  1374. * Add multiple error messages and flag element as failed validation
  1375. *
  1376. * @param array $messages
  1377. * @return Zend_Form_Element
  1378. */
  1379. public function addErrors(array $messages)
  1380. {
  1381. foreach ($messages as $message) {
  1382. $this->addError($message);
  1383. }
  1384. return $this;
  1385. }
  1386. /**
  1387. * Overwrite any previously set error messages and flag as failed validation
  1388. *
  1389. * @param array $messages
  1390. * @return Zend_Form_Element
  1391. */
  1392. public function setErrors(array $messages)
  1393. {
  1394. $this->clearErrorMessages();
  1395. return $this->addErrors($messages);
  1396. }
  1397. /**
  1398. * Are there errors registered?
  1399. *
  1400. * @return bool
  1401. */
  1402. public function hasErrors()
  1403. {
  1404. return (!empty($this->_messages) || $this->_isError);
  1405. }
  1406. /**
  1407. * Retrieve validator chain errors
  1408. *
  1409. * @return array
  1410. */
  1411. public function getErrors()
  1412. {
  1413. return $this->_errors;
  1414. }
  1415. /**
  1416. * Retrieve error messages
  1417. *
  1418. * @return array
  1419. */
  1420. public function getMessages()
  1421. {
  1422. return $this->_messages;
  1423. }
  1424. // Filtering
  1425. /**
  1426. * Add a filter to the element
  1427. *
  1428. * @param string|Zend_Filter_Interface $filter
  1429. * @return Zend_Form_Element
  1430. */
  1431. public function addFilter($filter, $options = array())
  1432. {
  1433. if ($filter instanceof Zend_Filter_Interface) {
  1434. $name = get_class($filter);
  1435. } elseif (is_string($filter)) {
  1436. $name = $filter;
  1437. $filter = array(
  1438. 'filter' => $filter,
  1439. 'options' => $options,
  1440. );
  1441. $this->_filters[$name] = $filter;
  1442. } else {
  1443. require_once 'Zend/Form/Exception.php';
  1444. throw new Zend_Form_Exception('Invalid filter provided to addFilter; must be string or Zend_Filter_Interface');
  1445. }
  1446. $this->_filters[$name] = $filter;
  1447. return $this;
  1448. }
  1449. /**
  1450. * Add filters to element
  1451. *
  1452. * @param array $filters
  1453. * @return Zend_Form_Element
  1454. */
  1455. public function addFilters(array $filters)
  1456. {
  1457. foreach ($filters as $filterInfo) {
  1458. if (is_string($filterInfo)) {
  1459. $this->addFilter($filterInfo);
  1460. } elseif ($filterInfo instanceof Zend_Filter_Interface) {
  1461. $this->addFilter($filterInfo);
  1462. } elseif (is_array($filterInfo)) {
  1463. $argc = count($filterInfo);
  1464. $options = array();
  1465. if (isset($filterInfo['filter'])) {
  1466. $filter = $filterInfo['filter'];
  1467. if (isset($filterInfo['options'])) {
  1468. $options = $filterInfo['options'];
  1469. }
  1470. $this->addFilter($filter, $options);
  1471. } else {
  1472. switch (true) {
  1473. case (0 == $argc):
  1474. break;
  1475. case (1 <= $argc):
  1476. $filter = array_shift($filterInfo);
  1477. case (2 <= $argc):
  1478. $options = array_shift($filterInfo);
  1479. default:
  1480. $this->addFilter($filter, $options);
  1481. break;
  1482. }
  1483. }
  1484. } else {
  1485. require_once 'Zend/Form/Exception.php';
  1486. throw new Zend_Form_Exception('Invalid filter passed to addFilters()');
  1487. }
  1488. }
  1489. return $this;
  1490. }
  1491. /**
  1492. * Add filters to element, overwriting any already existing
  1493. *
  1494. * @param array $filters
  1495. * @return Zend_Form_Element
  1496. */
  1497. public function setFilters(array $filters)
  1498. {
  1499. $this->clearFilters();
  1500. return $this->addFilters($filters);
  1501. }
  1502. /**
  1503. * Retrieve a single filter by name
  1504. *
  1505. * @param string $name
  1506. * @return Zend_Filter_Interface
  1507. */
  1508. public function getFilter($name)
  1509. {
  1510. if (!isset($this->_filters[$name])) {
  1511. $len = strlen($name);
  1512. foreach ($this->_filters as $localName => $filter) {
  1513. if ($len > strlen($localName)) {
  1514. continue;
  1515. }
  1516. if (0 === substr_compare($localName, $name, -$len, $len, true)) {
  1517. if (is_array($filter)) {
  1518. return $this->_loadFilter($filter);
  1519. }
  1520. return $filter;
  1521. }
  1522. }
  1523. return false;
  1524. }
  1525. if (is_array($this->_filters[$name])) {
  1526. return $this->_loadFilter($this->_filters[$name]);
  1527. }
  1528. return $this->_filters[$name];
  1529. }
  1530. /**
  1531. * Get all filters
  1532. *
  1533. * @return array
  1534. */
  1535. public function getFilters()
  1536. {
  1537. $filters = array();
  1538. foreach ($this->_filters as $key => $value) {
  1539. if ($value instanceof Zend_Filter_Interface) {
  1540. $filters[$key] = $value;
  1541. continue;
  1542. }
  1543. $filter = $this->_loadFilter($value);
  1544. $filters[get_class($filter)] = $filter;
  1545. }
  1546. return $filters;
  1547. }
  1548. /**
  1549. * Remove a filter by name
  1550. *
  1551. * @param string $name
  1552. * @return Zend_Form_Element
  1553. */
  1554. public function removeFilter($name)
  1555. {
  1556. if (isset($this->_filters[$name])) {
  1557. unset($this->_filters[$name]);
  1558. } else {
  1559. $len = strlen($name);
  1560. foreach (array_keys($this->_filters) as $filter) {
  1561. if ($len > strlen($filter)) {
  1562. continue;
  1563. }
  1564. if (0 === substr_compare($filter, $name, -$len, $len, true)) {
  1565. unset($this->_filters[$filter]);
  1566. break;
  1567. }
  1568. }
  1569. }
  1570. return $this;
  1571. }
  1572. /**
  1573. * Clear all filters
  1574. *
  1575. * @return Zend_Form_Element
  1576. */
  1577. public function clearFilters()
  1578. {
  1579. $this->_filters = array();
  1580. return $this;
  1581. }
  1582. // Rendering
  1583. /**
  1584. * Set view object
  1585. *
  1586. * @param Zend_View_Interface $view
  1587. * @return Zend_Form_Element
  1588. */
  1589. public function setView(Zend_View_Interface $view = null)
  1590. {
  1591. $this->_view = $view;
  1592. return $this;
  1593. }
  1594. /**
  1595. * Retrieve view object
  1596. *
  1597. * Retrieves from ViewRenderer if none previously set.
  1598. *
  1599. * @return null|Zend_View_Interface
  1600. */
  1601. public function getView()
  1602. {
  1603. if (null === $this->_view) {
  1604. require_once 'Zend/Controller/Action/HelperBroker.php';
  1605. $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
  1606. $this->setView($viewRenderer->view);
  1607. }
  1608. return $this->_view;
  1609. }
  1610. /**
  1611. * Instantiate a decorator based on class name or class name fragment
  1612. *
  1613. * @param string $name
  1614. * @param null|array $options
  1615. * @return Zend_Form_Decorator_Interface
  1616. */
  1617. protected function _getDecorator($name, $options)
  1618. {
  1619. $class = $this->getPluginLoader(self::DECORATOR)->load($name);
  1620. if (null === $options) {
  1621. $decorator = new $class;
  1622. } else {
  1623. $decorator = new $class($options);
  1624. }
  1625. return $decorator;
  1626. }
  1627. /**
  1628. * Add a decorator for rendering the element
  1629. *
  1630. * @param string|Zend_Form_Decorator_Interface $decorator
  1631. * @param array|Zend_Config $options Options with which to initialize decorator
  1632. * @return Zend_Form_Element
  1633. */
  1634. public function addDecorator($decorator, $options = null)
  1635. {
  1636. if ($decorator instanceof Zend_Form_Decorator_Interface) {
  1637. $name = get_class($decorator);
  1638. } elseif (is_string($decorator)) {
  1639. $name = $decorator;
  1640. $decorator = array(
  1641. 'decorator' => $name,
  1642. 'options' => $options,
  1643. );
  1644. } elseif (is_array($decorator)) {
  1645. foreach ($decorator as $name => $spec) {
  1646. break;
  1647. }
  1648. if (is_numeric($name)) {
  1649. require_once 'Zend/Form/Exception.php';
  1650. throw new Zend_Form_Exception('Invalid alias provided to addDecorator; must be alphanumeric string');
  1651. }
  1652. if (is_string($spec)) {
  1653. $decorator = array(
  1654. 'decorator' => $spec,
  1655. 'options' => $options,
  1656. );
  1657. } elseif ($spec instanceof Zend_Form_Decorator_Interface) {
  1658. $decorator = $spec;
  1659. }
  1660. } else {
  1661. require_once 'Zend/Form/Exception.php';
  1662. throw new Zend_Form_Exception('Invalid decorator provided to addDecorator; must be string or Zend_Form_Decorator_Interface');
  1663. }
  1664. $this->_decorators[$name] = $decorator;
  1665. return $this;
  1666. }
  1667. /**
  1668. * Add many decorators at once
  1669. *
  1670. * @param array $decorators
  1671. * @return Zend_Form_Element
  1672. */
  1673. public function addDecorators(array $decorators)
  1674. {
  1675. foreach ($decorators as $decoratorInfo) {
  1676. if (is_string($decoratorInfo)) {
  1677. $this->addDecorator($decoratorInfo);
  1678. } elseif ($decoratorInfo instanceof Zend_Form_Decorator_Interface) {
  1679. $this->addDecorator($decoratorInfo);
  1680. } elseif (is_array($decoratorInfo)) {
  1681. $argc = count($decoratorInfo);
  1682. $options = array();
  1683. if (isset($decoratorInfo['decorator'])) {
  1684. $decorator = $decoratorInfo['decorator'];
  1685. if (isset($decoratorInfo['options'])) {
  1686. $options = $decoratorInfo['options'];
  1687. }
  1688. $this->addDecorator($decorator, $options);
  1689. } else {
  1690. switch (true) {
  1691. case (0 == $argc):
  1692. break;
  1693. case (1 <= $argc):
  1694. $decorator = array_shift($decoratorInfo);
  1695. case (2 <= $argc):
  1696. $options = array_shift($decoratorInfo);
  1697. default:
  1698. $this->addDecorator($decorator, $options);
  1699. break;
  1700. }
  1701. }
  1702. } else {
  1703. require_once 'Zend/Form/Exception.php';
  1704. throw new Zend_Form_Exception('Invalid decorator passed to addDecorators()');
  1705. }
  1706. }
  1707. return $this;
  1708. }
  1709. /**
  1710. * Overwrite all decorators
  1711. *
  1712. * @param array $decorators
  1713. * @return Zend_Form_Element
  1714. */
  1715. public function setDecorators(array $decorators)
  1716. {
  1717. $this->clearDecorators();
  1718. return $this->addDecorators($decorators);
  1719. }
  1720. /**
  1721. * Retrieve a registered decorator
  1722. *
  1723. * @param string $name
  1724. * @return false|Zend_Form_Decorator_Abstract
  1725. */
  1726. public function getDecorator($name)
  1727. {
  1728. if (!isset($this->_decorators[$name])) {
  1729. $len = strlen($name);
  1730. foreach ($this->_decorators as $localName => $decorator) {
  1731. if ($len > strlen($localName)) {
  1732. continue;
  1733. }
  1734. if (0 === substr_compare($localName, $name, -$len, $len, true)) {
  1735. if (is_array($decorator)) {
  1736. return $this->_loadDecorator($decorator, $localName);
  1737. }
  1738. return $decorator;
  1739. }
  1740. }
  1741. return false;
  1742. }
  1743. if (is_array($this->_decorators[$name])) {
  1744. return $this->_loadDecorator($this->_decorators[$name], $name);
  1745. }
  1746. return $this->_decorators[$name];
  1747. }
  1748. /**
  1749. * Retrieve all decorators
  1750. *
  1751. * @return array
  1752. */
  1753. public function getDecorators()
  1754. {
  1755. foreach ($this->_decorators as $key => $value) {
  1756. if (is_array($value)) {
  1757. $this->_loadDecorator($value, $key);
  1758. }
  1759. }
  1760. return $this->_decorators;
  1761. }
  1762. /**
  1763. * Remove a single decorator
  1764. *
  1765. * @param string $name
  1766. * @return Zend_Form_Element
  1767. */
  1768. public function removeDecorator($name)
  1769. {
  1770. if (isset($this->_decorators[$name])) {
  1771. unset($this->_decorators[$name]);
  1772. } else {
  1773. $len = strlen($name);
  1774. foreach (array_keys($this->_decorators) as $decorator) {
  1775. if ($len > strlen($decorator)) {
  1776. continue;
  1777. }
  1778. if (0 === substr_compare($decorator, $name, -$len, $len, true)) {
  1779. unset($this->_decorators[$decorator]);
  1780. break;
  1781. }
  1782. }
  1783. }
  1784. return $this;
  1785. }
  1786. /**
  1787. * Clear all decorators
  1788. *
  1789. * @return Zend_Form_Element
  1790. */
  1791. public function clearDecorators()
  1792. {
  1793. $this->_decorators = array();
  1794. return $this;
  1795. }
  1796. /**
  1797. * Render form element
  1798. *
  1799. * @param Zend_View_Interface $view
  1800. * @return string
  1801. */
  1802. public function render(Zend_View_Interface $view = null)
  1803. {
  1804. if ($this->_isPartialRendering) {
  1805. return '';
  1806. }
  1807. if (null !== $view) {
  1808. $this->setView($view);
  1809. }
  1810. $content = '';
  1811. foreach ($this->getDecorators() as $decorator) {
  1812. $decorator->setElement($this);
  1813. $content = $decorator->render($content);
  1814. }
  1815. return $content;
  1816. }
  1817. /**
  1818. * String representation of form element
  1819. *
  1820. * Proxies to {@link render()}.
  1821. *
  1822. * @return string
  1823. */
  1824. public function __toString()
  1825. {
  1826. try {
  1827. $return = $this->render();
  1828. return $return;
  1829. } catch (Exception $e) {
  1830. trigger_error($e->getMessage(), E_USER_WARNING);
  1831. return '';
  1832. }
  1833. }
  1834. /**
  1835. * Lazy-load a filter
  1836. *
  1837. * @param array $filter
  1838. * @return Zend_Filter_Interface
  1839. */
  1840. protected function _loadFilter(array $filter)
  1841. {
  1842. $origName = $filter['filter'];
  1843. $name = $this->getPluginLoader(self::FILTER)->load($filter['filter']);
  1844. if (array_key_exists($name, $this->_filters)) {
  1845. require_once 'Zend/Form/Exception.php';
  1846. throw new Zend_Form_Exception(sprintf('Filter instance already exists for filter "%s"', $origName));
  1847. }
  1848. if (empty($filter['options'])) {
  1849. $instance = new $name;
  1850. } else {
  1851. $r = new ReflectionClass($name);
  1852. if ($r->hasMethod('__construct')) {
  1853. $instance = $r->newInstanceArgs((array) $filter['options']);
  1854. } else {
  1855. $instance = $r->newInstance();
  1856. }
  1857. }
  1858. if ($origName != $name) {
  1859. $filterNames = array_keys($this->_filters);
  1860. $order = array_flip($filterNames);
  1861. $order[$name] = $order[$origName];
  1862. $filtersExchange = array();
  1863. unset($order[$origName]);
  1864. asort($order);
  1865. foreach ($order as $key => $index) {
  1866. if ($key == $name) {
  1867. $filtersExchange[$key] = $instance;
  1868. continue;
  1869. }
  1870. $filtersExchange[$key] = $this->_filters[$key];
  1871. }
  1872. $this->_filters = $filtersExchange;
  1873. } else {
  1874. $this->_filters[$name] = $instance;
  1875. }
  1876. return $instance;
  1877. }
  1878. /**
  1879. * Lazy-load a validator
  1880. *
  1881. * @param array $validator Validator definition
  1882. * @return Zend_Validate_Interface
  1883. */
  1884. protected function _loadValidator(array $validator)
  1885. {
  1886. $origName = $validator['validator'];
  1887. $name = $this->getPluginLoader(self::VALIDATE)->load($validator['validator']);
  1888. if (array_key_exists($name, $this->_validators)) {
  1889. require_once 'Zend/Form/Exception.php';
  1890. throw new Zend_Form_Exception(sprintf('Validator instance already exists for validator "%s"', $origName));
  1891. }
  1892. $messages = false;
  1893. if (isset($validator['options']['messages'])) {
  1894. $messages = $validator['options']['messages'];
  1895. unset($validator['options']['messages']);
  1896. }
  1897. if (empty($validator['options'])) {
  1898. $instance = new $name;
  1899. } else {
  1900. $r = new ReflectionClass($name);
  1901. if ($r->hasMethod('__construct')) {
  1902. $numeric = false;
  1903. if (is_array($validator['options'])) {
  1904. $keys = array_keys($validator['options']);
  1905. foreach($keys as $key) {
  1906. if (is_numeric($key)) {
  1907. $numeric = true;
  1908. break;
  1909. }
  1910. }
  1911. }
  1912. if ($numeric) {
  1913. $instance = $r->newInstanceArgs((array) $validator['options']);
  1914. } else {
  1915. $instance = $r->newInstance($validator['options']);
  1916. }
  1917. } else {
  1918. $instance = $r->newInstance();
  1919. }
  1920. }
  1921. if ($messages) {
  1922. if (is_array($messages)) {
  1923. $instance->setMessages($messages);
  1924. } elseif (is_string($messages)) {
  1925. $instance->setMessage($messages);
  1926. }
  1927. }
  1928. $instance->zfBreakChainOnFailure = $validator['breakChainOnFailure'];
  1929. if ($origName != $name) {
  1930. $validatorNames = array_keys($this->_validators);
  1931. $order = array_flip($validatorNames);
  1932. $order[$name] = $order[$origName];
  1933. $validatorsExchange = array();
  1934. unset($order[$origName]);
  1935. asort($order);
  1936. foreach ($order as $key => $index) {
  1937. if ($key == $name) {
  1938. $validatorsExchange[$key] = $instance;
  1939. continue;
  1940. }
  1941. $validatorsExchange[$key] = $this->_validators[$key];
  1942. }
  1943. $this->_validators = $validatorsExchange;
  1944. } else {
  1945. $this->_validators[$name] = $instance;
  1946. }
  1947. return $instance;
  1948. }
  1949. /**
  1950. * Lazy-load a decorator
  1951. *
  1952. * @param array $decorator Decorator type and options
  1953. * @param mixed $name Decorator name or alias
  1954. * @return Zend_Form_Decorator_Interface
  1955. */
  1956. protected function _loadDecorator(array $decorator, $name)
  1957. {
  1958. $sameName = false;
  1959. if ($name == $decorator['decorator']) {
  1960. $sameName = true;
  1961. }
  1962. $instance = $this->_getDecorator($decorator['decorator'], $decorator['options']);
  1963. if ($sameName) {
  1964. $newName = get_class($instance);
  1965. $decoratorNames = array_keys($this->_decorators);
  1966. $order = array_flip($decoratorNames);
  1967. $order[$newName] = $order[$name];
  1968. $decoratorsExchange = array();
  1969. unset($order[$name]);
  1970. asort($order);
  1971. foreach ($order as $key => $index) {
  1972. if ($key == $newName) {
  1973. $decoratorsExchange[$key] = $instance;
  1974. continue;
  1975. }
  1976. $decoratorsExchange[$key] = $this->_decorators[$key];
  1977. }
  1978. $this->_decorators = $decoratorsExchange;
  1979. } else {
  1980. $this->_decorators[$name] = $instance;
  1981. }
  1982. return $instance;
  1983. }
  1984. /**
  1985. * Retrieve error messages and perform translation and value substitution
  1986. *
  1987. * @return array
  1988. */
  1989. protected function _getErrorMessages()
  1990. {
  1991. $translator = $this->getTranslator();
  1992. $messages = $this->getErrorMessages();
  1993. $value = $this->getValue();
  1994. foreach ($messages as $key => $message) {
  1995. if (null !== $translator) {
  1996. $message = $translator->translate($message);
  1997. }
  1998. if (($this->isArray() || is_array($value))
  1999. && !empty($value)
  2000. ) {
  2001. $aggregateMessages = array();
  2002. foreach ($value as $val) {
  2003. $aggregateMessages[] = str_replace('%value%', $val, $message);
  2004. }
  2005. $messages[$key] = implode($this->getErrorMessageSeparator(), $aggregateMessages);
  2006. } else {
  2007. $messages[$key] = str_replace('%value%', $value, $message);
  2008. }
  2009. }
  2010. return $messages;
  2011. }
  2012. /**
  2013. * Are there custom error messages registered?
  2014. *
  2015. * @return bool
  2016. */
  2017. protected function _hasErrorMessages()
  2018. {
  2019. return !empty($this->_errorMessages);
  2020. }
  2021. }