Element.php 58 KB

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