Element.php 59 KB

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