2
0

Element.php 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219
  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. $this->_messages = array();
  1196. $this->_errors = array();
  1197. $result = true;
  1198. $isArray = $this->isArray();
  1199. foreach ($this->getValidators() as $key => $validator) {
  1200. if (method_exists($validator, 'setTranslator')) {
  1201. $validator->setTranslator($this->getTranslator());
  1202. }
  1203. if (method_exists($validator, 'setDisableTranslator')) {
  1204. $validator->setDisableTranslator($this->translatorIsDisabled());
  1205. }
  1206. if ($isArray && is_array($value)) {
  1207. $messages = array();
  1208. $errors = array();
  1209. foreach ($value as $val) {
  1210. if (!$validator->isValid($val, $context)) {
  1211. $result = false;
  1212. if ($this->_hasErrorMessages()) {
  1213. $messages = $this->_getErrorMessages();
  1214. $errors = $messages;
  1215. } else {
  1216. $messages = array_merge($messages, $validator->getMessages());
  1217. $errors = array_merge($errors, $validator->getErrors());
  1218. }
  1219. }
  1220. }
  1221. if ($result) {
  1222. continue;
  1223. }
  1224. } elseif ($validator->isValid($value, $context)) {
  1225. continue;
  1226. } else {
  1227. $result = false;
  1228. if ($this->_hasErrorMessages()) {
  1229. $messages = $this->_getErrorMessages();
  1230. $errors = $messages;
  1231. } else {
  1232. $messages = $validator->getMessages();
  1233. $errors = array_keys($messages);
  1234. }
  1235. }
  1236. $result = false;
  1237. $this->_messages = array_merge($this->_messages, $messages);
  1238. $this->_errors = array_merge($this->_errors, $errors);
  1239. if ($validator->zfBreakChainOnFailure) {
  1240. break;
  1241. }
  1242. }
  1243. // If element manually flagged as invalid, return false
  1244. if ($this->_isErrorForced) {
  1245. return false;
  1246. }
  1247. return $result;
  1248. }
  1249. /**
  1250. * Add a custom error message to return in the event of failed validation
  1251. *
  1252. * @param string $message
  1253. * @return Zend_Form_Element
  1254. */
  1255. public function addErrorMessage($message)
  1256. {
  1257. $this->_errorMessages[] = (string) $message;
  1258. return $this;
  1259. }
  1260. /**
  1261. * Add multiple custom error messages to return in the event of failed validation
  1262. *
  1263. * @param array $messages
  1264. * @return Zend_Form_Element
  1265. */
  1266. public function addErrorMessages(array $messages)
  1267. {
  1268. foreach ($messages as $message) {
  1269. $this->addErrorMessage($message);
  1270. }
  1271. return $this;
  1272. }
  1273. /**
  1274. * Same as addErrorMessages(), but clears custom error message stack first
  1275. *
  1276. * @param array $messages
  1277. * @return Zend_Form_Element
  1278. */
  1279. public function setErrorMessages(array $messages)
  1280. {
  1281. $this->clearErrorMessages();
  1282. return $this->addErrorMessages($messages);
  1283. }
  1284. /**
  1285. * Retrieve custom error messages
  1286. *
  1287. * @return array
  1288. */
  1289. public function getErrorMessages()
  1290. {
  1291. return $this->_errorMessages;
  1292. }
  1293. /**
  1294. * Clear custom error messages stack
  1295. *
  1296. * @return Zend_Form_Element
  1297. */
  1298. public function clearErrorMessages()
  1299. {
  1300. $this->_errorMessages = array();
  1301. return $this;
  1302. }
  1303. /**
  1304. * Get errorMessageSeparator
  1305. *
  1306. * @return string
  1307. */
  1308. public function getErrorMessageSeparator()
  1309. {
  1310. return $this->_errorMessageSeparator;
  1311. }
  1312. /**
  1313. * Set errorMessageSeparator
  1314. *
  1315. * @param string $separator
  1316. * @return Zend_Form_Element
  1317. */
  1318. public function setErrorMessageSeparator($separator)
  1319. {
  1320. $this->_errorMessageSeparator = $separator;
  1321. return $this;
  1322. }
  1323. /**
  1324. * Mark the element as being in a failed validation state
  1325. *
  1326. * @return Zend_Form_Element
  1327. */
  1328. public function markAsError()
  1329. {
  1330. $messages = $this->getMessages();
  1331. $customMessages = $this->_getErrorMessages();
  1332. $messages = $messages + $customMessages;
  1333. if (empty($messages)) {
  1334. $this->_isError = true;
  1335. } else {
  1336. $this->_messages = $messages;
  1337. }
  1338. $this->_isErrorForced = true;
  1339. return $this;
  1340. }
  1341. /**
  1342. * Add an error message and mark element as failed validation
  1343. *
  1344. * @param string $message
  1345. * @return Zend_Form_Element
  1346. */
  1347. public function addError($message)
  1348. {
  1349. $this->addErrorMessage($message);
  1350. $this->markAsError();
  1351. return $this;
  1352. }
  1353. /**
  1354. * Add multiple error messages and flag element as failed validation
  1355. *
  1356. * @param array $messages
  1357. * @return Zend_Form_Element
  1358. */
  1359. public function addErrors(array $messages)
  1360. {
  1361. foreach ($messages as $message) {
  1362. $this->addError($message);
  1363. }
  1364. return $this;
  1365. }
  1366. /**
  1367. * Overwrite any previously set error messages and flag as failed validation
  1368. *
  1369. * @param array $messages
  1370. * @return Zend_Form_Element
  1371. */
  1372. public function setErrors(array $messages)
  1373. {
  1374. $this->clearErrorMessages();
  1375. return $this->addErrors($messages);
  1376. }
  1377. /**
  1378. * Are there errors registered?
  1379. *
  1380. * @return bool
  1381. */
  1382. public function hasErrors()
  1383. {
  1384. return (!empty($this->_messages) || $this->_isError);
  1385. }
  1386. /**
  1387. * Retrieve validator chain errors
  1388. *
  1389. * @return array
  1390. */
  1391. public function getErrors()
  1392. {
  1393. return $this->_errors;
  1394. }
  1395. /**
  1396. * Retrieve error messages
  1397. *
  1398. * @return array
  1399. */
  1400. public function getMessages()
  1401. {
  1402. return $this->_messages;
  1403. }
  1404. // Filtering
  1405. /**
  1406. * Add a filter to the element
  1407. *
  1408. * @param string|Zend_Filter_Interface $filter
  1409. * @return Zend_Form_Element
  1410. */
  1411. public function addFilter($filter, $options = array())
  1412. {
  1413. if ($filter instanceof Zend_Filter_Interface) {
  1414. $name = get_class($filter);
  1415. } elseif (is_string($filter)) {
  1416. $name = $filter;
  1417. $filter = array(
  1418. 'filter' => $filter,
  1419. 'options' => $options,
  1420. );
  1421. $this->_filters[$name] = $filter;
  1422. } else {
  1423. require_once 'Zend/Form/Exception.php';
  1424. throw new Zend_Form_Exception('Invalid filter provided to addFilter; must be string or Zend_Filter_Interface');
  1425. }
  1426. $this->_filters[$name] = $filter;
  1427. return $this;
  1428. }
  1429. /**
  1430. * Add filters to element
  1431. *
  1432. * @param array $filters
  1433. * @return Zend_Form_Element
  1434. */
  1435. public function addFilters(array $filters)
  1436. {
  1437. foreach ($filters as $filterInfo) {
  1438. if (is_string($filterInfo)) {
  1439. $this->addFilter($filterInfo);
  1440. } elseif ($filterInfo instanceof Zend_Filter_Interface) {
  1441. $this->addFilter($filterInfo);
  1442. } elseif (is_array($filterInfo)) {
  1443. $argc = count($filterInfo);
  1444. $options = array();
  1445. if (isset($filterInfo['filter'])) {
  1446. $filter = $filterInfo['filter'];
  1447. if (isset($filterInfo['options'])) {
  1448. $options = $filterInfo['options'];
  1449. }
  1450. $this->addFilter($filter, $options);
  1451. } else {
  1452. switch (true) {
  1453. case (0 == $argc):
  1454. break;
  1455. case (1 <= $argc):
  1456. $filter = array_shift($filterInfo);
  1457. case (2 <= $argc):
  1458. $options = array_shift($filterInfo);
  1459. default:
  1460. $this->addFilter($filter, $options);
  1461. break;
  1462. }
  1463. }
  1464. } else {
  1465. require_once 'Zend/Form/Exception.php';
  1466. throw new Zend_Form_Exception('Invalid filter passed to addFilters()');
  1467. }
  1468. }
  1469. return $this;
  1470. }
  1471. /**
  1472. * Add filters to element, overwriting any already existing
  1473. *
  1474. * @param array $filters
  1475. * @return Zend_Form_Element
  1476. */
  1477. public function setFilters(array $filters)
  1478. {
  1479. $this->clearFilters();
  1480. return $this->addFilters($filters);
  1481. }
  1482. /**
  1483. * Retrieve a single filter by name
  1484. *
  1485. * @param string $name
  1486. * @return Zend_Filter_Interface
  1487. */
  1488. public function getFilter($name)
  1489. {
  1490. if (!isset($this->_filters[$name])) {
  1491. $len = strlen($name);
  1492. foreach ($this->_filters as $localName => $filter) {
  1493. if ($len > strlen($localName)) {
  1494. continue;
  1495. }
  1496. if (0 === substr_compare($localName, $name, -$len, $len, true)) {
  1497. if (is_array($filter)) {
  1498. return $this->_loadFilter($filter);
  1499. }
  1500. return $filter;
  1501. }
  1502. }
  1503. return false;
  1504. }
  1505. if (is_array($this->_filters[$name])) {
  1506. return $this->_loadFilter($this->_filters[$name]);
  1507. }
  1508. return $this->_filters[$name];
  1509. }
  1510. /**
  1511. * Get all filters
  1512. *
  1513. * @return array
  1514. */
  1515. public function getFilters()
  1516. {
  1517. $filters = array();
  1518. foreach ($this->_filters as $key => $value) {
  1519. if ($value instanceof Zend_Filter_Interface) {
  1520. $filters[$key] = $value;
  1521. continue;
  1522. }
  1523. $filter = $this->_loadFilter($value);
  1524. $filters[get_class($filter)] = $filter;
  1525. }
  1526. return $filters;
  1527. }
  1528. /**
  1529. * Remove a filter by name
  1530. *
  1531. * @param string $name
  1532. * @return Zend_Form_Element
  1533. */
  1534. public function removeFilter($name)
  1535. {
  1536. if (isset($this->_filters[$name])) {
  1537. unset($this->_filters[$name]);
  1538. } else {
  1539. $len = strlen($name);
  1540. foreach (array_keys($this->_filters) as $filter) {
  1541. if ($len > strlen($filter)) {
  1542. continue;
  1543. }
  1544. if (0 === substr_compare($filter, $name, -$len, $len, true)) {
  1545. unset($this->_filters[$filter]);
  1546. break;
  1547. }
  1548. }
  1549. }
  1550. return $this;
  1551. }
  1552. /**
  1553. * Clear all filters
  1554. *
  1555. * @return Zend_Form_Element
  1556. */
  1557. public function clearFilters()
  1558. {
  1559. $this->_filters = array();
  1560. return $this;
  1561. }
  1562. // Rendering
  1563. /**
  1564. * Set view object
  1565. *
  1566. * @param Zend_View_Interface $view
  1567. * @return Zend_Form_Element
  1568. */
  1569. public function setView(Zend_View_Interface $view = null)
  1570. {
  1571. $this->_view = $view;
  1572. return $this;
  1573. }
  1574. /**
  1575. * Retrieve view object
  1576. *
  1577. * Retrieves from ViewRenderer if none previously set.
  1578. *
  1579. * @return null|Zend_View_Interface
  1580. */
  1581. public function getView()
  1582. {
  1583. if (null === $this->_view) {
  1584. require_once 'Zend/Controller/Action/HelperBroker.php';
  1585. $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
  1586. $this->setView($viewRenderer->view);
  1587. }
  1588. return $this->_view;
  1589. }
  1590. /**
  1591. * Instantiate a decorator based on class name or class name fragment
  1592. *
  1593. * @param string $name
  1594. * @param null|array $options
  1595. * @return Zend_Form_Decorator_Interface
  1596. */
  1597. protected function _getDecorator($name, $options)
  1598. {
  1599. $class = $this->getPluginLoader(self::DECORATOR)->load($name);
  1600. if (null === $options) {
  1601. $decorator = new $class;
  1602. } else {
  1603. $decorator = new $class($options);
  1604. }
  1605. return $decorator;
  1606. }
  1607. /**
  1608. * Add a decorator for rendering the element
  1609. *
  1610. * @param string|Zend_Form_Decorator_Interface $decorator
  1611. * @param array|Zend_Config $options Options with which to initialize decorator
  1612. * @return Zend_Form_Element
  1613. */
  1614. public function addDecorator($decorator, $options = null)
  1615. {
  1616. if ($decorator instanceof Zend_Form_Decorator_Interface) {
  1617. $name = get_class($decorator);
  1618. } elseif (is_string($decorator)) {
  1619. $name = $decorator;
  1620. $decorator = array(
  1621. 'decorator' => $name,
  1622. 'options' => $options,
  1623. );
  1624. } elseif (is_array($decorator)) {
  1625. foreach ($decorator as $name => $spec) {
  1626. break;
  1627. }
  1628. if (is_numeric($name)) {
  1629. require_once 'Zend/Form/Exception.php';
  1630. throw new Zend_Form_Exception('Invalid alias provided to addDecorator; must be alphanumeric string');
  1631. }
  1632. if (is_string($spec)) {
  1633. $decorator = array(
  1634. 'decorator' => $spec,
  1635. 'options' => $options,
  1636. );
  1637. } elseif ($spec instanceof Zend_Form_Decorator_Interface) {
  1638. $decorator = $spec;
  1639. }
  1640. } else {
  1641. require_once 'Zend/Form/Exception.php';
  1642. throw new Zend_Form_Exception('Invalid decorator provided to addDecorator; must be string or Zend_Form_Decorator_Interface');
  1643. }
  1644. $this->_decorators[$name] = $decorator;
  1645. return $this;
  1646. }
  1647. /**
  1648. * Add many decorators at once
  1649. *
  1650. * @param array $decorators
  1651. * @return Zend_Form_Element
  1652. */
  1653. public function addDecorators(array $decorators)
  1654. {
  1655. foreach ($decorators as $decoratorInfo) {
  1656. if (is_string($decoratorInfo)) {
  1657. $this->addDecorator($decoratorInfo);
  1658. } elseif ($decoratorInfo instanceof Zend_Form_Decorator_Interface) {
  1659. $this->addDecorator($decoratorInfo);
  1660. } elseif (is_array($decoratorInfo)) {
  1661. $argc = count($decoratorInfo);
  1662. $options = array();
  1663. if (isset($decoratorInfo['decorator'])) {
  1664. $decorator = $decoratorInfo['decorator'];
  1665. if (isset($decoratorInfo['options'])) {
  1666. $options = $decoratorInfo['options'];
  1667. }
  1668. $this->addDecorator($decorator, $options);
  1669. } else {
  1670. switch (true) {
  1671. case (0 == $argc):
  1672. break;
  1673. case (1 <= $argc):
  1674. $decorator = array_shift($decoratorInfo);
  1675. case (2 <= $argc):
  1676. $options = array_shift($decoratorInfo);
  1677. default:
  1678. $this->addDecorator($decorator, $options);
  1679. break;
  1680. }
  1681. }
  1682. } else {
  1683. require_once 'Zend/Form/Exception.php';
  1684. throw new Zend_Form_Exception('Invalid decorator passed to addDecorators()');
  1685. }
  1686. }
  1687. return $this;
  1688. }
  1689. /**
  1690. * Overwrite all decorators
  1691. *
  1692. * @param array $decorators
  1693. * @return Zend_Form_Element
  1694. */
  1695. public function setDecorators(array $decorators)
  1696. {
  1697. $this->clearDecorators();
  1698. return $this->addDecorators($decorators);
  1699. }
  1700. /**
  1701. * Retrieve a registered decorator
  1702. *
  1703. * @param string $name
  1704. * @return false|Zend_Form_Decorator_Abstract
  1705. */
  1706. public function getDecorator($name)
  1707. {
  1708. if (!isset($this->_decorators[$name])) {
  1709. $len = strlen($name);
  1710. foreach ($this->_decorators as $localName => $decorator) {
  1711. if ($len > strlen($localName)) {
  1712. continue;
  1713. }
  1714. if (0 === substr_compare($localName, $name, -$len, $len, true)) {
  1715. if (is_array($decorator)) {
  1716. return $this->_loadDecorator($decorator, $localName);
  1717. }
  1718. return $decorator;
  1719. }
  1720. }
  1721. return false;
  1722. }
  1723. if (is_array($this->_decorators[$name])) {
  1724. return $this->_loadDecorator($this->_decorators[$name], $name);
  1725. }
  1726. return $this->_decorators[$name];
  1727. }
  1728. /**
  1729. * Retrieve all decorators
  1730. *
  1731. * @return array
  1732. */
  1733. public function getDecorators()
  1734. {
  1735. foreach ($this->_decorators as $key => $value) {
  1736. if (is_array($value)) {
  1737. $this->_loadDecorator($value, $key);
  1738. }
  1739. }
  1740. return $this->_decorators;
  1741. }
  1742. /**
  1743. * Remove a single decorator
  1744. *
  1745. * @param string $name
  1746. * @return Zend_Form_Element
  1747. */
  1748. public function removeDecorator($name)
  1749. {
  1750. if (isset($this->_decorators[$name])) {
  1751. unset($this->_decorators[$name]);
  1752. } else {
  1753. $len = strlen($name);
  1754. foreach (array_keys($this->_decorators) as $decorator) {
  1755. if ($len > strlen($decorator)) {
  1756. continue;
  1757. }
  1758. if (0 === substr_compare($decorator, $name, -$len, $len, true)) {
  1759. unset($this->_decorators[$decorator]);
  1760. break;
  1761. }
  1762. }
  1763. }
  1764. return $this;
  1765. }
  1766. /**
  1767. * Clear all decorators
  1768. *
  1769. * @return Zend_Form_Element
  1770. */
  1771. public function clearDecorators()
  1772. {
  1773. $this->_decorators = array();
  1774. return $this;
  1775. }
  1776. /**
  1777. * Render form element
  1778. *
  1779. * @param Zend_View_Interface $view
  1780. * @return string
  1781. */
  1782. public function render(Zend_View_Interface $view = null)
  1783. {
  1784. if ($this->_isPartialRendering) {
  1785. return '';
  1786. }
  1787. if (null !== $view) {
  1788. $this->setView($view);
  1789. }
  1790. $content = '';
  1791. foreach ($this->getDecorators() as $decorator) {
  1792. $decorator->setElement($this);
  1793. $content = $decorator->render($content);
  1794. }
  1795. return $content;
  1796. }
  1797. /**
  1798. * String representation of form element
  1799. *
  1800. * Proxies to {@link render()}.
  1801. *
  1802. * @return string
  1803. */
  1804. public function __toString()
  1805. {
  1806. try {
  1807. $return = $this->render();
  1808. return $return;
  1809. } catch (Exception $e) {
  1810. trigger_error($e->getMessage(), E_USER_WARNING);
  1811. return '';
  1812. }
  1813. }
  1814. /**
  1815. * Lazy-load a filter
  1816. *
  1817. * @param array $filter
  1818. * @return Zend_Filter_Interface
  1819. */
  1820. protected function _loadFilter(array $filter)
  1821. {
  1822. $origName = $filter['filter'];
  1823. $name = $this->getPluginLoader(self::FILTER)->load($filter['filter']);
  1824. if (array_key_exists($name, $this->_filters)) {
  1825. require_once 'Zend/Form/Exception.php';
  1826. throw new Zend_Form_Exception(sprintf('Filter instance already exists for filter "%s"', $origName));
  1827. }
  1828. if (empty($filter['options'])) {
  1829. $instance = new $name;
  1830. } else {
  1831. $r = new ReflectionClass($name);
  1832. if ($r->hasMethod('__construct')) {
  1833. $instance = $r->newInstanceArgs((array) $filter['options']);
  1834. } else {
  1835. $instance = $r->newInstance();
  1836. }
  1837. }
  1838. if ($origName != $name) {
  1839. $filterNames = array_keys($this->_filters);
  1840. $order = array_flip($filterNames);
  1841. $order[$name] = $order[$origName];
  1842. $filtersExchange = array();
  1843. unset($order[$origName]);
  1844. asort($order);
  1845. foreach ($order as $key => $index) {
  1846. if ($key == $name) {
  1847. $filtersExchange[$key] = $instance;
  1848. continue;
  1849. }
  1850. $filtersExchange[$key] = $this->_filters[$key];
  1851. }
  1852. $this->_filters = $filtersExchange;
  1853. } else {
  1854. $this->_filters[$name] = $instance;
  1855. }
  1856. return $instance;
  1857. }
  1858. /**
  1859. * Lazy-load a validator
  1860. *
  1861. * @param array $validator Validator definition
  1862. * @return Zend_Validate_Interface
  1863. */
  1864. protected function _loadValidator(array $validator)
  1865. {
  1866. $origName = $validator['validator'];
  1867. $name = $this->getPluginLoader(self::VALIDATE)->load($validator['validator']);
  1868. if (array_key_exists($name, $this->_validators)) {
  1869. require_once 'Zend/Form/Exception.php';
  1870. throw new Zend_Form_Exception(sprintf('Validator instance already exists for validator "%s"', $origName));
  1871. }
  1872. $messages = false;
  1873. if (isset($validator['options']['messages'])) {
  1874. $messages = $validator['options']['messages'];
  1875. unset($validator['options']['messages']);
  1876. }
  1877. if (empty($validator['options'])) {
  1878. $instance = new $name;
  1879. } else {
  1880. $r = new ReflectionClass($name);
  1881. if ($r->hasMethod('__construct')) {
  1882. $numeric = false;
  1883. if (is_array($validator['options'])) {
  1884. $keys = array_keys($validator['options']);
  1885. foreach($keys as $key) {
  1886. if (is_numeric($key)) {
  1887. $numeric = true;
  1888. break;
  1889. }
  1890. }
  1891. }
  1892. if ($numeric) {
  1893. $instance = $r->newInstanceArgs((array) $validator['options']);
  1894. } else {
  1895. $instance = $r->newInstance($validator['options']);
  1896. }
  1897. } else {
  1898. $instance = $r->newInstance();
  1899. }
  1900. }
  1901. if ($messages) {
  1902. if (is_array($messages)) {
  1903. $instance->setMessages($messages);
  1904. } elseif (is_string($messages)) {
  1905. $instance->setMessage($messages);
  1906. }
  1907. }
  1908. $instance->zfBreakChainOnFailure = $validator['breakChainOnFailure'];
  1909. if ($origName != $name) {
  1910. $validatorNames = array_keys($this->_validators);
  1911. $order = array_flip($validatorNames);
  1912. $order[$name] = $order[$origName];
  1913. $validatorsExchange = array();
  1914. unset($order[$origName]);
  1915. asort($order);
  1916. foreach ($order as $key => $index) {
  1917. if ($key == $name) {
  1918. $validatorsExchange[$key] = $instance;
  1919. continue;
  1920. }
  1921. $validatorsExchange[$key] = $this->_validators[$key];
  1922. }
  1923. $this->_validators = $validatorsExchange;
  1924. } else {
  1925. $this->_validators[$name] = $instance;
  1926. }
  1927. return $instance;
  1928. }
  1929. /**
  1930. * Lazy-load a decorator
  1931. *
  1932. * @param array $decorator Decorator type and options
  1933. * @param mixed $name Decorator name or alias
  1934. * @return Zend_Form_Decorator_Interface
  1935. */
  1936. protected function _loadDecorator(array $decorator, $name)
  1937. {
  1938. $sameName = false;
  1939. if ($name == $decorator['decorator']) {
  1940. $sameName = true;
  1941. }
  1942. $instance = $this->_getDecorator($decorator['decorator'], $decorator['options']);
  1943. if ($sameName) {
  1944. $newName = get_class($instance);
  1945. $decoratorNames = array_keys($this->_decorators);
  1946. $order = array_flip($decoratorNames);
  1947. $order[$newName] = $order[$name];
  1948. $decoratorsExchange = array();
  1949. unset($order[$name]);
  1950. asort($order);
  1951. foreach ($order as $key => $index) {
  1952. if ($key == $newName) {
  1953. $decoratorsExchange[$key] = $instance;
  1954. continue;
  1955. }
  1956. $decoratorsExchange[$key] = $this->_decorators[$key];
  1957. }
  1958. $this->_decorators = $decoratorsExchange;
  1959. } else {
  1960. $this->_decorators[$name] = $instance;
  1961. }
  1962. return $instance;
  1963. }
  1964. /**
  1965. * Retrieve error messages and perform translation and value substitution
  1966. *
  1967. * @return array
  1968. */
  1969. protected function _getErrorMessages()
  1970. {
  1971. $translator = $this->getTranslator();
  1972. $messages = $this->getErrorMessages();
  1973. $value = $this->getValue();
  1974. foreach ($messages as $key => $message) {
  1975. if (null !== $translator) {
  1976. $message = $translator->translate($message);
  1977. }
  1978. if (($this->isArray() || is_array($value))
  1979. && !empty($value)
  1980. ) {
  1981. $aggregateMessages = array();
  1982. foreach ($value as $val) {
  1983. $aggregateMessages[] = str_replace('%value%', $val, $message);
  1984. }
  1985. $messages[$key] = implode($this->getErrorMessageSeparator(), $aggregateMessages);
  1986. } else {
  1987. $messages[$key] = str_replace('%value%', $value, $message);
  1988. }
  1989. }
  1990. return $messages;
  1991. }
  1992. /**
  1993. * Are there custom error messages registered?
  1994. *
  1995. * @return bool
  1996. */
  1997. protected function _hasErrorMessages()
  1998. {
  1999. return !empty($this->_errorMessages);
  2000. }
  2001. }