Element.php 61 KB

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