Element.php 58 KB

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