Element.php 57 KB

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