2
0

Element.php 57 KB

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