Element.php 59 KB

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