PageRenderTime 68ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/tests/Zend/Form/FormTest.php

https://bitbucket.org/ksekar/campus
PHP | 4586 lines | 3757 code | 613 blank | 216 comment | 31 complexity | 880fcb1b5dd37cd1df3f4daa4e24e202 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.0, MIT
  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. * @subpackage UnitTests
  18. * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id: FormTest.php 24594 2012-01-05 21:27:01Z matthew $
  21. */
  22. if (!defined('PHPUnit_MAIN_METHOD')) {
  23. define('PHPUnit_MAIN_METHOD', 'Zend_Form_FormTest::main');
  24. }
  25. require_once 'Zend/Form.php';
  26. require_once 'Zend/Config.php';
  27. require_once 'Zend/Controller/Action/HelperBroker.php';
  28. require_once 'Zend/Form/Decorator/Form.php';
  29. require_once 'Zend/Form/DisplayGroup.php';
  30. require_once 'Zend/Form/Element.php';
  31. require_once 'Zend/Form/Element/Text.php';
  32. require_once 'Zend/Form/Element/File.php';
  33. require_once 'Zend/Form/SubForm.php';
  34. require_once 'Zend/Loader/PluginLoader.php';
  35. require_once 'Zend/Registry.php';
  36. require_once 'Zend/Translate.php';
  37. require_once 'Zend/View.php';
  38. /**
  39. * @category Zend
  40. * @package Zend_Form
  41. * @subpackage UnitTests
  42. * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
  43. * @license http://framework.zend.com/license/new-bsd New BSD License
  44. * @group Zend_Form
  45. */
  46. class Zend_Form_FormTest extends PHPUnit_Framework_TestCase
  47. {
  48. /**
  49. * @var Zend_Form
  50. */
  51. public $form;
  52. public static function main()
  53. {
  54. $suite = new PHPUnit_Framework_TestSuite('Zend_Form_FormTest');
  55. $result = PHPUnit_TextUI_TestRunner::run($suite);
  56. }
  57. public function clearRegistry()
  58. {
  59. if (Zend_Registry::isRegistered('Zend_Translate')) {
  60. $registry = Zend_Registry::getInstance();
  61. unset($registry['Zend_Translate']);
  62. }
  63. }
  64. public function setUp()
  65. {
  66. $this->clearRegistry();
  67. Zend_Form::setDefaultTranslator(null);
  68. if (isset($this->error)) {
  69. unset($this->error);
  70. }
  71. Zend_Controller_Action_HelperBroker::resetHelpers();
  72. $this->form = new Zend_Form();
  73. }
  74. public function tearDown()
  75. {
  76. $this->clearRegistry();
  77. }
  78. public function testZendFormImplementsZendValidateInterface()
  79. {
  80. $this->assertTrue($this->form instanceof Zend_Validate_Interface);
  81. }
  82. // Configuration
  83. public function getOptions()
  84. {
  85. $options = array(
  86. 'name' => 'foo',
  87. 'class' => 'someform',
  88. 'action' => '/foo/bar',
  89. 'method' => 'put',
  90. );
  91. return $options;
  92. }
  93. public function testCanSetObjectStateViaSetOptions()
  94. {
  95. $options = $this->getOptions();
  96. $this->form->setOptions($options);
  97. $this->assertEquals('foo', $this->form->getName());
  98. $this->assertEquals('someform', $this->form->getAttrib('class'));
  99. $this->assertEquals('/foo/bar', $this->form->getAction());
  100. $this->assertEquals('put', $this->form->getMethod());
  101. }
  102. public function testCanSetObjectStateByPassingOptionsToConstructor()
  103. {
  104. $options = $this->getOptions();
  105. $form = new Zend_Form($options);
  106. $this->assertEquals('foo', $form->getName());
  107. $this->assertEquals('someform', $form->getAttrib('class'));
  108. $this->assertEquals('/foo/bar', $form->getAction());
  109. $this->assertEquals('put', $form->getMethod());
  110. }
  111. public function testSetOptionsSkipsCallsToSetOptionsAndSetConfig()
  112. {
  113. $options = $this->getOptions();
  114. $config = new Zend_Config($options);
  115. $options['config'] = $config;
  116. $options['options'] = $config->toArray();
  117. $this->form->setOptions($options);
  118. }
  119. public function testSetOptionsSkipsSettingAccessorsRequiringObjectsWhenNonObjectPassed()
  120. {
  121. $options = $this->getOptions();
  122. $options['pluginLoader'] = true;
  123. $options['subForms'] = true;
  124. $options['view'] = true;
  125. $options['translator'] = true;
  126. $options['default'] = true;
  127. $options['attrib'] = true;
  128. $this->form->setOptions($options);
  129. }
  130. public function testSetOptionsWithAttribsDoesNotOverwriteActionOrMethodOrName()
  131. {
  132. $attribs = $this->getOptions();
  133. unset($attribs['action'], $attribs['method']);
  134. $options = array(
  135. 'name' => 'MYFORM',
  136. 'action' => '/bar/baz',
  137. 'method' => 'GET',
  138. 'attribs' => $attribs,
  139. );
  140. $form = new Zend_Form($options);
  141. $this->assertEquals($options['name'], $form->getName());
  142. $this->assertEquals($options['action'], $form->getAction());
  143. $this->assertEquals(strtolower($options['method']), strtolower($form->getMethod()));
  144. }
  145. public function getElementOptions()
  146. {
  147. $elements = array(
  148. 'foo' => 'text',
  149. array('text', 'bar', array('class' => 'foobar')),
  150. array(
  151. 'options' => array('class' => 'barbaz'),
  152. 'type' => 'text',
  153. 'name' => 'baz',
  154. ),
  155. 'bat' => array(
  156. 'options' => array('class' => 'bazbat'),
  157. 'type' => 'text',
  158. ),
  159. 'lol' => array(
  160. 'text',
  161. array('class' => 'lolcat'),
  162. )
  163. );
  164. return $elements;
  165. }
  166. public function testSetOptionsSetsElements()
  167. {
  168. $options = $this->getOptions();
  169. $options['elements'] = $this->getElementOptions();
  170. $this->form->setOptions($options);
  171. $this->assertTrue(isset($this->form->foo));
  172. $this->assertTrue($this->form->foo instanceof Zend_Form_Element_Text);
  173. $this->assertTrue(isset($this->form->bar));
  174. $this->assertTrue($this->form->bar instanceof Zend_Form_Element_Text);
  175. $this->assertEquals('foobar', $this->form->bar->class);
  176. $this->assertTrue(isset($this->form->baz));
  177. $this->assertTrue($this->form->baz instanceof Zend_Form_Element_Text);
  178. $this->assertEquals('barbaz', $this->form->baz->class);
  179. $this->assertTrue(isset($this->form->bat));
  180. $this->assertTrue($this->form->bat instanceof Zend_Form_Element_Text);
  181. $this->assertEquals('bazbat', $this->form->bat->class);
  182. $this->assertTrue(isset($this->form->lol));
  183. $this->assertTrue($this->form->lol instanceof Zend_Form_Element_Text);
  184. $this->assertEquals('lolcat', $this->form->lol->class);
  185. }
  186. public function testSetOptionsSetsDefaultValues()
  187. {
  188. $options = $this->getOptions();
  189. $options['defaults'] = array(
  190. 'bar' => 'barvalue',
  191. 'bat' => 'batvalue',
  192. );
  193. $options['elements'] = $this->getElementOptions();
  194. $this->form->setOptions($options);
  195. $this->assertEquals('barvalue', $this->form->bar->getValue());
  196. $this->assertEquals('batvalue', $this->form->bat->getValue());
  197. }
  198. public function testSetOptionsSetsArrayOfStringDecorators()
  199. {
  200. $this->_checkZf2794();
  201. $options = $this->getOptions();
  202. $options['decorators'] = array('label', 'errors');
  203. $this->form->setOptions($options);
  204. $this->assertFalse($this->form->getDecorator('form'));
  205. $decorator = $this->form->getDecorator('label');
  206. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Label);
  207. $decorator = $this->form->getDecorator('errors');
  208. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Errors);
  209. }
  210. public function testSetOptionsSetsArrayOfArrayDecorators()
  211. {
  212. $this->_checkZf2794();
  213. $options = $this->getOptions();
  214. $options['decorators'] = array(
  215. array('label', array('id' => 'mylabel')),
  216. array('errors', array('id' => 'errors')),
  217. );
  218. $this->form->setOptions($options);
  219. $this->assertFalse($this->form->getDecorator('form'));
  220. $decorator = $this->form->getDecorator('label');
  221. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Label);
  222. $options = $decorator->getOptions();
  223. $this->assertEquals('mylabel', $options['id']);
  224. $decorator = $this->form->getDecorator('errors');
  225. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Errors);
  226. $options = $decorator->getOptions();
  227. $this->assertEquals('errors', $options['id']);
  228. }
  229. public function testSetOptionsSetsArrayOfAssocArrayDecorators()
  230. {
  231. $this->_checkZf2794();
  232. $options = $this->getOptions();
  233. $options['decorators'] = array(
  234. array(
  235. 'options' => array('id' => 'mylabel'),
  236. 'decorator' => 'label',
  237. ),
  238. array(
  239. 'options' => array('id' => 'errors'),
  240. 'decorator' => 'errors',
  241. ),
  242. );
  243. $this->form->setOptions($options);
  244. $this->assertFalse($this->form->getDecorator('form'));
  245. $decorator = $this->form->getDecorator('label');
  246. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Label);
  247. $options = $decorator->getOptions();
  248. $this->assertEquals('mylabel', $options['id']);
  249. $decorator = $this->form->getDecorator('errors');
  250. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Errors);
  251. $options = $decorator->getOptions();
  252. $this->assertEquals('errors', $options['id']);
  253. }
  254. public function testSetOptionsSetsGlobalPrefixPaths()
  255. {
  256. $options = $this->getOptions();
  257. $options['prefixPath'] = array(
  258. 'prefix' => 'Zend_Foo',
  259. 'path' => 'Zend/Foo/'
  260. );
  261. $this->form->setOptions($options);
  262. foreach (array('element', 'decorator') as $type) {
  263. $loader = $this->form->getPluginLoader($type);
  264. $paths = $loader->getPaths('Zend_Foo_' . ucfirst($type));
  265. $this->assertTrue(is_array($paths), "Failed for type $type: " . var_export($paths, 1));
  266. $this->assertFalse(empty($paths));
  267. $this->assertContains('Foo', $paths[0]);
  268. }
  269. }
  270. public function testSetOptionsSetsIndividualPrefixPathsFromKeyedArrays()
  271. {
  272. $options = $this->getOptions();
  273. $options['prefixPath'] = array(
  274. 'element' => array('prefix' => 'Zend_Foo', 'path' => 'Zend/Foo/')
  275. );
  276. $this->form->setOptions($options);
  277. $loader = $this->form->getPluginLoader('element');
  278. $paths = $loader->getPaths('Zend_Foo');
  279. $this->assertTrue(is_array($paths));
  280. $this->assertFalse(empty($paths));
  281. $this->assertContains('Foo', $paths[0]);
  282. }
  283. public function testSetOptionsSetsIndividualPrefixPathsFromUnKeyedArrays()
  284. {
  285. $options = $this->getOptions();
  286. $options['prefixPath'] = array(
  287. array('type' => 'decorator', 'prefix' => 'Zend_Foo', 'path' => 'Zend/Foo/')
  288. );
  289. $this->form->setOptions($options);
  290. $loader = $this->form->getPluginLoader('decorator');
  291. $paths = $loader->getPaths('Zend_Foo');
  292. $this->assertTrue(is_array($paths));
  293. $this->assertFalse(empty($paths));
  294. $this->assertContains('Foo', $paths[0]);
  295. }
  296. public function testSetOptionsSetsDisplayGroups()
  297. {
  298. $options = $this->getOptions();
  299. $options['displayGroups'] = array(
  300. 'barbat' => array(array('bar', 'bat'), array('order' => 20)),
  301. array(array('foo', 'baz'), 'foobaz', array('order' => 10)),
  302. array(
  303. 'name' => 'ghiabc',
  304. 'elements' => array('ghi', 'abc'),
  305. 'options' => array('order' => 15),
  306. ),
  307. );
  308. $options['elements'] = array(
  309. 'foo' => 'text',
  310. 'bar' => 'text',
  311. 'baz' => 'text',
  312. 'bat' => 'text',
  313. 'abc' => 'text',
  314. 'ghi' => 'text',
  315. 'jkl' => 'text',
  316. 'mno' => 'text',
  317. );
  318. $this->form->setOptions($options);
  319. $this->assertTrue(isset($this->form->barbat));
  320. $elements = $this->form->barbat->getElements();
  321. $expected = array('bar', 'bat');
  322. $this->assertEquals($expected, array_keys($elements));
  323. $this->assertEquals(20, $this->form->barbat->getOrder());
  324. $this->assertTrue(isset($this->form->foobaz));
  325. $elements = $this->form->foobaz->getElements();
  326. $expected = array('foo', 'baz');
  327. $this->assertEquals($expected, array_keys($elements));
  328. $this->assertEquals(10, $this->form->foobaz->getOrder());
  329. $this->assertTrue(isset($this->form->ghiabc));
  330. $elements = $this->form->ghiabc->getElements();
  331. $expected = array('ghi', 'abc');
  332. $this->assertEquals($expected, array_keys($elements));
  333. $this->assertEquals(15, $this->form->ghiabc->getOrder());
  334. }
  335. /**
  336. * @group ZF-3250
  337. */
  338. public function testDisplayGroupOrderInConfigShouldNotMatter()
  339. {
  340. require_once 'Zend/Config/Xml.php';
  341. $config = new Zend_Config_Xml(dirname(__FILE__) . '/_files/config/zf3250.xml', 'sitearea', true);
  342. $form = new Zend_Form($config->test);
  343. // no assertions needed; throws error if order matters
  344. }
  345. /**
  346. * @group ZF-3112
  347. */
  348. public function testSetOptionsShouldCreateDisplayGroupsLast()
  349. {
  350. $options = array();
  351. $options['displayGroups'] = array(
  352. 'barbat' => array(array('bar', 'bat'), array('order' => 20)),
  353. array(array('foo', 'baz'), 'foobaz', array('order' => 10)),
  354. array(
  355. 'name' => 'ghiabc',
  356. 'elements' => array('ghi', 'abc'),
  357. 'options' => array('order' => 15),
  358. ),
  359. );
  360. $options = array_merge($options, $this->getOptions());
  361. $options['elements'] = array(
  362. 'foo' => 'text',
  363. 'bar' => 'text',
  364. 'baz' => 'text',
  365. 'bat' => 'text',
  366. 'abc' => 'text',
  367. 'ghi' => 'text',
  368. 'jkl' => 'text',
  369. 'mno' => 'text',
  370. );
  371. $this->form = new Zend_Form($options);
  372. $this->assertTrue(isset($this->form->barbat));
  373. $elements = $this->form->barbat->getElements();
  374. $expected = array('bar', 'bat');
  375. $this->assertEquals($expected, array_keys($elements));
  376. $this->assertEquals(20, $this->form->barbat->getOrder());
  377. $this->assertTrue(isset($this->form->foobaz));
  378. $elements = $this->form->foobaz->getElements();
  379. $expected = array('foo', 'baz');
  380. $this->assertEquals($expected, array_keys($elements));
  381. $this->assertEquals(10, $this->form->foobaz->getOrder());
  382. $this->assertTrue(isset($this->form->ghiabc));
  383. $elements = $this->form->ghiabc->getElements();
  384. $expected = array('ghi', 'abc');
  385. $this->assertEquals($expected, array_keys($elements));
  386. $this->assertEquals(15, $this->form->ghiabc->getOrder());
  387. }
  388. public function testSetConfigSetsObjectState()
  389. {
  390. $config = new Zend_Config($this->getOptions());
  391. $this->form->setConfig($config);
  392. $this->assertEquals('foo', $this->form->getName());
  393. $this->assertEquals('someform', $this->form->getAttrib('class'));
  394. $this->assertEquals('/foo/bar', $this->form->getAction());
  395. $this->assertEquals('put', $this->form->getMethod());
  396. }
  397. public function testCanSetObjectStateByPassingConfigObjectToConstructor()
  398. {
  399. $config = new Zend_Config($this->getOptions());
  400. $form = new Zend_Form($config);
  401. $this->assertEquals('foo', $form->getName());
  402. $this->assertEquals('someform', $form->getAttrib('class'));
  403. $this->assertEquals('/foo/bar', $form->getAction());
  404. $this->assertEquals('put', $form->getMethod());
  405. }
  406. // Attribs:
  407. public function testAttribsArrayInitiallyEmpty()
  408. {
  409. $attribs = $this->form->getAttribs();
  410. $this->assertTrue(is_array($attribs));
  411. $this->assertTrue(empty($attribs));
  412. }
  413. public function testRetrievingUndefinedAttribReturnsNull()
  414. {
  415. $this->assertNull($this->form->getAttrib('foo'));
  416. }
  417. public function testCanAddAndRetrieveSingleAttribs()
  418. {
  419. $this->testRetrievingUndefinedAttribReturnsNull();
  420. $this->form->setAttrib('foo', 'bar');
  421. $this->assertEquals('bar', $this->form->getAttrib('foo'));
  422. }
  423. public function testCanAddAndRetrieveMultipleAttribs()
  424. {
  425. $this->form->setAttrib('foo', 'bar');
  426. $this->assertEquals('bar', $this->form->getAttrib('foo'));
  427. $this->form->addAttribs(array(
  428. 'bar' => 'baz',
  429. 'baz' => 'bat',
  430. 'bat' => 'foo'
  431. ));
  432. $test = $this->form->getAttribs();
  433. $attribs = array(
  434. 'foo' => 'bar',
  435. 'bar' => 'baz',
  436. 'baz' => 'bat',
  437. 'bat' => 'foo'
  438. );
  439. $this->assertSame($attribs, $test);
  440. }
  441. public function testSetAttribsOverwritesExistingAttribs()
  442. {
  443. $this->testCanAddAndRetrieveMultipleAttribs();
  444. $array = array('bogus' => 'value', 'not' => 'real');
  445. $this->form->setAttribs($array);
  446. $this->assertSame($array, $this->form->getAttribs());
  447. }
  448. public function testCanRemoveSingleAttrib()
  449. {
  450. $this->testCanAddAndRetrieveSingleAttribs();
  451. $this->assertTrue($this->form->removeAttrib('foo'));
  452. $this->assertNull($this->form->getAttrib('foo'));
  453. }
  454. public function testRemoveAttribReturnsFalseIfAttribDoesNotExist()
  455. {
  456. $this->assertFalse($this->form->removeAttrib('foo'));
  457. }
  458. public function testCanClearAllAttribs()
  459. {
  460. $this->testCanAddAndRetrieveMultipleAttribs();
  461. $this->form->clearAttribs();
  462. $attribs = $this->form->getAttribs();
  463. $this->assertTrue(is_array($attribs));
  464. $this->assertTrue(empty($attribs));
  465. }
  466. public function testNameIsInitiallyNull()
  467. {
  468. $this->assertNull($this->form->getName());
  469. }
  470. public function testCanSetName()
  471. {
  472. $this->testNameIsInitiallyNull();
  473. $this->form->setName('foo');
  474. $this->assertEquals('foo', $this->form->getName());
  475. }
  476. public function testZeroAsNameIsAllowed()
  477. {
  478. try {
  479. $this->form->setName(0);
  480. $this->assertEquals(0, $this->form->getName());
  481. } catch (Zend_Form_Exception $e) {
  482. $this->fail('Should allow zero as form name');
  483. }
  484. }
  485. public function testSetNameNormalizesValueToContainOnlyValidVariableCharacters()
  486. {
  487. $this->form->setName('f%\o^&*)o\(%$b#@!.a}{;-,r');
  488. $this->assertEquals('foobar', $this->form->getName());
  489. try {
  490. $this->form->setName('%\^&*)\(%$#@!.}{;-,');
  491. $this->fail('Empty names should raise exception');
  492. } catch (Zend_Form_Exception $e) {
  493. $this->assertContains('Invalid name provided', $e->getMessage());
  494. }
  495. }
  496. public function testActionDefaultsToEmptyString()
  497. {
  498. $this->assertSame('', $this->form->getAction());
  499. }
  500. public function testCanSetAction()
  501. {
  502. $this->testActionDefaultsToEmptyString();
  503. $this->form->setAction('/foo/bar');
  504. $this->assertEquals('/foo/bar', $this->form->getAction());
  505. }
  506. /**
  507. * @group ZF-7067
  508. */
  509. public function testCanSetActionWithGetParams()
  510. {
  511. $this->testActionDefaultsToEmptyString();
  512. $this->form->setAction('/foo.php?bar')
  513. ->setView(new Zend_View);
  514. $html = $this->form->render();
  515. $this->assertContains('action="/foo.php?bar"', $html);
  516. $this->assertEquals('/foo.php?bar', $this->form->getAction());
  517. }
  518. public function testMethodDefaultsToPost()
  519. {
  520. $this->assertEquals('post', $this->form->getMethod());
  521. }
  522. public function testCanSetMethod()
  523. {
  524. $this->testMethodDefaultsToPost();
  525. $this->form->setMethod('get');
  526. $this->assertEquals('get', $this->form->getMethod());
  527. }
  528. public function testMethodLimitedToGetPostPutAndDelete()
  529. {
  530. foreach (array('get', 'post', 'put', 'delete') as $method) {
  531. $this->form->setMethod($method);
  532. $this->assertEquals($method, $this->form->getMethod());
  533. }
  534. try {
  535. $this->form->setMethod('bogus');
  536. $this->fail('Invalid method type should throw exception');
  537. } catch (Zend_Form_Exception $e) {
  538. $this->assertContains('invalid', $e->getMessage());
  539. }
  540. }
  541. public function testEnctypeDefaultsToUrlEncoded()
  542. {
  543. $this->assertEquals(Zend_Form::ENCTYPE_URLENCODED, $this->form->getEnctype());
  544. }
  545. public function testCanSetEnctype()
  546. {
  547. $this->testEnctypeDefaultsToUrlEncoded();
  548. $this->form->setEnctype(Zend_Form::ENCTYPE_MULTIPART);
  549. $this->assertEquals(Zend_Form::ENCTYPE_MULTIPART, $this->form->getEnctype());
  550. }
  551. public function testLegendInitiallyNull()
  552. {
  553. $this->assertNull($this->form->getLegend());
  554. }
  555. public function testCanSetLegend()
  556. {
  557. $this->testLegendInitiallyNull();
  558. $legend = "This is a legend";
  559. $this->form->setLegend($legend);
  560. $this->assertEquals($legend, $this->form->getLegend());
  561. }
  562. public function testDescriptionInitiallyNull()
  563. {
  564. $this->assertNull($this->form->getDescription());
  565. }
  566. public function testCanSetDescription()
  567. {
  568. $this->testDescriptionInitiallyNull();
  569. $description = "This is a description";
  570. $this->form->setDescription($description);
  571. $this->assertEquals($description, $this->form->getDescription());
  572. }
  573. // Plugin loaders
  574. public function testGetPluginLoaderRetrievesDefaultDecoratorPluginLoader()
  575. {
  576. $loader = $this->form->getPluginLoader('decorator');
  577. $this->assertTrue($loader instanceof Zend_Loader_PluginLoader);
  578. $paths = $loader->getPaths('Zend_Form_Decorator');
  579. $this->assertTrue(is_array($paths), var_export($loader, 1));
  580. $this->assertTrue(0 < count($paths));
  581. $this->assertContains('Form', $paths[0]);
  582. $this->assertContains('Decorator', $paths[0]);
  583. }
  584. public function testPassingInvalidTypeToSetPluginLoaderThrowsException()
  585. {
  586. $loader = new Zend_Loader_PluginLoader();
  587. try {
  588. $this->form->setPluginLoader($loader, 'foo');
  589. $this->fail('Invalid plugin loader type should raise exception');
  590. } catch (Zend_Form_Exception $e) {
  591. $this->assertContains('Invalid type', $e->getMessage());
  592. }
  593. }
  594. public function testPassingInvalidTypeToGetPluginLoaderThrowsException()
  595. {
  596. try {
  597. $this->form->getPluginLoader('foo');
  598. $this->fail('Invalid plugin loader type should raise exception');
  599. } catch (Zend_Form_Exception $e) {
  600. $this->assertContains('Invalid type', $e->getMessage());
  601. }
  602. }
  603. public function testCanSetCustomDecoratorPluginLoader()
  604. {
  605. $loader = new Zend_Loader_PluginLoader();
  606. $this->form->setPluginLoader($loader, 'decorator');
  607. $test = $this->form->getPluginLoader('decorator');
  608. $this->assertSame($loader, $test);
  609. }
  610. public function testPassingInvalidTypeToAddPrefixPathThrowsException()
  611. {
  612. try {
  613. $this->form->addPrefixPath('Zend_Foo', 'Zend/Foo/', 'foo');
  614. $this->fail('Passing invalid loader type to addPrefixPath() should raise exception');
  615. } catch (Zend_Form_Exception $e) {
  616. $this->assertContains('Invalid type', $e->getMessage());
  617. }
  618. }
  619. public function testCanAddDecoratorPluginLoaderPrefixPath()
  620. {
  621. $loader = $this->form->getPluginLoader('decorator');
  622. $this->form->addPrefixPath('Zend_Foo', 'Zend/Foo/', 'decorator');
  623. $paths = $loader->getPaths('Zend_Foo');
  624. $this->assertTrue(is_array($paths));
  625. $this->assertContains('Foo', $paths[0]);
  626. }
  627. public function testUpdatedDecoratorPrefixPathUsedForNewElements()
  628. {
  629. $loader = $this->form->getPluginLoader('decorator');
  630. $this->form->addPrefixPath('Zend_Foo', 'Zend/Foo/', 'decorator');
  631. $foo = new Zend_Form_Element_Text('foo');
  632. $this->form->addElement($foo);
  633. $loader = $foo->getPluginLoader('decorator');
  634. $paths = $loader->getPaths('Zend_Foo');
  635. $this->assertTrue(is_array($paths));
  636. $this->assertContains('Foo', $paths[0]);
  637. $this->form->addElement('text', 'bar');
  638. $bar = $this->form->bar;
  639. $loader = $bar->getPluginLoader('decorator');
  640. $paths = $loader->getPaths('Zend_Foo');
  641. $this->assertTrue(is_array($paths));
  642. $this->assertContains('Foo', $paths[0]);
  643. }
  644. public function testUpdatedDecoratorPrefixPathUsedForNewDisplayGroups()
  645. {
  646. $loader = $this->form->getPluginLoader('decorator');
  647. $this->form->addPrefixPath('Zend_Foo', 'Zend/Foo/', 'decorator');
  648. $this->setupElements();
  649. $foo = $this->form->foo;
  650. $loader = $foo->getPluginLoader('decorator');
  651. $paths = $loader->getPaths('Zend_Foo');
  652. $this->assertTrue(is_array($paths));
  653. $this->assertContains('Foo', $paths[0]);
  654. }
  655. public function testUpdatedPrefixPathUsedForNewSubForms()
  656. {
  657. $loader = $this->form->getPluginLoader('decorator');
  658. $this->form->addPrefixPath('Zend_Foo', 'Zend/Foo/', 'decorator');
  659. $this->setupSubForm();
  660. $loader = $this->form->sub->getPluginLoader('decorator');
  661. $paths = $loader->getPaths('Zend_Foo');
  662. $this->assertTrue(is_array($paths));
  663. $this->assertContains('Foo', $paths[0]);
  664. }
  665. public function testGetPluginLoaderRetrievesDefaultElementPluginLoader()
  666. {
  667. $loader = $this->form->getPluginLoader('element');
  668. $this->assertTrue($loader instanceof Zend_Loader_PluginLoader);
  669. $paths = $loader->getPaths('Zend_Form_Element');
  670. $this->assertTrue(is_array($paths), var_export($loader, 1));
  671. $this->assertTrue(0 < count($paths));
  672. $this->assertContains('Form', $paths[0]);
  673. $this->assertContains('Element', $paths[0]);
  674. }
  675. public function testCanSetCustomDecoratorElementLoader()
  676. {
  677. $loader = new Zend_Loader_PluginLoader();
  678. $this->form->setPluginLoader($loader, 'element');
  679. $test = $this->form->getPluginLoader('element');
  680. $this->assertSame($loader, $test);
  681. }
  682. public function testCanAddElementPluginLoaderPrefixPath()
  683. {
  684. $loader = $this->form->getPluginLoader('element');
  685. $this->form->addPrefixPath('Zend_Foo', 'Zend/Foo/', 'element');
  686. $paths = $loader->getPaths('Zend_Foo');
  687. $this->assertTrue(is_array($paths));
  688. $this->assertContains('Foo', $paths[0]);
  689. }
  690. public function testAddAllPluginLoaderPrefixPathsSimultaneously()
  691. {
  692. $decoratorLoader = new Zend_Loader_PluginLoader();
  693. $elementLoader = new Zend_Loader_PluginLoader();
  694. $this->form->setPluginLoader($decoratorLoader, 'decorator')
  695. ->setPluginLoader($elementLoader, 'element')
  696. ->addPrefixPath('Zend', 'Zend/');
  697. $paths = $decoratorLoader->getPaths('Zend_Decorator');
  698. $this->assertTrue(is_array($paths), var_export($paths, 1));
  699. $this->assertContains('Decorator', $paths[0]);
  700. $paths = $elementLoader->getPaths('Zend_Element');
  701. $this->assertTrue(is_array($paths), var_export($paths, 1));
  702. $this->assertContains('Element', $paths[0]);
  703. }
  704. // Elements:
  705. public function testCanAddAndRetrieveSingleElements()
  706. {
  707. $element = new Zend_Form_Element('foo');
  708. $this->form->addElement($element);
  709. $this->assertSame($element, $this->form->getElement('foo'));
  710. }
  711. public function testGetElementReturnsNullForUnregisteredElement()
  712. {
  713. $this->assertNull($this->form->getElement('foo'));
  714. }
  715. public function testCanAddAndRetrieveSingleElementsByStringType()
  716. {
  717. $this->form->addElement('text', 'foo');
  718. $element = $this->form->getElement('foo');
  719. $this->assertTrue($element instanceof Zend_Form_Element);
  720. $this->assertTrue($element instanceof Zend_Form_Element_Text);
  721. $this->assertEquals('foo', $element->getName());
  722. }
  723. public function testAddElementAsStringElementThrowsExceptionWhenNoNameProvided()
  724. {
  725. try {
  726. $this->form->addElement('text');
  727. $this->fail('Should not be able to specify string element type without name');
  728. } catch (Zend_Form_Exception $e) {
  729. $this->assertContains('must have', $e->getMessage());
  730. }
  731. }
  732. public function testCreateElementReturnsNewElement()
  733. {
  734. $element = $this->form->createElement('text', 'foo');
  735. $this->assertTrue($element instanceof Zend_Form_Element);
  736. }
  737. public function testCreateElementDoesNotAttachElementToForm()
  738. {
  739. $element = $this->form->createElement('text', 'foo');
  740. $this->assertTrue($element instanceof Zend_Form_Element);
  741. $this->assertNull($this->form->foo);
  742. }
  743. public function testCanAddAndRetrieveMultipleElements()
  744. {
  745. $this->form->addElements(array(
  746. 'foo' => 'text',
  747. array('text', 'bar'),
  748. array('text', 'baz', array('foo' => 'bar')),
  749. new Zend_Form_Element_Text('bat'),
  750. ));
  751. $elements = $this->form->getElements();
  752. $names = array('foo', 'bar', 'baz', 'bat');
  753. $this->assertEquals($names, array_keys($elements));
  754. $foo = $elements['foo'];
  755. $this->assertTrue($foo instanceof Zend_Form_Element_Text);
  756. $bar = $elements['bar'];
  757. $this->assertTrue($bar instanceof Zend_Form_Element_Text);
  758. $baz = $elements['baz'];
  759. $this->assertTrue($baz instanceof Zend_Form_Element_Text);
  760. $this->assertEquals('bar', $baz->foo, var_export($baz->getAttribs(), 1));
  761. $bat = $elements['bat'];
  762. $this->assertTrue($bat instanceof Zend_Form_Element_Text);
  763. }
  764. public function testSetElementsOverwritesExistingElements()
  765. {
  766. $this->testCanAddAndRetrieveMultipleElements();
  767. $this->form->setElements(array(
  768. 'bogus' => 'text'
  769. ));
  770. $elements = $this->form->getElements();
  771. $names = array('bogus');
  772. $this->assertEquals($names, array_keys($elements));
  773. }
  774. public function testCanRemoveSingleElement()
  775. {
  776. $this->testCanAddAndRetrieveMultipleElements();
  777. $this->assertTrue($this->form->removeElement('bar'));
  778. $this->assertNull($this->form->getElement('bar'));
  779. }
  780. public function testRemoveElementReturnsFalseWhenElementNotRegistered()
  781. {
  782. $this->assertFalse($this->form->removeElement('bogus'));
  783. }
  784. public function testCanClearAllElements()
  785. {
  786. $this->testCanAddAndRetrieveMultipleElements();
  787. $this->form->clearElements();
  788. $elements = $this->form->getElements();
  789. $this->assertTrue(is_array($elements));
  790. $this->assertTrue(empty($elements));
  791. }
  792. public function testGetValueReturnsNullForUndefinedElements()
  793. {
  794. $this->assertNull($this->form->getValue('foo'));
  795. }
  796. public function testCanSetElementDefaultValues()
  797. {
  798. $this->testCanAddAndRetrieveMultipleElements();
  799. $values = array(
  800. 'foo' => 'foovalue',
  801. 'bar' => 'barvalue',
  802. 'baz' => 'bazvalue',
  803. 'bat' => 'batvalue'
  804. );
  805. $this->form->setDefaults($values);
  806. $elements = $this->form->getElements();
  807. foreach (array_keys($values) as $name) {
  808. $this->assertEquals($name . 'value', $elements[$name]->getValue(), var_export($elements[$name], 1));
  809. }
  810. }
  811. public function testSettingElementDefaultsDoesNotSetElementValuesToNullIfNotInDefaultsArray()
  812. {
  813. $this->testCanAddAndRetrieveMultipleElements();
  814. $this->form->baz->setValue('testing');
  815. $this->form->bar->setValue('testing');
  816. $values = array(
  817. 'foo' => 'foovalue',
  818. 'bat' => 'batvalue'
  819. );
  820. $this->form->setDefaults($values);
  821. $this->assertEquals('foovalue', $this->form->foo->getValue());
  822. $this->assertEquals('batvalue', $this->form->bat->getValue());
  823. $this->assertNotNull($this->form->baz->getValue());
  824. $this->assertNotNull($this->form->bar->getValue());
  825. }
  826. public function testCanRetrieveSingleElementValue()
  827. {
  828. $this->form->addElement('text', 'foo', array('value' => 'foovalue'));
  829. $this->assertEquals('foovalue', $this->form->getValue('foo'));
  830. }
  831. public function testCanRetrieveAllElementValues()
  832. {
  833. $this->testCanAddAndRetrieveMultipleElements();
  834. $values = array(
  835. 'foo' => 'foovalue',
  836. 'bar' => 'barvalue',
  837. 'baz' => 'bazvalue',
  838. 'bat' => 'batvalue'
  839. );
  840. $this->form->setDefaults($values);
  841. $test = $this->form->getValues();
  842. $elements = $this->form->getElements();
  843. foreach (array_keys($values) as $name) {
  844. $this->assertEquals($values[$name], $test[$name]);
  845. }
  846. }
  847. public function testRetrievingAllElementValuesSkipsThoseFlaggedAsIgnore()
  848. {
  849. $this->form->addElements(array(
  850. 'foo' => 'text',
  851. 'bar' => 'text',
  852. 'baz' => 'text'
  853. ));
  854. $this->form->setDefaults(array(
  855. 'foo' => 'Foo Value',
  856. 'bar' => 'Bar Value',
  857. 'baz' => 'Baz Value',
  858. ));
  859. $this->form->bar->setIgnore(true);
  860. $test = $this->form->getValues();
  861. $this->assertFalse(array_key_exists('bar', $test));
  862. $this->assertTrue(array_key_exists('foo', $test));
  863. $this->assertTrue(array_key_exists('baz', $test));
  864. }
  865. public function testCanRetrieveSingleUnfilteredElementValue()
  866. {
  867. $foo = new Zend_Form_Element_Text('foo');
  868. $foo->addFilter('StringToUpper')
  869. ->setValue('foovalue');
  870. $this->form->addElement($foo);
  871. $this->assertEquals('FOOVALUE', $this->form->getValue('foo'));
  872. $this->assertEquals('foovalue', $this->form->getUnfilteredValue('foo'));
  873. }
  874. public function testCanRetrieveAllUnfilteredElementValues()
  875. {
  876. $foo = new Zend_Form_Element_Text('foo');
  877. $foo->addFilter('StringToUpper')
  878. ->setValue('foovalue');
  879. $bar = new Zend_Form_Element_Text('bar');
  880. $bar->addFilter('StringToUpper')
  881. ->setValue('barvalue');
  882. $this->form->addElements(array($foo, $bar));
  883. $values = $this->form->getValues();
  884. $unfiltered = $this->form->getUnfilteredValues();
  885. foreach (array('foo', 'bar') as $key) {
  886. $value = $key . 'value';
  887. $this->assertEquals(strtoupper($value), $values[$key]);
  888. $this->assertEquals($value, $unfiltered[$key]);
  889. }
  890. }
  891. public function testOverloadingElements()
  892. {
  893. $this->form->addElement('text', 'foo');
  894. $this->assertTrue(isset($this->form->foo));
  895. $element = $this->form->foo;
  896. $this->assertTrue($element instanceof Zend_Form_Element);
  897. unset($this->form->foo);
  898. $this->assertFalse(isset($this->form->foo));
  899. $bar = new Zend_Form_Element_Text('bar');
  900. $this->form->bar = $bar;
  901. $this->assertTrue(isset($this->form->bar));
  902. $element = $this->form->bar;
  903. $this->assertSame($bar, $element);
  904. }
  905. public function testOverloadingGetReturnsNullForUndefinedFormItems()
  906. {
  907. $this->assertNull($this->form->bogus);
  908. }
  909. public function testOverloadingSetThrowsExceptionForInvalidTypes()
  910. {
  911. try {
  912. $this->form->foo = true;
  913. $this->fail('Overloading should not allow scalars');
  914. } catch (Zend_Form_Exception $e) {
  915. $this->assertContains('Only form elements and groups may be overloaded', $e->getMessage());
  916. }
  917. try {
  918. $this->form->foo = new Zend_Config(array());
  919. $this->fail('Overloading should not allow arbitrary object types');
  920. } catch (Zend_Form_Exception $e) {
  921. $this->assertContains('Only form elements and groups may be overloaded', $e->getMessage());
  922. $this->assertContains('Zend_Config', $e->getMessage());
  923. }
  924. }
  925. public function testFormIsNotAnArrayByDefault()
  926. {
  927. $this->assertFalse($this->form->isArray());
  928. }
  929. public function testCanSetArrayFlag()
  930. {
  931. $this->testFormIsNotAnArrayByDefault();
  932. $this->form->setIsArray(true);
  933. $this->assertTrue($this->form->isArray());
  934. $this->form->setIsArray(false);
  935. $this->assertFalse($this->form->isArray());
  936. }
  937. public function testElementsBelongToReturnsFormNameWhenFormIsArray()
  938. {
  939. $this->form->setName('foo')
  940. ->setIsArray(true);
  941. $this->assertEquals('foo', $this->form->getElementsBelongTo());
  942. }
  943. public function testElementsInitiallyBelongToNoArrays()
  944. {
  945. $this->assertNull($this->form->getElementsBelongTo());
  946. }
  947. public function testCanSetArrayToWhichElementsBelong()
  948. {
  949. $this->testElementsInitiallyBelongToNoArrays();
  950. $this->form->setElementsBelongTo('foo');
  951. $this->assertEquals('foo', $this->form->getElementsBelongTo());
  952. }
  953. public function testSettingArrayToWhichElementsBelongSetsArrayFlag()
  954. {
  955. $this->testFormIsNotAnArrayByDefault();
  956. $this->testCanSetArrayToWhichElementsBelong();
  957. $this->assertTrue($this->form->isArray());
  958. }
  959. public function testArrayToWhichElementsBelongCanConsistOfValidVariableCharsOnly()
  960. {
  961. $this->testElementsInitiallyBelongToNoArrays();
  962. $this->form->setElementsBelongTo('f%\o^&*)o\(%$b#@!.a}{;-,r');
  963. $this->assertEquals('foobar', $this->form->getElementsBelongTo());
  964. }
  965. public function testSettingArrayToWhichElementsBelongEmptyClearsIt()
  966. {
  967. $this->testCanSetArrayToWhichElementsBelong();
  968. $this->form->setElementsBelongTo('');
  969. $this->assertNull($this->form->getElementsBelongTo());
  970. }
  971. public function testSettingArrayToWhichElementsBelongEmptySetsArrayFlagToFalse()
  972. {
  973. $this->testSettingArrayToWhichElementsBelongEmptyClearsIt();
  974. $this->assertFalse($this->form->isArray());
  975. }
  976. /**
  977. * @group ZF-6741
  978. */
  979. public function testUseIdForDdTagByDefault()
  980. {
  981. $this->form->addSubForm(new Zend_Form_SubForm(), 'bar')
  982. ->bar->addElement('text', 'foo');
  983. $html = $this->form->setView($this->getView())->render();
  984. $this->assertRegexp('/<dd.*?bar-foo.*?>/', $html);
  985. }
  986. public function testUseIdForDtTagByDefault()
  987. {
  988. $this->form->addSubForm(new Zend_Form_SubForm(), 'bar')
  989. ->bar->addElement('text', 'foo');
  990. $html = $this->form->setView($this->getView())->render();
  991. $this->assertRegexp('/<dt.*?bar-foo.*?>/', $html);
  992. }
  993. /**
  994. * @group ZF-3146
  995. */
  996. public function testSetElementsBelongToShouldApplyToBothExistingAndFutureElements()
  997. {
  998. $this->form->addElement('text', 'testBelongsTo');
  999. $this->form->setElementsBelongTo('foo');
  1000. $this->assertEquals('foo', $this->form->testBelongsTo->getBelongsTo(), 'Failed determining testBelongsTo belongs to array');
  1001. $this->setupElements();
  1002. foreach ($this->form->getElements() as $element) {
  1003. $message = sprintf('Failed determining element "%s" belongs to foo', $element->getName());
  1004. $this->assertEquals('foo', $element->getBelongsTo(), $message);
  1005. }
  1006. }
  1007. /**
  1008. * @group ZF-3742
  1009. */
  1010. public function testElementsInDisplayGroupsShouldInheritFormElementsBelongToSetting()
  1011. {
  1012. $subForm = new Zend_Form_SubForm();
  1013. $subForm->addElements(array(
  1014. new Zend_Form_Element_Text('foo'),
  1015. new Zend_Form_Element_Text('bar'),
  1016. new Zend_Form_Element_Text('baz'),
  1017. new Zend_Form_Element_Text('bat'),
  1018. ))
  1019. ->addDisplayGroup(array('bar', 'baz'), 'barbaz');
  1020. $this->form->addSubForm($subForm, 'sub')
  1021. ->setElementsBelongTo('myform')
  1022. ->setView(new Zend_View);
  1023. $html = $this->form->render();
  1024. foreach (array('foo', 'bar', 'baz', 'bat') as $test) {
  1025. $this->assertContains('id="myform-sub-' . $test . '"', $html);
  1026. $this->assertContains('name="myform[sub][' . $test . ']"', $html);
  1027. }
  1028. }
  1029. public function testIsValidWithOneLevelElementsBelongTo()
  1030. {
  1031. $this->form->addElement('text', 'test')->test
  1032. ->addValidator('Identical', false, array('Test Value'));
  1033. $this->form->setElementsBelongTo('foo');
  1034. $data = array(
  1035. 'foo' => array(
  1036. 'test' => 'Test Value',
  1037. ),
  1038. );
  1039. $this->assertTrue($this->form->isValid($data));
  1040. }
  1041. public function testIsValidWithMultiLevelElementsBelongTo()
  1042. {
  1043. $this->form->addElement('text', 'test')->test
  1044. ->addValidator('Identical', false, array('Test Value'));
  1045. $this->form->setElementsBelongTo('foo[bar][zot]');
  1046. $data = array(
  1047. 'foo' => array(
  1048. 'bar' => array(
  1049. 'zot' => array(
  1050. 'test' => 'Test Value',
  1051. ),
  1052. ),
  1053. ),
  1054. );
  1055. $this->assertTrue($this->form->isValid($data));
  1056. }
  1057. // Sub forms
  1058. public function testCanAddAndRetrieveSingleSubForm()
  1059. {
  1060. $subForm = new Zend_Form_SubForm;
  1061. $subForm->addElements(array('foo' => 'text', 'bar' => 'text'));
  1062. $this->form->addSubForm($subForm, 'page1');
  1063. $test = $this->form->getSubForm('page1');
  1064. $this->assertSame($subForm, $test);
  1065. }
  1066. public function testAddingSubFormSetsSubFormName()
  1067. {
  1068. $subForm = new Zend_Form_SubForm;
  1069. $subForm->addElements(array('foo' => 'text', 'bar' => 'text'));
  1070. $this->form->addSubForm($subForm, 'page1');
  1071. $this->assertEquals('page1', $subForm->getName());
  1072. }
  1073. public function testAddingSubFormResetsBelongsToWithDifferentSubFormName()
  1074. {
  1075. $subForm = new Zend_Form_SubForm;
  1076. $subForm->setName('quo')
  1077. ->addElement('text', 'foo');
  1078. $this->form->addSubForm($subForm, 'bar');
  1079. $this->assertEquals('bar', $subForm->foo->getBelongsTo());
  1080. }
  1081. public function testGetSubFormReturnsNullForUnregisteredSubForm()
  1082. {
  1083. $this->assertNull($this->form->getSubForm('foo'));
  1084. }
  1085. public function testCanAddAndRetrieveMultipleSubForms()
  1086. {
  1087. $page1 = new Zend_Form_SubForm();
  1088. $page2 = new Zend_Form_SubForm();
  1089. $page3 = new Zend_Form_SubForm();
  1090. $this->form->addSubForms(array(
  1091. 'page1' => $page1,
  1092. array($page2, 'page2'),
  1093. array($page3, 'page3', 3)
  1094. ));
  1095. $subforms = $this->form->getSubForms();
  1096. $keys = array('page1', 'page2', 'page3');
  1097. $this->assertEquals($keys, array_keys($subforms));
  1098. $this->assertSame($page1, $subforms['page1']);
  1099. $this->assertSame($page2, $subforms['page2']);
  1100. $this->assertSame($page3, $subforms['page3']);
  1101. }
  1102. public function testSetSubFormsOverwritesExistingSubForms()
  1103. {
  1104. $this->testCanAddAndRetrieveMultipleSubForms();
  1105. $foo = new Zend_Form_SubForm();
  1106. $this->form->setSubForms(array('foo' => $foo));
  1107. $subforms = $this->form->getSubForms();
  1108. $keys = array('foo');
  1109. $this->assertEquals($keys, array_keys($subforms));
  1110. $this->assertSame($foo, $subforms['foo']);
  1111. }
  1112. public function testCanRemoveSingleSubForm()
  1113. {
  1114. $this->testCanAddAndRetrieveMultipleSubForms();
  1115. $this->assertTrue($this->form->removeSubForm('page2'));
  1116. $this->assertNull($this->form->getSubForm('page2'));
  1117. }
  1118. public function testRemoveSubFormReturnsFalseForNonexistantSubForm()
  1119. {
  1120. $this->assertFalse($this->form->removeSubForm('foo'));
  1121. }
  1122. public function testCanClearAllSubForms()
  1123. {
  1124. $this->testCanAddAndRetrieveMultipleSubForms();
  1125. $this->form->clearSubForms();
  1126. $subforms = $this->form->getSubForms();
  1127. $this->assertTrue(is_array($subforms));
  1128. $this->assertTrue(empty($subforms));
  1129. }
  1130. public function testOverloadingSubForms()
  1131. {
  1132. $foo = new Zend_Form_SubForm;
  1133. $this->form->addSubForm($foo, 'foo');
  1134. $this->assertTrue(isset($this->form->foo));
  1135. $subform = $this->form->foo;
  1136. $this->assertSame($foo, $subform);
  1137. unset($this->form->foo);
  1138. $this->assertFalse(isset($this->form->foo));
  1139. $bar = new Zend_Form_SubForm();
  1140. $this->form->bar = $bar;
  1141. $this->assertTrue(isset($this->form->bar));
  1142. $subform = $this->form->bar;
  1143. $this->assertSame($bar, $subform);
  1144. }
  1145. public function testCanSetDefaultsForSubFormElementsFromForm()
  1146. {
  1147. $subForm = new Zend_Form_SubForm;
  1148. $subForm->addElements(array('foo' => 'text', 'bar' => 'text'));
  1149. $this->form->addSubForm($subForm, 'page1');
  1150. $data = array('foo' => 'foo value', 'bar' => 'bar value');
  1151. $this->form->setDefaults($data);
  1152. $this->assertEquals($data['foo'], $subForm->foo->getValue());
  1153. $this->assertEquals($data['bar'], $subForm->bar->getValue());
  1154. }
  1155. public function testCanSetDefaultsForSubFormElementsFromFormWithArray()
  1156. {
  1157. $subForm = new Zend_Form_SubForm;
  1158. $subForm->addElements(array('foo' => 'text', 'bar' => 'text'));
  1159. $this->form->addSubForm($subForm, 'page1');
  1160. $data = array( 'page1' => array(
  1161. 'foo' => 'foo value',
  1162. 'bar' => 'bar value'
  1163. ));
  1164. $this->form->setDefaults($data);
  1165. $this->assertEquals($data['page1']['foo'], $subForm->foo->getValue());
  1166. $this->assertEquals($data['page1']['bar'], $subForm->bar->getValue());
  1167. }
  1168. public function testGetValuesReturnsSubFormValues()
  1169. {
  1170. $subForm = new Zend_Form_SubForm;
  1171. $subForm->addElements(array('foo' => 'text', 'bar' => 'text'));
  1172. $subForm->foo->setValue('foo value');
  1173. $subForm->bar->setValue('bar value');
  1174. $this->form->addSubForm($subForm, 'page1');
  1175. $values = $this->form->getValues();
  1176. $this->assertTrue(isset($values['page1']));
  1177. $this->assertTrue(isset($values['page1']['foo']));
  1178. $this->assertTrue(isset($values['page1']['bar']));
  1179. $this->assertEquals($subForm->foo->getValue(), $values['page1']['foo']);
  1180. $this->assertEquals($subForm->bar->getValue(), $values['page1']['bar']);
  1181. }
  1182. public function testGetValuesReturnsSubFormValuesFromArrayToWhichElementsBelong()
  1183. {
  1184. $subForm = new Zend_Form_SubForm;
  1185. $subForm->addElements(array('foo' => 'text', 'bar' => 'text'))
  1186. ->setElementsBelongTo('subform');
  1187. $subForm->foo->setValue('foo value');
  1188. $subForm->bar->setValue('bar value');
  1189. $this->form->addSubForm($subForm, 'page1');
  1190. $values = $this->form->getValues();
  1191. $this->assertTrue(isset($values['subform']), var_export($values, 1));
  1192. $this->assertTrue(isset($values['subform']['foo']));
  1193. $this->assertTrue(isset($values['subform']['bar']));
  1194. $this->assertEquals($subForm->foo->getValue(), $values['subform']['foo']);
  1195. $this->assertEquals($subForm->bar->getValue(), $values['subform']['bar']);
  1196. }
  1197. public function testGetValuesReturnsNestedSubFormValuesFromArraysToWhichElementsBelong()
  1198. {
  1199. $form = new Zend_Form();
  1200. $form->setElementsBelongTo('foobar');
  1201. $form->addElement('text', 'firstName')
  1202. ->getElement('firstName')
  1203. ->setRequired(true);
  1204. $form->addElement('text', 'lastName')
  1205. ->getElement('lastName')
  1206. ->setRequired(true);
  1207. $subForm = new Zend_Form_SubForm();
  1208. $subForm->setElementsBelongTo('baz[quux]');
  1209. $subForm->addElement('text', 'email')
  1210. ->getElement('email')->setRequired(true);
  1211. $subSubForm = new Zend_Form_SubForm();
  1212. $subSubForm->setElementsBelongTo('bat');
  1213. $subSubForm->addElement('checkbox', 'home')
  1214. ->getElement('home')->setRequired(true);
  1215. $subForm->addSubForm($subSubForm, 'subSub');
  1216. $form->addSubForm($subForm, 'sub')
  1217. ->addElement('submit', 'save', array('value' => 'submit', 'ignore' => true));
  1218. $data = array('foobar' => array(
  1219. 'firstName' => 'Mabel',
  1220. 'lastName' => 'Cow',
  1221. 'baz' => array(
  1222. 'quux' => array(
  1223. 'email' => 'mabel@cow.org',
  1224. 'bat' => array(
  1225. 'home' => 1,
  1226. )
  1227. ),
  1228. )
  1229. ));
  1230. $this->assertTrue($form->isValid($data));
  1231. $values = $form->getValues();
  1232. $this->assertEquals($data, $values);
  1233. }
  1234. public function testGetValueCanReturnSubFormValues()
  1235. {
  1236. $subForm = new Zend_Form_SubForm;
  1237. $subForm->addElements(array('foo' => 'text', 'bar' => 'text'));
  1238. $subForm->foo->setValue('foo value');
  1239. $subForm->bar->setValue('bar value');
  1240. $this->form->addSubForm($subForm, 'page1');
  1241. $values = $this->form->getValue('page1');
  1242. $this->assertTrue(isset($values['foo']), var_export($values, 1));
  1243. $this->assertTrue(isset($values['bar']));
  1244. $this->assertEquals($subForm->foo->getValue(), $values['foo']);
  1245. $this->assertEquals($subForm->bar->getValue(), $values['bar']);
  1246. }
  1247. public function testGetValueCanReturnSubFormValuesFromArrayToWhichElementsBelong()
  1248. {
  1249. $subForm = new Zend_Form_SubForm;
  1250. $subForm->addElements(array('foo' => 'text', 'bar' => 'text'))
  1251. ->setElementsBelongTo('subform');
  1252. $subForm->foo->setValue('foo value');
  1253. $subForm->bar->setValue('bar value');
  1254. $this->form->addSubForm($subForm, 'page1');
  1255. $values = $this->form->getValue('subform');
  1256. $this->assertTrue(isset($values['foo']), var_export($values, 1));
  1257. $this->assertTrue(isset($values['bar']));
  1258. $this->assertEquals($subForm->foo->getValue(), $values['foo']);
  1259. $this->assertEquals($subForm->bar->getValue(), $values['bar']);
  1260. }
  1261. public function testIsValidCanValidateSubFormsWithArbitraryElementsBelong()
  1262. {
  1263. $subForm = new Zend_Form_SubForm();
  1264. $subForm->addElement('text', 'test')->test
  1265. ->setRequired(true)->addValidator('Identical', false, array('Test Value'));
  1266. $this->form->addSubForm($subForm, 'sub');
  1267. $this->form->setElementsBelongTo('foo[bar]');
  1268. $subForm->setElementsBelongTo('my[subform]');
  1269. $data = array(
  1270. 'foo' => array(
  1271. 'bar' => array(
  1272. 'my' => array(
  1273. 'subform' => array(
  1274. 'test' => 'Test Value',
  1275. ),
  1276. ),
  1277. ),
  1278. ),
  1279. );
  1280. $this->assertTrue($this->form->isValid($data));
  1281. }
  1282. public function testIsValidCanValidateNestedSubFormsWithArbitraryElementsBelong()
  1283. {
  1284. $subForm = new Zend_Form_SubForm();
  1285. $subForm->addElement('text', 'test1')->test1
  1286. ->setRequired(true)->addValidator('Identical', false, array('Test1 Value'));
  1287. $this->form->addSubForm($subForm, 'sub');
  1288. $subSubForm = new Zend_Form_SubForm();
  1289. $subSubForm->addElement('text', 'test2')->test2
  1290. ->setRequired(true)->addValidator('Identical', false, array('Test2 Value'));
  1291. $subForm->addSubForm($subSubForm, 'subSub');
  1292. $this->form->setElementsBelongTo('form[first]');
  1293. // Notice we skipped subForm, to mix manual and auto elementsBelongTo.
  1294. $subSubForm->setElementsBelongTo('subsubform[first]');
  1295. $data = array(
  1296. 'form' => array(
  1297. 'first' => array(
  1298. 'sub' => array(
  1299. 'test1' => 'Test1 Value',
  1300. 'subsubform' => array(
  1301. 'first' => array(
  1302. 'test2' => 'Test2 Value',
  1303. ),
  1304. ),
  1305. ),
  1306. ),
  1307. ),
  1308. );
  1309. $this->assertTrue($this->form->isValid($data));
  1310. }
  1311. /**
  1312. * @group ZF-9679
  1313. */
  1314. public function testIsValidDiscardsValidatedValues()
  1315. {
  1316. $this->form->addElement('text', 'foo');
  1317. $this->form->addSubForm(new Zend_Form_SubForm(), 'bar')
  1318. ->bar->addElement('text', 'foo')
  1319. ->foo->setAllowEmpty(true)
  1320. ->addValidator('Identical', true, '');
  1321. $this->assertTrue($this->form->isValid(array('foo' => 'foo Value')));
  1322. }
  1323. /**
  1324. * @group ZF-9666
  1325. */
  1326. public function testSetDefaultsDiscardsPopulatedValues()
  1327. {
  1328. $this->form->addElement('text', 'foo');
  1329. $this->form->addSubForm(new Zend_Form_SubForm(), 'bar')
  1330. ->bar->addElement('text', 'foo');
  1331. $this->form->populate(array('foo' => 'foo Value'));
  1332. $html = $this->form->setView($this->getView())
  1333. ->render();
  1334. $this->assertEquals(1, preg_match_all('/foo Value/', $html, $matches));
  1335. }
  1336. public function _setup9350()
  1337. {
  1338. $this->form->addSubForm(new Zend_Form_SubForm(), 'foo')
  1339. ->foo->setElementsBelongTo('foo[foo]') // foo[foo]
  1340. ->addSubForm(new Zend_Form_SubForm(), 'foo') // foo[foo][foo]
  1341. ->foo->setIsArray(false)
  1342. ->addElement('text', 'foo') // foo[foo][foo][foo]
  1343. ->foo->addValidator('Identical',
  1344. false,
  1345. array('foo Value'));
  1346. $this->form->foo->addSubForm(new Zend_Form_SubForm(), 'baz') // foo[foo][baz]
  1347. ->baz->setIsArray(false)
  1348. ->addSubForm(new Zend_Form_SubForm(), 'baz')
  1349. ->baz->setElementsBelongTo('baz[baz]') // foo[foo][baz][baz][baz]
  1350. ->addElement('text', 'baz') // foo[foo][baz][baz][baz][baz]
  1351. ->baz->addValidator('Identical',
  1352. false,
  1353. array('baz Value'));
  1354. // This is appending a different named SubForm and setting
  1355. // elementsBelongTo to a !isArray() Subform name from same level
  1356. $this->form->foo->addSubForm(new Zend_Form_SubForm(), 'quo')
  1357. ->quo->setElementsBelongTo('foo') // foo[foo][foo] !!!!
  1358. ->addElement('text', 'quo') // foo[foo][foo][quo]
  1359. ->quo->addValidator('Identical',
  1360. false,
  1361. array('quo Value'));
  1362. // This is setting elementsBelongTo point into the middle of
  1363. // a chain of another SubForms elementsBelongTo
  1364. $this->form->addSubForm(new Zend_Form_SubForm(), 'duh')
  1365. ->duh->setElementsBelongTo('foo[zoo]') // foo[zoo] !!!!
  1366. ->addElement('text', 'zoo') // foo[zoo][zoo]
  1367. ->zoo->addValidator('Identical',
  1368. false,
  1369. array('zoo Value'));
  1370. // This is !isArray SubForms Name equal to the last segment
  1371. // of another SubForms elementsBelongTo
  1372. $this->form->addSubForm(new Zend_Form_SubForm(), 'iek')
  1373. ->iek->setElementsBelongTo('foo') // foo !!!!
  1374. ->addSubForm(new Zend_Form_SubForm(), 'zoo') // foo[zoo] !!!!
  1375. ->zoo->setIsArray(false)
  1376. ->addElement('text', 'iek') // foo[zoo][iek]
  1377. ->iek->addValidator('Identical',
  1378. false,
  1379. array('iek Value'));
  1380. $data = array('valid' => array('foo' =>
  1381. array('foo' =>
  1382. array('foo' =>
  1383. array('foo' => 'foo Value',
  1384. 'quo' => 'quo Value'),
  1385. 'baz' =>
  1386. array('baz' =>
  1387. array('baz' =>
  1388. array('baz' => 'baz Value')))),
  1389. 'zoo' =>
  1390. array('zoo' => 'zoo Value',
  1391. 'iek' => 'iek Value'))),
  1392. 'invalid' => array('foo' =>
  1393. array('foo' =>
  1394. array('foo' =>
  1395. array('foo' => 'foo Invalid',
  1396. 'quo' => 'quo Value'),
  1397. 'baz' =>
  1398. array('baz' =>
  1399. array('baz' =>
  1400. array('baz' => 'baz Value')))),
  1401. 'zoo' =>
  1402. array('zoo' => 'zoo Value',
  1403. 'iek' => 'iek Invalid'))),
  1404. 'partial' => array('foo' =>
  1405. array('foo' =>
  1406. array('baz' =>
  1407. array('baz' =>
  1408. array('baz' =>
  1409. array('baz' => 'baz Value'))),
  1410. 'foo' =>
  1411. array('quo' => 'quo Value')),
  1412. 'zoo' =>
  1413. array('zoo' => 'zoo Value'))));
  1414. return $data;
  1415. }
  1416. public function testIsValidEqualSubFormAndElementName()
  1417. {
  1418. $data = $this->_setup9350();
  1419. $this->assertTrue($this->form->isValid($data['valid']));
  1420. }
  1421. public function testIsValidPartialEqualSubFormAndElementName()
  1422. {
  1423. $data = $this->_setup9350();
  1424. $this->assertTrue($this->form->isValidPartial($data['partial']));
  1425. }
  1426. public function testPopulateWithElementsBelongTo()
  1427. {
  1428. $data = $this->_setup9350();
  1429. $this->form->setView($this->getView())->populate($data['valid']);
  1430. $html = $this->form->render();
  1431. $this->assertRegexp('/value=.foo Value./', $html);
  1432. $this->assertRegexp('/value=.baz Value./', $html);
  1433. $this->assertRegexp('/value=.quo Value./', $html);
  1434. $this->assertRegexp('/value=.zoo Value./', $html);
  1435. $this->assertRegexp('/value=.iek Value./', $html);
  1436. }
  1437. public function testGetValidValuesWithElementsBelongTo()
  1438. {
  1439. $data = $this->_setup9350();
  1440. $this->assertSame($this->form->getValidValues($data['invalid']), $data['partial']);
  1441. }
  1442. public function testGetErrorsWithElementsBelongTo()
  1443. {
  1444. $data = $this->_setup9350();
  1445. $this->form->isValid($data['invalid']);
  1446. $errors = $this->form->getErrors();
  1447. $this->assertTrue(isset($errors['foo']['foo']['foo']['foo']));
  1448. $this->assertTrue(isset($errors['foo']['zoo']['iek']));
  1449. }
  1450. public function testGetValuesWithElementsBelongTo()
  1451. {
  1452. $data = $this->_setup9350();
  1453. $this->form->populate($data['valid']);
  1454. $this->assertSame($this->form->getValues(), $data['valid']);
  1455. }
  1456. public function testGetMessagesWithElementsBelongTo()
  1457. {
  1458. $data = $this->_setup9350();
  1459. $this->form->isValid($data['invalid']);
  1460. $msgs = $this->form->getMessages();
  1461. $this->assertTrue(isset($msgs['foo']['foo']['foo']['foo']));
  1462. $this->assertTrue(isset($msgs['foo']['zoo']['iek']));
  1463. }
  1464. public function _setup9401()
  1465. {
  1466. $sub0 = 0;
  1467. $this->form->addSubForm(new Zend_Form_SubForm(), $sub0)
  1468. ->$sub0->setElementsBelongTo('f[2]')
  1469. ->addElement('text', 'foo')
  1470. ->foo->addValidator('Identical',
  1471. false,
  1472. array('foo Value'));
  1473. $this->form->$sub0->addSubForm(new Zend_Form_SubForm(), $sub0)
  1474. ->$sub0->addElement('text', 'quo')
  1475. ->quo->addValidator('Identical',
  1476. false,
  1477. array('quo Value'));
  1478. $data = array('valid' => array('f' =>
  1479. array(2 =>
  1480. array('foo' => 'foo Value',
  1481. 0 =>
  1482. array('quo' => 'quo Value')))),
  1483. 'invalid' => array('f' =>
  1484. array(2 =>
  1485. array('foo' => 'foo Invalid',
  1486. 0 =>
  1487. array('quo' => 'quo Value')))),
  1488. 'partial' => array('f' =>
  1489. array(2 =>
  1490. array(0 =>
  1491. array('quo' => 'quo Value')))));
  1492. return $data;
  1493. }
  1494. public function testGetErrorsNumericalSubForms()
  1495. {
  1496. $data = $this->_setup9401();
  1497. $this->form->isValid($data['invalid']);
  1498. $err = $this->form->getErrors();
  1499. $this->assertTrue(is_array($err['f'][2]['foo']) && !empty($err['f'][2]['foo']));
  1500. }
  1501. public function testGetMessagesNumericalSubForms()
  1502. {
  1503. $data = $this->_setup9401();
  1504. $this->form->isValid($data['invalid']);
  1505. $msg = $this->form->getMessages();
  1506. $this->assertTrue(is_array($msg['f'][2]['foo']) && !empty($msg['f'][2]['foo']));
  1507. }
  1508. public function testGetValuesNumericalSubForms()
  1509. {
  1510. $data = $this->_setup9401();
  1511. $this->form->populate($data['valid']);
  1512. $this->assertEquals($this->form->getValues(), $data['valid']);
  1513. }
  1514. public function testGetValidValuesNumericalSubForms()
  1515. {
  1516. $data = $this->_setup9401();
  1517. $this->assertEquals($this->form->getValidValues($data['invalid']), $data['partial']);
  1518. }
  1519. public function _setup9607()
  1520. {
  1521. $this->form->addElement('text', 'foo')
  1522. ->foo->setBelongsTo('bar[quo]')
  1523. ->setRequired(true)
  1524. ->addValidator('Identical',
  1525. false,
  1526. 'foo Value');
  1527. $this->form->addElement('text', 'quo')
  1528. ->quo->setBelongsTo('bar[quo]')
  1529. ->addValidator('Identical',
  1530. false,
  1531. 'quo Value');
  1532. $data = array('valid' => array('bar' =>
  1533. array('quo' =>
  1534. array('foo' => 'foo Value',
  1535. 'quo' => 'quo Value'))),
  1536. 'invalid' => array('bar' =>
  1537. array('quo' =>
  1538. array('foo' => 'foo Invalid',
  1539. 'quo' => 'quo Value'))),
  1540. 'partial' => array('bar' =>
  1541. array('quo' =>
  1542. array('quo' => 'quo Value'))));
  1543. return $data;
  1544. }
  1545. public function testIsValidWithBelongsTo()
  1546. {
  1547. $data = $this->_setup9607();
  1548. $this->assertTrue($this->form->isValid($data['valid']));
  1549. }
  1550. public function testIsValidPartialWithBelongsTo()
  1551. {
  1552. $data = $this->_setup9607();
  1553. $this->assertTrue($this->form->isValidPartial($data['valid']));
  1554. $this->assertSame('foo Value', $this->form->foo->getValue());
  1555. }
  1556. public function testPopulateWithBelongsTo()
  1557. {
  1558. $data = $this->_setup9607();
  1559. $this->form->populate($data['valid']);
  1560. $this->assertSame('foo Value', $this->form->foo->getValue());
  1561. }
  1562. public function testGetValuesWithBelongsTo()
  1563. {
  1564. $data = $this->_setup9607();
  1565. $this->form->populate($data['valid']);
  1566. $this->assertSame($data['valid'], $this->form->getValues());
  1567. }
  1568. public function testGetValidValuesWithBelongsTo()
  1569. {
  1570. $data = $this->_setup9607();
  1571. $this->assertSame($data['partial'], $this->form->getValidValues($data['invalid']));
  1572. }
  1573. public function testZF9788_NumericArrayIndex()
  1574. {
  1575. $s = 2;
  1576. $e = 4;
  1577. $this->form->setName('f')
  1578. ->setIsArray(true)
  1579. ->addElement('text', (string)$e)
  1580. ->$e->setRequired(true);
  1581. $this->form->addSubForm(new Zend_Form_SubForm(), $s)
  1582. ->$s->addElement('text', (string)$e)
  1583. ->$e->setRequired(true);
  1584. $valid = array('f' => array($e => 1,
  1585. $s => array($e => 1)));
  1586. $this->form->populate($valid);
  1587. $this->assertEquals($valid, $this->form->getValues());
  1588. $vv = $this->form->getValidValues(array('f' => array($e => 1,
  1589. $s => array($e => 1))));
  1590. $this->assertEquals($valid, $vv);
  1591. $this->form->isValid(array());
  1592. $err = $this->form->getErrors();
  1593. $msg = $this->form->getMessages();
  1594. $this->assertTrue(is_array($err['f'][$e]) && is_array($err['f'][$s][$e]));
  1595. $this->assertTrue(is_array($msg['f'][$e]) && is_array($msg['f'][$s][$e]));
  1596. }
  1597. // Display groups
  1598. public function testCanAddAndRetrieveSingleDisplayGroups()
  1599. {
  1600. $this->testCanAddAndRetrieveMultipleElements();
  1601. $this->form->addDisplayGroup(array('bar', 'bat'), 'barbat');
  1602. $group = $this->form->getDisplayGroup('barbat');
  1603. $this->assertTrue($group instanceof Zend_Form_DisplayGroup);
  1604. $elements = $group->getElements();
  1605. $expected = array('bar' => $this->form->bar, 'bat' => $this->form->bat);
  1606. $this->assertEquals($expected, $elements);
  1607. }
  1608. public function testDisplayGroupsMustContainAtLeastOneElement()
  1609. {
  1610. try {
  1611. $this->form->addDisplayGroup(array(), 'foo');
  1612. $this->fail('Empty display group should raise exception');
  1613. } catch (Zend_Form_Exception $e) {
  1614. $this->assertContains('No valid elements', $e->getMessage());
  1615. }
  1616. }
  1617. public function testCanAddAndRetrieveMultipleDisplayGroups()
  1618. {
  1619. $this->testCanAddAndRetrieveMultipleElements();
  1620. $this->form->addDisplayGroups(array(
  1621. array(array('bar', 'bat'), 'barbat'),
  1622. 'foobaz' => array('baz', 'foo')
  1623. ));
  1624. $groups = $this->form->getDisplayGroups();
  1625. $expected = array(
  1626. 'barbat' => array('bar' => $this->form->bar, 'bat' => $this->form->bat),
  1627. 'foobaz' => array('baz' => $this->form->baz, 'foo' => $this->form->foo),
  1628. );
  1629. foreach ($groups as $group) {
  1630. $this->assertTrue($group instanceof Zend_Form_DisplayGroup);
  1631. }
  1632. $this->assertEquals($expected['barbat'], $groups['barbat']->getElements());
  1633. $this->assertEquals($expected['foobaz'], $groups['foobaz']->getElements());
  1634. }
  1635. public function testSetDisplayGroupsOverwritesExistingDisplayGroups()
  1636. {
  1637. $this->testCanAddAndRetrieveMultipleDisplayGroups();
  1638. $this->form->setDisplayGroups(array('foobar' => array('bar', 'foo')));
  1639. $groups = $this->form->getDisplayGroups();
  1640. $expected = array('bar' => $this->form->bar, 'foo' => $this->form->foo);
  1641. $this->assertEquals(1, count($groups));
  1642. $this->assertTrue(isset($groups['foobar']));
  1643. $this->assertEquals($expected, $groups['foobar']->getElements());
  1644. }
  1645. public function testCanRemoveSingleDisplayGroup()
  1646. {
  1647. $this->testCanAddAndRetrieveMultipleDisplayGroups();
  1648. $this->assertTrue($this->form->removeDisplayGroup('barbat'));
  1649. $this->assertNull($this->form->getDisplayGroup('barbat'));
  1650. }
  1651. public function testRemoveDisplayGroupReturnsFalseForNonexistantGroup()
  1652. {
  1653. $this->assertFalse($this->form->removeDisplayGroup('bogus'));
  1654. }
  1655. public function testCanClearAllDisplayGroups()
  1656. {
  1657. $this->testCanAddAndRetrieveMultipleDisplayGroups();
  1658. $this->form->clearDisplayGroups();
  1659. $groups = $this->form->getDisplayGroups();
  1660. $this->assertTrue(is_array($groups));
  1661. $this->assertTrue(empty($groups));
  1662. }
  1663. public function testOverloadingDisplayGroups()
  1664. {
  1665. $this->testCanAddAndRetrieveMultipleElements();
  1666. $this->form->addDisplayGroup(array('foo', 'bar'), 'foobar');
  1667. $this->assertTrue(isset($this->form->foobar));
  1668. $group = $this->form->foobar;
  1669. $expected = array('foo' => $this->form->foo, 'bar' => $this->form->bar);
  1670. $this->assertEquals($expected, $group->getElements());
  1671. unset($this->form->foobar);
  1672. $this->assertFalse(isset($this->form->foobar));
  1673. $this->form->barbaz = array('bar', 'baz');
  1674. $this->assertTrue(isset($this->form->barbaz));
  1675. $group = $this->form->barbaz;
  1676. $expected = array('bar' => $this->form->bar, 'baz' => $this->form->baz);
  1677. $this->assertSame($expected, $group->getElements());
  1678. }
  1679. public function testDefaultDisplayGroupClassExists()
  1680. {
  1681. $this->assertEquals('Zend_Form_DisplayGroup', $this->form->getDefaultDisplayGroupClass());
  1682. }
  1683. public function testCanSetDefaultDisplayGroupClass()
  1684. {
  1685. $this->testDefaultDisplayGroupClassExists();
  1686. $this->form->setDefaultDisplayGroupClass('Zend_Form_FormTest_DisplayGroup');
  1687. $this->assertEquals('Zend_Form_FormTest_DisplayGroup', $this->form->getDefaultDisplayGroupClass());
  1688. }
  1689. public function testDefaultDisplayGroupClassUsedForNewDisplayGroups()
  1690. {
  1691. $this->form->setDefaultDisplayGroupClass('Zend_Form_FormTest_DisplayGroup');
  1692. $this->setupElements();
  1693. $this->form->addDisplayGroup(array('foo', 'bar'), 'foobar');
  1694. $displayGroup = $this->form->getDisplayGroup('foobar');
  1695. $this->assertTrue($displayGroup instanceof Zend_Form_FormTest_DisplayGroup);
  1696. }
  1697. public function testCanPassDisplayGroupClassWhenAddingDisplayGroup()
  1698. {
  1699. $this->setupElements();
  1700. $this->form->addDisplayGroup(array('foo', 'bar'), 'foobar', array('displayGroupClass' => 'Zend_Form_FormTest_DisplayGroup'));
  1701. $this->assertTrue($this->form->foobar instanceof Zend_Form_FormTest_DisplayGroup);
  1702. }
  1703. /**
  1704. * @group ZF-3254
  1705. */
  1706. public function testAddingDisplayGroupShouldPassOptions()
  1707. {
  1708. $this->testCanAddAndRetrieveMultipleElements();
  1709. $this->form->addDisplayGroup(array('bar', 'bat'), 'barbat', array('disableLoadDefaultDecorators' => true));
  1710. $group = $this->form->getDisplayGroup('barbat');
  1711. $this->assertTrue($group instanceof Zend_Form_DisplayGroup);
  1712. $decorators = $group->getDecorators();
  1713. $this->assertTrue(is_array($decorators));
  1714. $this->assertTrue(empty($decorators));
  1715. }
  1716. // Processing
  1717. public function testPopulateProxiesToSetDefaults()
  1718. {
  1719. $this->testCanAddAndRetrieveMultipleElements();
  1720. $values = array(
  1721. 'foo' => 'foovalue',
  1722. 'bar' => 'barvalue',
  1723. 'baz' => 'bazvalue',
  1724. 'bat' => 'batvalue'
  1725. );
  1726. $this->form->populate($values);
  1727. $test = $this->form->getValues();
  1728. $elements = $this->form->getElements();
  1729. foreach (array_keys($values) as $name) {
  1730. $this->assertEquals($values[$name], $test[$name]);
  1731. }
  1732. }
  1733. public function setupElements()
  1734. {
  1735. $foo = new Zend_Form_Element_Text('foo');
  1736. $foo->addValidator('NotEmpty')
  1737. ->addValidator('Alpha');
  1738. $bar = new Zend_Form_Element_Text('bar');
  1739. $bar->addValidator('NotEmpty')
  1740. ->addValidator('Digits');
  1741. $baz = new Zend_Form_Element_Text('baz');
  1742. $baz->addValidator('NotEmpty')
  1743. ->addValidator('Alnum');
  1744. $this->form->addElements(array($foo, $bar, $baz));
  1745. $this->elementValues = array(
  1746. 'foo' => 'fooBarBAZ',
  1747. 'bar' => '123456789',
  1748. 'baz' => 'foo123BAR',
  1749. );
  1750. }
  1751. public function testIsValidShouldThrowExceptionWithNonArrayArgument()
  1752. {
  1753. try {
  1754. $this->form->isValid(true);
  1755. $this->fail('isValid() should raise exception with non-array argument');
  1756. } catch (Zend_Form_Exception $e) {
  1757. $this->assertContains('expects an array', $e->getMessage());
  1758. }
  1759. }
  1760. public function testCanValidateFullFormContainingOnlyElements()
  1761. {
  1762. $this->_checkZf2794();
  1763. $this->setupElements();
  1764. $this->assertTrue($this->form->isValid($this->elementValues));
  1765. $values = array(
  1766. 'foo' => '12345',
  1767. 'bar' => 'abc',
  1768. 'baz' => 'abc-123'
  1769. );
  1770. $this->assertFalse($this->form->isValid($values));
  1771. $validator = $this->form->foo->getValidator('alpha');
  1772. $this->assertEquals('12345', $validator->value);
  1773. $validator = $this->form->bar->getValidator('digits');
  1774. $this->assertEquals('abc', $validator->value);
  1775. $validator = $this->form->baz->getValidator('alnum');
  1776. $this->assertEquals('abc-123', $validator->value);
  1777. }
  1778. public function testValidationTakesElementRequiredFlagsIntoAccount()
  1779. {
  1780. $this->_checkZf2794();
  1781. $this->setupElements();
  1782. $this->assertTrue($this->form->isValid(array()));
  1783. $this->form->getElement('foo')->setRequired(true);
  1784. $this->assertTrue($this->form->isValid(array(
  1785. 'foo' => 'abc',
  1786. 'baz' => 'abc123'
  1787. )));
  1788. $this->assertFalse($this->form->isValid(array(
  1789. 'baz' => 'abc123'
  1790. )));
  1791. }
  1792. public function testCanValidatePartialFormContainingOnlyElements()
  1793. {
  1794. $this->_checkZf2794();
  1795. $this->setupElements();
  1796. $this->form->getElement('foo')->setRequired(true);
  1797. $this->form->getElement('bar')->setRequired(true);
  1798. $this->form->getElement('baz')->setRequired(true);
  1799. $this->assertTrue($this->form->isValidPartial(array(
  1800. 'foo' => 'abc',
  1801. 'baz' => 'abc123'
  1802. )));
  1803. $this->assertFalse($this->form->isValidPartial(array(
  1804. 'foo' => '123',
  1805. 'baz' => 'abc-123'
  1806. )));
  1807. }
  1808. public function setupSubForm()
  1809. {
  1810. $subForm = new Zend_Form_SubForm();
  1811. $foo = new Zend_Form_Element_Text('subfoo');
  1812. $foo->addValidators(array('NotEmpty', 'Alpha'))->setRequired(true);
  1813. $bar = new Zend_Form_Element_Text('subbar');
  1814. $bar->addValidators(array('NotEmpty', 'Digits'));
  1815. $baz = new Zend_Form_Element_Text('subbaz');
  1816. $baz->addValidators(array('NotEmpty', 'Alnum'))->setRequired(true);
  1817. $subForm->addElements(array($foo, $bar, $baz));
  1818. $this->form->addSubForm($subForm, 'sub');
  1819. }
  1820. public function testFullDataArrayUsedToValidateSubFormByDefault()
  1821. {
  1822. $this->_checkZf2794();
  1823. $this->setupElements();
  1824. $this->setupSubForm();
  1825. $data = array(
  1826. 'foo' => 'abcdef',
  1827. 'bar' => '123456',
  1828. 'baz' => '123abc',
  1829. 'subfoo' => 'abcdef',
  1830. 'subbar' => '123456',
  1831. 'subbaz' => '123abc',
  1832. );
  1833. $this->assertTrue($this->form->isValid($data));
  1834. $data = array(
  1835. 'foo' => 'abcdef',
  1836. 'bar' => '123456',
  1837. 'baz' => '123abc',
  1838. 'subfoo' => '123',
  1839. 'subbar' => 'abc',
  1840. 'subbaz' => '123-abc',
  1841. );
  1842. $this->assertFalse($this->form->isValid($data));
  1843. $data = array(
  1844. 'foo' => 'abcdef',
  1845. 'bar' => '123456',
  1846. 'baz' => '123abc',
  1847. 'subfoo' => 'abc',
  1848. 'subbaz' => '123abc',
  1849. );
  1850. $this->assertTrue($this->form->isValid($data));
  1851. $data = array(
  1852. 'foo' => 'abcdef',
  1853. 'bar' => '123456',
  1854. 'baz' => '123abc',
  1855. 'subbar' => '123',
  1856. 'subbaz' => '123abc',
  1857. );
  1858. $this->assertFalse($this->form->isValid($data));
  1859. }
  1860. public function testDataKeyWithSameNameAsSubFormIsUsedForValidatingSubForm()
  1861. {
  1862. $this->_checkZf2794();
  1863. $this->setupElements();
  1864. $this->setupSubForm();
  1865. $data = array(
  1866. 'foo' => 'abcdef',
  1867. 'bar' => '123456',
  1868. 'baz' => '123abc',
  1869. 'sub' => array(
  1870. 'subfoo' => 'abcdef',
  1871. 'subbar' => '123456',
  1872. 'subbaz' => '123abc',
  1873. ),
  1874. );
  1875. $this->assertTrue($this->form->isValid($data));
  1876. $data = array(
  1877. 'foo' => 'abcdef',
  1878. 'bar' => '123456',
  1879. 'baz' => '123abc',
  1880. 'sub' => array(
  1881. 'subfoo' => '123',
  1882. 'subbar' => 'abc',
  1883. 'subbaz' => '123-abc',
  1884. )
  1885. );
  1886. $this->assertFalse($this->form->isValid($data));
  1887. $data = array(
  1888. 'foo' => 'abcdef',
  1889. 'bar' => '123456',
  1890. 'baz' => '123abc',
  1891. 'sub' => array(
  1892. 'subfoo' => 'abc',
  1893. 'subbaz' => '123abc',
  1894. )
  1895. );
  1896. $this->assertTrue($this->form->isValid($data));
  1897. $data = array(
  1898. 'foo' => 'abcdef',
  1899. 'bar' => '123456',
  1900. 'baz' => '123abc',
  1901. 'sub' => array(
  1902. 'subbar' => '123',
  1903. 'subbaz' => '123abc',
  1904. )
  1905. );
  1906. $this->assertFalse($this->form->isValid($data));
  1907. }
  1908. public function testCanValidateNestedFormsWithElementsBelongingToArrays()
  1909. {
  1910. $form = new Zend_Form();
  1911. $form->setElementsBelongTo('foobar');
  1912. $form->addElement('text', 'firstName')
  1913. ->getElement('firstName')
  1914. ->setRequired(true);
  1915. $form->addElement('text', 'lastName')
  1916. ->getElement('lastName')
  1917. ->setRequired(true);
  1918. $subForm = new Zend_Form_SubForm();
  1919. $subForm->setElementsBelongTo('baz');
  1920. $subForm->addElement('text', 'email')
  1921. ->getElement('email')->setRequired(true);
  1922. $subSubForm = new Zend_Form_SubForm();
  1923. $subSubForm->setElementsBelongTo('bat');
  1924. $subSubForm->addElement('checkbox', 'home')
  1925. ->getElement('home')->setRequired(true);
  1926. $subForm->addSubForm($subSubForm, 'subSub');
  1927. $form->addSubForm($subForm, 'sub')
  1928. ->addElement('submit', 'save', array('value' => 'submit'));
  1929. $data = array('foobar' => array(
  1930. 'firstName' => 'Mabel',
  1931. 'lastName' => 'Cow',
  1932. 'baz' => array(
  1933. 'email' => 'mabel@cow.org',
  1934. 'bat' => array(
  1935. 'home' => 1,
  1936. )
  1937. )
  1938. ));
  1939. $this->assertTrue($form->isValid($data));
  1940. $this->assertEquals('Mabel', $form->firstName->getValue());
  1941. $this->assertEquals('Cow', $form->lastName->getValue());
  1942. $this->assertEquals('mabel@cow.org', $form->sub->email->getValue());
  1943. $this->assertEquals(1, $form->sub->subSub->home->getValue());
  1944. }
  1945. public function testCanValidatePartialFormContainingSubForms()
  1946. {
  1947. $this->_checkZf2794();
  1948. $this->setupElements();
  1949. $this->setupSubForm();
  1950. $data = array(
  1951. 'subfoo' => 'abcdef',
  1952. 'subbar' => '123456',
  1953. );
  1954. $this->assertTrue($this->form->isValidPartial($data));
  1955. $data = array(
  1956. 'foo' => 'abcdef',
  1957. 'baz' => '123abc',
  1958. 'sub' => array(
  1959. 'subbar' => '123',
  1960. )
  1961. );
  1962. $this->assertTrue($this->form->isValidPartial($data));
  1963. $data = array(
  1964. 'foo' => 'abcdef',
  1965. 'bar' => '123456',
  1966. 'baz' => '123abc',
  1967. 'sub' => array(
  1968. 'subfoo' => '123',
  1969. )
  1970. );
  1971. $this->assertFalse($this->form->isValidPartial($data));
  1972. }
  1973. public function testCanValidatePartialNestedFormsWithElementsBelongingToArrays()
  1974. {
  1975. $this->_checkZf2794();
  1976. $form = new Zend_Form();
  1977. $form->setElementsBelongTo('foobar');
  1978. $form->addElement('text', 'firstName')
  1979. ->getElement('firstName')
  1980. ->setRequired(false);
  1981. $form->addElement('text', 'lastName')
  1982. ->getElement('lastName')
  1983. ->setRequired(true);
  1984. $subForm = new Zend_Form_SubForm();
  1985. $subForm->setElementsBelongTo('baz');
  1986. $subForm->addElement('text', 'email')
  1987. ->getElement('email')
  1988. ->setRequired(true)
  1989. ->addValidator('NotEmpty');
  1990. $subSubForm = new Zend_Form_SubForm();
  1991. $subSubForm->setElementsBelongTo('bat');
  1992. $subSubForm->addElement('checkbox', 'home')
  1993. ->getElement('home')
  1994. ->setRequired(true)
  1995. ->addValidator('InArray', false, array(array('1')));
  1996. $subForm->addSubForm($subSubForm, 'subSub');
  1997. $form->addSubForm($subForm, 'sub')
  1998. ->addElement('submit', 'save', array('value' => 'submit'));
  1999. $data = array('foobar' => array(
  2000. 'lastName' => 'Cow',
  2001. ));
  2002. $this->assertTrue($form->isValidPartial($data));
  2003. $this->assertEquals('Cow', $form->lastName->getValue());
  2004. $firstName = $form->firstName->getValue();
  2005. $email = $form->sub->email->getValue();
  2006. $home = $form->sub->subSub->home->getValue();
  2007. $this->assertTrue(empty($firstName));
  2008. $this->assertTrue(empty($email));
  2009. $this->assertTrue(empty($home));
  2010. $form->sub->subSub->home->addValidator('StringLength', false, array(4, 6));
  2011. $data['foobar']['baz'] = array('bat' => array('home' => 'ab'));
  2012. $this->assertFalse($form->isValidPartial($data), var_export($data, 1));
  2013. $this->assertEquals('0', $form->sub->subSub->home->getValue());
  2014. $messages = $form->getMessages();
  2015. $this->assertFalse(empty($messages));
  2016. $this->assertTrue(isset($messages['foobar']['baz']['bat']['home']), var_export($messages, 1));
  2017. $this->assertTrue(isset($messages['foobar']['baz']['bat']['home']['notInArray']), var_export($messages, 1));
  2018. }
  2019. public function testCanValidatePartialNestedFormsWithMultiLevelElementsBelongingToArrays()
  2020. {
  2021. $this->_checkZf2794();
  2022. $form = new Zend_Form();
  2023. $form->setElementsBelongTo('foo[bar]');
  2024. $form->addElement('text', 'firstName')
  2025. ->getElement('firstName')
  2026. ->setRequired(false);
  2027. $form->addElement('text', 'lastName')
  2028. ->getElement('lastName')
  2029. ->setRequired(true);
  2030. $subForm = new Zend_Form_SubForm();
  2031. $subForm->setElementsBelongTo('baz');
  2032. $subForm->addElement('text', 'email')
  2033. ->getElement('email')
  2034. ->setRequired(true)
  2035. ->addValidator('NotEmpty');
  2036. $subSubForm = new Zend_Form_SubForm();
  2037. $subSubForm->setElementsBelongTo('bat[quux]');
  2038. $subSubForm->addElement('checkbox', 'home')
  2039. ->getElement('home')
  2040. ->setRequired(true)
  2041. ->addValidator('InArray', false, array(array('1')));
  2042. $subForm->addSubForm($subSubForm, 'subSub');
  2043. $form->addSubForm($subForm, 'sub')
  2044. ->addElement('submit', 'save', array('value' => 'submit'));
  2045. $data = array('foo' => array(
  2046. 'bar' => array(
  2047. 'lastName' => 'Cow',
  2048. ),
  2049. ));
  2050. $this->assertTrue($form->isValidPartial($data));
  2051. $this->assertEquals('Cow', $form->lastName->getValue());
  2052. $firstName = $form->firstName->getValue();
  2053. $email = $form->sub->email->getValue();
  2054. $home = $form->sub->subSub->home->getValue();
  2055. $this->assertTrue(empty($firstName));
  2056. $this->assertTrue(empty($email));
  2057. $this->assertTrue(empty($home));
  2058. $form->sub->subSub->home->addValidator('StringLength', false, array(4, 6));
  2059. $data['foo']['bar']['baz'] = array('bat' => array('quux' => array('home' => 'ab')));
  2060. $this->assertFalse($form->isValidPartial($data), var_export($data, 1));
  2061. $this->assertEquals('0', $form->sub->subSub->home->getValue());
  2062. }
  2063. public function testCanGetMessagesOfNestedFormsWithMultiLevelElementsBelongingToArrays()
  2064. {
  2065. $this->_checkZf2794();
  2066. $form = new Zend_Form();
  2067. $form->setElementsBelongTo('foo[bar]');
  2068. $form->addElement('text', 'firstName')
  2069. ->getElement('firstName')
  2070. ->setRequired(false);
  2071. $form->addElement('text', 'lastName')
  2072. ->getElement('lastName')
  2073. ->setRequired(true);
  2074. $subForm = new Zend_Form_SubForm();
  2075. $subForm->setElementsBelongTo('baz');
  2076. $subForm->addElement('text', 'email')
  2077. ->getElement('email')
  2078. ->setRequired(true)
  2079. ->addValidator('NotEmpty');
  2080. $subSubForm = new Zend_Form_SubForm();
  2081. $subSubForm->setElementsBelongTo('bat[quux]');
  2082. $subSubForm->addElement('checkbox', 'home')
  2083. ->getElement('home')
  2084. ->setRequired(true)
  2085. ->addValidator('InArray', false, array(array('1')));
  2086. $subForm->addSubForm($subSubForm, 'subSub');
  2087. $form->addSubForm($subForm, 'sub')
  2088. ->addElement('submit', 'save', array('value' => 'submit'));
  2089. $data = array('foo' => array(
  2090. 'bar' => array(
  2091. 'lastName' => 'Cow',
  2092. ),
  2093. ));
  2094. $form->sub->subSub->home->addValidator('StringLength', false, array(4, 6));
  2095. $data['foo']['bar']['baz'] = array('bat' => array('quux' => array('home' => 'ab')));
  2096. $form->isValidPartial($data);
  2097. $messages = $form->getMessages();
  2098. $this->assertFalse(empty($messages));
  2099. $this->assertTrue(isset($messages['foo']['bar']['baz']['bat']['quux']['home']), var_export($messages, 1));
  2100. $this->assertTrue(isset($messages['foo']['bar']['baz']['bat']['quux']['home']['notInArray']), var_export($messages, 1));
  2101. }
  2102. public function testValidatingFormWithDisplayGroupsDoesSameAsWithout()
  2103. {
  2104. $this->setupElements();
  2105. $this->form->addDisplayGroup(array('foo', 'baz'), 'foobaz');
  2106. $this->assertTrue($this->form->isValid($this->elementValues));
  2107. $this->assertFalse($this->form->isValid(array(
  2108. 'foo' => '123',
  2109. 'bar' => 'abc',
  2110. 'baz' => 'abc-123'
  2111. )));
  2112. }
  2113. public function testValidatePartialFormWithDisplayGroupsDoesSameAsWithout()
  2114. {
  2115. $this->setupElements();
  2116. $this->form->addDisplayGroup(array('foo', 'baz'), 'foobaz');
  2117. $this->assertTrue($this->form->isValid(array(
  2118. 'foo' => 'abc',
  2119. 'baz' => 'abc123'
  2120. )));
  2121. $this->assertFalse($this->form->isValid(array(
  2122. 'foo' => '123',
  2123. 'baz' => 'abc-123'
  2124. )));
  2125. }
  2126. public function testProcessAjaxReturnsJsonTrueForValidForm()
  2127. {
  2128. $this->setupElements();
  2129. $return = $this->form->processAjax($this->elementValues);
  2130. $this->assertTrue(Zend_Json::decode($return));
  2131. }
  2132. public function testProcessAjaxReturnsJsonTrueForValidPartialForm()
  2133. {
  2134. $this->setupElements();
  2135. $data = array('foo' => 'abcdef', 'baz' => 'abc123');
  2136. $return = $this->form->processAjax($data);
  2137. $this->assertTrue(Zend_Json::decode($return));
  2138. }
  2139. public function testProcessAjaxReturnsJsonWithAllErrorMessagesForInvalidForm()
  2140. {
  2141. $this->setupElements();
  2142. $data = array('foo' => '123456', 'bar' => 'abcdef', 'baz' => 'abc-123');
  2143. $return = Zend_Json::decode($this->form->processAjax($data));
  2144. $this->assertTrue(is_array($return));
  2145. $this->assertEquals(array_keys($data), array_keys($return));
  2146. }
  2147. public function testProcessAjaxReturnsJsonWithAllErrorMessagesForInvalidPartialForm()
  2148. {
  2149. $this->setupElements();
  2150. $data = array('baz' => 'abc-123');
  2151. $return = Zend_Json::decode($this->form->processAjax($data));
  2152. $this->assertTrue(is_array($return));
  2153. $this->assertEquals(array_keys($data), array_keys($return), var_export($return, 1));
  2154. }
  2155. public function testPersistDataStoresDataInSession()
  2156. {
  2157. $this->markTestIncomplete('Zend_Form does not implement session storage at this time');
  2158. }
  2159. public function testCanCheckIfErrorsAreRegistered()
  2160. {
  2161. $this->assertFalse($this->form->isErrors());
  2162. $this->testCanValidateFullFormContainingOnlyElements();
  2163. $this->assertTrue($this->form->isErrors());
  2164. }
  2165. public function testCanRetrieveErrorCodesFromAllElementsAfterFailedValidation()
  2166. {
  2167. $this->_checkZf2794();
  2168. $this->testCanValidateFullFormContainingOnlyElements();
  2169. $codes = $this->form->getErrors();
  2170. $keys = array('foo', 'bar', 'baz');
  2171. $this->assertEquals($keys, array_keys($codes));
  2172. }
  2173. public function testCanRetrieveErrorCodesFromSingleElementAfterFailedValidation()
  2174. {
  2175. $this->_checkZf2794();
  2176. $this->testCanValidateFullFormContainingOnlyElements();
  2177. $codes = $this->form->getErrors();
  2178. $keys = array('foo', 'bar', 'baz');
  2179. $errors = $this->form->getErrors('foo');
  2180. $foo = $this->form->foo;
  2181. $this->assertEquals($foo->getErrors(), $errors);
  2182. }
  2183. public function testCanRetrieveErrorMessagesFromAllElementsAfterFailedValidation()
  2184. {
  2185. $this->_checkZf2794();
  2186. $this->testCanValidateFullFormContainingOnlyElements();
  2187. $codes = $this->form->getMessages();
  2188. $keys = array('foo', 'bar', 'baz');
  2189. $this->assertEquals($keys, array_keys($codes));
  2190. }
  2191. public function testCanRetrieveErrorMessagesFromSingleElementAfterFailedValidation()
  2192. {
  2193. $this->_checkZf2794();
  2194. $this->testCanValidateFullFormContainingOnlyElements();
  2195. $codes = $this->form->getMessages();
  2196. $keys = array('foo', 'bar', 'baz');
  2197. $messages = $this->form->getMessages('foo');
  2198. $foo = $this->form->foo;
  2199. $this->assertEquals($foo->getMessages(), $messages);
  2200. }
  2201. public function testErrorCodesFromSubFormReturnedInSeparateArray()
  2202. {
  2203. $this->_checkZf2794();
  2204. $this->testFullDataArrayUsedToValidateSubFormByDefault();
  2205. $codes = $this->form->getErrors();
  2206. $this->assertTrue(array_key_exists('sub', $codes));
  2207. $this->assertTrue(is_array($codes['sub']));
  2208. $keys = array('subfoo', 'subbar', 'subbaz');
  2209. $this->assertEquals($keys, array_keys($codes['sub']));
  2210. }
  2211. public function testCanRetrieveErrorCodesFromSingleSubFormAfterFailedValidation()
  2212. {
  2213. $this->_checkZf2794();
  2214. $this->testFullDataArrayUsedToValidateSubFormByDefault();
  2215. $codes = $this->form->getErrors('sub');
  2216. $this->assertTrue(is_array($codes));
  2217. $this->assertFalse(empty($codes));
  2218. $keys = array('subfoo', 'subbar', 'subbaz');
  2219. $this->assertEquals($keys, array_keys($codes));
  2220. }
  2221. public function testGetErrorsHonorsElementsBelongTo()
  2222. {
  2223. $this->_checkZf2794();
  2224. $subForm = new Zend_Form_SubForm();
  2225. $subForm->setElementsBelongTo('foo[bar]');
  2226. $subForm->addElement('text', 'test')->test
  2227. ->setRequired(true);
  2228. $this->form->addSubForm($subForm, 'sub');
  2229. $data = array('foo' => array(
  2230. 'bar' => array(
  2231. 'test' => '',
  2232. ),
  2233. ));
  2234. $this->form->isValid($data);
  2235. $codes = $this->form->getErrors();
  2236. $this->assertFalse(empty($codes['foo']['bar']['test']));
  2237. }
  2238. public function testErrorMessagesFromSubFormReturnedInSeparateArray()
  2239. {
  2240. $this->_checkZf2794();
  2241. $this->testFullDataArrayUsedToValidateSubFormByDefault();
  2242. $data = array(
  2243. 'foo' => 'abcdef',
  2244. 'bar' => '123456',
  2245. 'baz' => '123abc',
  2246. 'subfoo' => '123',
  2247. 'subbar' => 'abc',
  2248. 'subbaz' => '123-abc',
  2249. );
  2250. $this->assertFalse($this->form->isValid($data));
  2251. $codes = $this->form->getMessages();
  2252. $this->assertTrue(array_key_exists('sub', $codes));
  2253. $this->assertTrue(is_array($codes['sub']));
  2254. $keys = array('subfoo', 'subbar', 'subbaz');
  2255. $this->assertEquals($keys, array_keys($codes['sub']));
  2256. }
  2257. public function testCanRetrieveErrorMessagesFromSingleSubFormAfterFailedValidation()
  2258. {
  2259. $this->_checkZf2794();
  2260. $this->testFullDataArrayUsedToValidateSubFormByDefault();
  2261. $data = array(
  2262. 'foo' => 'abcdef',
  2263. 'bar' => '123456',
  2264. 'baz' => '123abc',
  2265. 'subfoo' => '123',
  2266. 'subbar' => 'abc',
  2267. 'subbaz' => '123-abc',
  2268. );
  2269. $this->assertFalse($this->form->isValid($data));
  2270. $codes = $this->form->getMessages('sub');
  2271. $this->assertTrue(is_array($codes));
  2272. $this->assertFalse(empty($codes));
  2273. $keys = array('subfoo', 'subbar', 'subbaz');
  2274. $this->assertEquals($keys, array_keys($codes), var_export($codes, 1));
  2275. }
  2276. public function testErrorMessagesAreLocalizedWhenTranslateAdapterPresent()
  2277. {
  2278. $this->_checkZf2794();
  2279. $translations = include dirname(__FILE__) . '/_files/locale/array.php';
  2280. $translate = new Zend_Translate('array', $translations, 'en');
  2281. $translate->setLocale('en');
  2282. $this->form->addElements(array(
  2283. 'foo' => array(
  2284. 'type' => 'text',
  2285. 'options' => array(
  2286. 'required' => true,
  2287. 'validators' => array('NotEmpty')
  2288. )
  2289. ),
  2290. 'bar' => array(
  2291. 'type' => 'text',
  2292. 'options' => array(
  2293. 'required' => true,
  2294. 'validators' => array('Digits')
  2295. )
  2296. ),
  2297. ))
  2298. ->setTranslator($translate);
  2299. $data = array(
  2300. 'foo' => '',
  2301. 'bar' => 'abc',
  2302. );
  2303. if ($this->form->isValid($data)) {
  2304. $this->fail('Form should not validate');
  2305. }
  2306. $messages = $this->form->getMessages();
  2307. $this->assertTrue(isset($messages['foo']));
  2308. $this->assertTrue(isset($messages['bar']));
  2309. foreach ($messages['foo'] as $key => $message) {
  2310. if (array_key_exists($key, $translations)) {
  2311. $this->assertEquals($translations[$key], $message);
  2312. } else {
  2313. $this->fail('Translation for ' . $key . ' does not exist?');
  2314. }
  2315. }
  2316. foreach ($messages['bar'] as $key => $message) {
  2317. if (array_key_exists($key, $translations)) {
  2318. $this->assertEquals($translations[$key], $message);
  2319. } else {
  2320. $this->fail('Translation for ' . $key . ' does not exist?');
  2321. }
  2322. }
  2323. }
  2324. public function testErrorMessagesFromPartialValidationAreLocalizedWhenTranslateAdapterPresent()
  2325. {
  2326. $this->_checkZf2794();
  2327. $translations = include dirname(__FILE__) . '/_files/locale/array.php';
  2328. $translate = new Zend_Translate('array', $translations, 'en');
  2329. $translate->setLocale('en');
  2330. $this->form->addElements(array(
  2331. 'foo' => array(
  2332. 'type' => 'text',
  2333. 'options' => array(
  2334. 'required' => true,
  2335. 'validators' => array('NotEmpty')
  2336. )
  2337. ),
  2338. 'bar' => array(
  2339. 'type' => 'text',
  2340. 'options' => array(
  2341. 'required' => true,
  2342. 'validators' => array('Digits')
  2343. )
  2344. ),
  2345. ))
  2346. ->setTranslator($translate);
  2347. $data = array(
  2348. 'foo' => '',
  2349. );
  2350. if ($this->form->isValidPartial($data)) {
  2351. $this->fail('Form should not validate');
  2352. }
  2353. $messages = $this->form->getMessages();
  2354. $this->assertTrue(isset($messages['foo']));
  2355. $this->assertFalse(isset($messages['bar']));
  2356. foreach ($messages['foo'] as $key => $message) {
  2357. if (array_key_exists($key, $translations)) {
  2358. $this->assertEquals($translations[$key], $message);
  2359. } else {
  2360. $this->fail('Translation for ' . $key . ' does not exist?');
  2361. }
  2362. }
  2363. }
  2364. public function testErrorMessagesFromProcessAjaxAreLocalizedWhenTranslateAdapterPresent()
  2365. {
  2366. $this->_checkZf2794();
  2367. $translations = include dirname(__FILE__) . '/_files/locale/array.php';
  2368. $translate = new Zend_Translate('array', $translations, 'en');
  2369. $translate->setLocale('en');
  2370. $this->form->addElements(array(
  2371. 'foo' => array(
  2372. 'type' => 'text',
  2373. 'options' => array(
  2374. 'required' => true,
  2375. 'validators' => array('NotEmpty')
  2376. )
  2377. ),
  2378. 'bar' => array(
  2379. 'type' => 'text',
  2380. 'options' => array(
  2381. 'required' => true,
  2382. 'validators' => array('Digits')
  2383. )
  2384. ),
  2385. ))
  2386. ->setTranslator($translate);
  2387. $data = array(
  2388. 'foo' => '',
  2389. );
  2390. $return = $this->form->processAjax($data);
  2391. $messages = Zend_Json::decode($return);
  2392. $this->assertTrue(is_array($messages));
  2393. $this->assertTrue(isset($messages['foo']));
  2394. $this->assertFalse(isset($messages['bar']));
  2395. foreach ($messages['foo'] as $key => $message) {
  2396. if (array_key_exists($key, $translations)) {
  2397. $this->assertEquals($translations[$key], $message);
  2398. } else {
  2399. $this->fail('Translation for ' . $key . ' does not exist?');
  2400. }
  2401. }
  2402. }
  2403. /**
  2404. * @Group ZF-9697
  2405. */
  2406. public function _setup9697()
  2407. {
  2408. $callback = create_function('$value, $options',
  2409. 'return (isset($options["bar"]["quo"]["foo"]) &&
  2410. "foo Value" === $options["bar"]["quo"]["foo"]);');
  2411. $this->form->addElement('text', 'foo')
  2412. ->foo->setBelongsTo('bar[quo]');
  2413. $this->form->addElement('text', 'quo')
  2414. ->quo->setBelongsTo('bar[quo]')
  2415. ->addValidator('Callback',
  2416. false,
  2417. $callback);
  2418. return array('bar' => array('quo' => array('foo' => 'foo Value',
  2419. 'quo' => 'quo Value')));
  2420. }
  2421. public function testIsValidKeepsContext()
  2422. {
  2423. $data = $this->_setup9697();
  2424. $this->assertTrue($this->form->isValid($data));
  2425. }
  2426. public function testIsValidPartialKeepsContext()
  2427. {
  2428. $data = $this->_setup9697();
  2429. $this->assertTrue($this->form->isValidPartial($data));
  2430. }
  2431. public function testGetValidValuesKeepsContext()
  2432. {
  2433. $data = $this->_setup9697();
  2434. $this->assertSame($data, $this->form->getValidValues($data));
  2435. }
  2436. /**
  2437. * @group ZF-2988
  2438. */
  2439. public function testSettingErrorMessageShouldOverrideValidationErrorMessages()
  2440. {
  2441. $this->form->addElement('text', 'foo', array('validators' => array('Alpha')));
  2442. $this->form->addErrorMessage('Invalid values entered');
  2443. $this->assertFalse($this->form->isValid(array('foo' => 123)));
  2444. $messages = $this->form->getMessages();
  2445. $this->assertEquals(1, count($messages));
  2446. $this->assertEquals('Invalid values entered', array_shift($messages));
  2447. }
  2448. public function testCustomErrorMessagesShouldBeManagedInAStack()
  2449. {
  2450. $this->form->addElement('text', 'foo', array('validators' => array('Alpha')));
  2451. $this->form->addErrorMessage('Invalid values entered');
  2452. $this->form->addErrorMessage('Really, they are not valid');
  2453. $messages = $this->form->getErrorMessages();
  2454. $this->assertEquals(2, count($messages));
  2455. $this->assertFalse($this->form->isValid(array('foo' => 123)));
  2456. $messages = $this->form->getMessages();
  2457. $this->assertEquals(2, count($messages));
  2458. $this->assertEquals('Invalid values entered', array_shift($messages));
  2459. $this->assertEquals('Really, they are not valid', array_shift($messages));
  2460. }
  2461. public function testShouldAllowSettingMultipleErrorMessagesAtOnce()
  2462. {
  2463. $set1 = array('foo', 'bar', 'baz');
  2464. $this->form->addErrorMessages($set1);
  2465. $this->assertSame($set1, $this->form->getErrorMessages());
  2466. }
  2467. public function testSetErrorMessagesShouldOverwriteMessages()
  2468. {
  2469. $set1 = array('foo', 'bar', 'baz');
  2470. $set2 = array('bat', 'cat');
  2471. $this->form->addErrorMessages($set1);
  2472. $this->assertSame($set1, $this->form->getErrorMessages());
  2473. $this->form->setErrorMessages($set2);
  2474. $this->assertSame($set2, $this->form->getErrorMessages());
  2475. }
  2476. public function testCustomErrorMessageStackShouldBeClearable()
  2477. {
  2478. $this->testCustomErrorMessagesShouldBeManagedInAStack();
  2479. $this->form->clearErrorMessages();
  2480. $messages = $this->form->getErrorMessages();
  2481. $this->assertTrue(empty($messages));
  2482. }
  2483. public function testCustomErrorMessagesShouldBeTranslated()
  2484. {
  2485. $translations = array(
  2486. 'foo' => 'Foo message',
  2487. );
  2488. $translate = new Zend_Translate('array', $translations);
  2489. $this->form->addElement('text', 'foo', array('validators' => array('Alpha')));
  2490. $this->form->setTranslator($translate)
  2491. ->addErrorMessage('foo');
  2492. $this->assertFalse($this->form->isValid(array('foo' => 123)));
  2493. $messages = $this->form->getMessages();
  2494. $this->assertEquals(1, count($messages));
  2495. $this->assertEquals('Foo message', array_shift($messages));
  2496. }
  2497. public function testShouldAllowMarkingFormAsInvalid()
  2498. {
  2499. $this->form->addErrorMessage('Invalid values entered');
  2500. $this->assertFalse($this->form->isErrors());
  2501. $this->form->markAsError();
  2502. $this->assertTrue($this->form->isErrors());
  2503. $messages = $this->form->getMessages();
  2504. $this->assertEquals(1, count($messages));
  2505. $this->assertEquals('Invalid values entered', array_shift($messages));
  2506. }
  2507. public function testShouldAllowPushingErrorsOntoErrorStackWithErrorMessages()
  2508. {
  2509. $this->assertFalse($this->form->isErrors());
  2510. $this->form->setErrors(array('Error 1', 'Error 2'))
  2511. ->addError('Error 3')
  2512. ->addErrors(array('Error 4', 'Error 5'));
  2513. $this->assertTrue($this->form->isErrors());
  2514. $messages = $this->form->getMessages();
  2515. $this->assertEquals(5, count($messages));
  2516. foreach (range(1, 5) as $id) {
  2517. $message = 'Error ' . $id;
  2518. $this->assertContains($message, $messages);
  2519. }
  2520. }
  2521. /**#@-*/
  2522. // View object
  2523. public function getView()
  2524. {
  2525. $view = new Zend_View();
  2526. return $view;
  2527. }
  2528. public function testGetViewRetrievesFromViewRendererByDefault()
  2529. {
  2530. $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
  2531. $viewRenderer->initView();
  2532. $view = $viewRenderer->view;
  2533. $test = $this->form->getView();
  2534. $this->assertSame($view, $test);
  2535. }
  2536. public function testGetViewReturnsNullWhenNoViewRegisteredWithViewRenderer()
  2537. {
  2538. $this->assertNull($this->form->getView());
  2539. }
  2540. public function testCanSetView()
  2541. {
  2542. $view = new Zend_View();
  2543. $this->assertNull($this->form->getView());
  2544. $this->form->setView($view);
  2545. $received = $this->form->getView();
  2546. $this->assertSame($view, $received);
  2547. }
  2548. // Decorators
  2549. public function testFormDecoratorRegisteredByDefault()
  2550. {
  2551. $this->_checkZf2794();
  2552. $decorator = $this->form->getDecorator('form');
  2553. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Form);
  2554. }
  2555. public function testCanDisableRegisteringFormDecoratorsDuringInitialization()
  2556. {
  2557. $form = new Zend_Form(array('disableLoadDefaultDecorators' => true));
  2558. $decorators = $form->getDecorators();
  2559. $this->assertEquals(array(), $decorators);
  2560. }
  2561. public function testCanAddSingleDecoratorAsString()
  2562. {
  2563. $this->_checkZf2794();
  2564. $this->form->clearDecorators();
  2565. $this->assertFalse($this->form->getDecorator('viewHelper'));
  2566. $this->form->addDecorator('viewHelper');
  2567. $decorator = $this->form->getDecorator('viewHelper');
  2568. $this->assertTrue($decorator instanceof Zend_Form_Decorator_ViewHelper);
  2569. }
  2570. public function testNotCanRetrieveSingleDecoratorRegisteredAsStringUsingClassName()
  2571. {
  2572. $this->assertFalse($this->form->getDecorator('Zend_Form_Decorator_Form'));
  2573. }
  2574. public function testCanAddSingleDecoratorAsDecoratorObject()
  2575. {
  2576. $this->form->clearDecorators();
  2577. $this->assertFalse($this->form->getDecorator('viewHelper'));
  2578. $decorator = new Zend_Form_Decorator_ViewHelper;
  2579. $this->form->addDecorator($decorator);
  2580. $test = $this->form->getDecorator('Zend_Form_Decorator_ViewHelper');
  2581. $this->assertSame($decorator, $test);
  2582. }
  2583. public function testCanRetrieveSingleDecoratorRegisteredAsDecoratorObjectUsingShortName()
  2584. {
  2585. $this->_checkZf2794();
  2586. $this->form->clearDecorators();
  2587. $this->assertFalse($this->form->getDecorator('viewHelper'));
  2588. $decorator = new Zend_Form_Decorator_ViewHelper;
  2589. $this->form->addDecorator($decorator);
  2590. $test = $this->form->getDecorator('viewHelper');
  2591. $this->assertSame($decorator, $test);
  2592. }
  2593. public function testCanAddMultipleDecorators()
  2594. {
  2595. $this->_checkZf2794();
  2596. $this->form->clearDecorators();
  2597. $this->assertFalse($this->form->getDecorator('viewHelper'));
  2598. $testDecorator = new Zend_Form_Decorator_Errors;
  2599. $this->form->addDecorators(array(
  2600. 'ViewHelper',
  2601. $testDecorator
  2602. ));
  2603. $viewHelper = $this->form->getDecorator('viewHelper');
  2604. $this->assertTrue($viewHelper instanceof Zend_Form_Decorator_ViewHelper);
  2605. $decorator = $this->form->getDecorator('errors');
  2606. $this->assertSame($testDecorator, $decorator);
  2607. }
  2608. public function testRemoveDecoratorReturnsFalseForUnregisteredDecorators()
  2609. {
  2610. $this->_checkZf2794();
  2611. $this->assertFalse($this->form->removeDecorator('foobar'));
  2612. }
  2613. public function testCanRemoveDecorator()
  2614. {
  2615. $this->_checkZf2794();
  2616. $this->testFormDecoratorRegisteredByDefault();
  2617. $this->form->removeDecorator('form');
  2618. $this->assertFalse($this->form->getDecorator('form'));
  2619. }
  2620. /**
  2621. * @group ZF-3069
  2622. */
  2623. public function testRemovingNamedDecoratorShouldWork()
  2624. {
  2625. $this->_checkZf2794();
  2626. $this->form->setDecorators(array(
  2627. 'FormElements',
  2628. array(array('div' => 'HtmlTag'), array('tag' => 'div')),
  2629. array(array('fieldset' => 'HtmlTag'), array('tag' => 'fieldset')),
  2630. ));
  2631. $decorators = $this->form->getDecorators();
  2632. $this->assertTrue(array_key_exists('div', $decorators));
  2633. $this->assertTrue(array_key_exists('fieldset', $decorators));
  2634. $this->form->removeDecorator('div');
  2635. $decorators = $this->form->getDecorators();
  2636. $this->assertFalse(array_key_exists('div', $decorators));
  2637. $this->assertTrue(array_key_exists('fieldset', $decorators));
  2638. }
  2639. public function testCanClearAllDecorators()
  2640. {
  2641. $this->_checkZf2794();
  2642. $this->testCanAddMultipleDecorators();
  2643. $this->form->clearDecorators();
  2644. $this->assertFalse($this->form->getDecorator('viewHelper'));
  2645. $this->assertFalse($this->form->getDecorator('fieldset'));
  2646. }
  2647. public function testCanAddDecoratorAliasesToAllowMultipleDecoratorsOfSameType()
  2648. {
  2649. $this->_checkZf2794();
  2650. $this->form->setDecorators(array(
  2651. array('HtmlTag', array('tag' => 'div')),
  2652. array('decorator' => array('FooBar' => 'HtmlTag'), 'options' => array('tag' => 'dd')),
  2653. ));
  2654. $decorator = $this->form->getDecorator('FooBar');
  2655. $this->assertTrue($decorator instanceof Zend_Form_Decorator_HtmlTag);
  2656. $this->assertEquals('dd', $decorator->getOption('tag'));
  2657. $decorator = $this->form->getDecorator('HtmlTag');
  2658. $this->assertTrue($decorator instanceof Zend_Form_Decorator_HtmlTag);
  2659. $this->assertEquals('div', $decorator->getOption('tag'));
  2660. }
  2661. public function testRetrievingNamedDecoratorShouldNotReorderDecorators()
  2662. {
  2663. $this->form->setDecorators(array(
  2664. 'FormElements',
  2665. array(array('div' => 'HtmlTag'), array('tag' => 'div')),
  2666. array(array('fieldset' => 'HtmlTag'), array('tag' => 'fieldset')),
  2667. 'Form',
  2668. ));
  2669. $decorator = $this->form->getDecorator('fieldset');
  2670. $decorators = $this->form->getDecorators();
  2671. $i = 0;
  2672. $order = array();
  2673. foreach (array_keys($decorators) as $name) {
  2674. $order[$name] = $i;
  2675. ++$i;
  2676. }
  2677. $this->assertEquals(2, $order['fieldset'], var_export($order, 1));
  2678. }
  2679. // Rendering
  2680. public function checkMarkup($html)
  2681. {
  2682. $this->assertFalse(empty($html));
  2683. $this->assertContains('<form', $html);
  2684. $this->assertRegexp('/<form[^>]+action="' . $this->form->getAction() . '"/', $html);
  2685. $this->assertRegexp('/<form[^>]+method="' . $this->form->getMethod() . '"/i', $html);
  2686. $this->assertRegexp('#<form[^>]+enctype="application/x-www-form-urlencoded"#', $html);
  2687. $this->assertContains('</form>', $html);
  2688. }
  2689. public function testRenderReturnsMarkup()
  2690. {
  2691. $this->setupElements();
  2692. $html = $this->form->render($this->getView());
  2693. $this->checkMarkup($html);
  2694. }
  2695. public function testRenderReturnsMarkupRepresentingAllElements()
  2696. {
  2697. $this->testRenderReturnsMarkup();
  2698. $html = $this->form->render();
  2699. foreach ($this->form->getElements() as $key => $element) {
  2700. $this->assertFalse(empty($key));
  2701. $this->assertFalse(is_numeric($key));
  2702. $this->assertContains('<input', $html);
  2703. $this->assertRegexp('/<input type="text" name="' . $key . '"/', $html);
  2704. }
  2705. }
  2706. public function testRenderReturnsMarkupContainingSubForms()
  2707. {
  2708. $this->setupElements();
  2709. $this->setupSubForm();
  2710. $this->form->setView($this->getView());
  2711. $html = $this->form->render();
  2712. $this->assertRegexp('/<fieldset/', $html);
  2713. $this->assertContains('</fieldset>', $html);
  2714. foreach ($this->form->sub as $key => $item) {
  2715. $this->assertFalse(empty($key));
  2716. $this->assertFalse(is_numeric($key));
  2717. $this->assertContains('<input', $html);
  2718. $pattern = '/<input type="text" name="sub\[' . $key . '\]"/';
  2719. $this->assertRegexp($pattern, $html, 'Pattern: ' . $pattern . "\nHTML:\n" . $html);
  2720. }
  2721. }
  2722. public function testRenderReturnsMarkupContainingDisplayGroups()
  2723. {
  2724. $this->setupElements();
  2725. $this->form->addDisplayGroup(array('foo', 'baz'), 'foobaz', array('legend' => 'Display Group'));
  2726. $this->form->setView($this->getView());
  2727. $html = $this->html = $this->form->render();
  2728. $this->assertRegexp('/<fieldset/', $html);
  2729. $this->assertContains('</fieldset>', $html);
  2730. $this->assertRegexp('#<legend>Display Group</legend>#', $html, $html);
  2731. $dom = new DOMDocument();
  2732. $dom->loadHTML($html);
  2733. $fieldsets = $dom->getElementsByTagName('fieldset');
  2734. $this->assertTrue(0 < $fieldsets->length);
  2735. $fieldset = $fieldsets->item(0);
  2736. $nodes = $fieldset->childNodes;
  2737. $this->assertNotNull($nodes);
  2738. for ($i = 0; $i < $nodes->length; ++$i) {
  2739. $node = $nodes->item($i);
  2740. if ('input' != $node->nodeName) {
  2741. continue;
  2742. }
  2743. $this->assertTrue($node->hasAttribute('name'));
  2744. $nameNode = $node->getAttributeNode('name');
  2745. switch ($i) {
  2746. case 0:
  2747. $this->assertEquals('foo', $nameNode->nodeValue);
  2748. break;
  2749. case 1:
  2750. $this->assertEquals('baz', $nameNode->nodeValue);
  2751. break;
  2752. default:
  2753. $this->fail('There should only be two input nodes in this display group: ' . $html);
  2754. }
  2755. }
  2756. }
  2757. public function testRenderDoesNotRepeatElementsInDisplayGroups()
  2758. {
  2759. $this->testRenderReturnsMarkupContainingDisplayGroups();
  2760. if (!preg_match_all('#<input[^>]+name="foo"#', $this->html, $matches)) {
  2761. $this->fail("Should find foo element in rendered form");
  2762. }
  2763. $this->assertEquals(1, count($matches));
  2764. $this->assertEquals(1, count($matches[0]));
  2765. }
  2766. public function testElementsRenderAsArrayMembersWhenElementsBelongToAnArray()
  2767. {
  2768. $this->setupElements();
  2769. $this->form->setElementsBelongTo('anArray');
  2770. $html = $this->form->render($this->getView());
  2771. $this->assertContains('name="anArray[foo]"', $html);
  2772. $this->assertContains('name="anArray[bar]"', $html);
  2773. $this->assertContains('name="anArray[baz]"', $html);
  2774. $this->assertContains('id="anArray-foo"', $html);
  2775. $this->assertContains('id="anArray-bar"', $html);
  2776. $this->assertContains('id="anArray-baz"', $html);
  2777. }
  2778. public function testElementsRenderAsSubArrayMembersWhenElementsBelongToASubArray()
  2779. {
  2780. $this->setupElements();
  2781. $this->form->setElementsBelongTo('data[foo]');
  2782. $html = $this->form->render($this->getView());
  2783. $this->assertContains('name="data[foo][foo]"', $html);
  2784. $this->assertContains('name="data[foo][bar]"', $html);
  2785. $this->assertContains('name="data[foo][baz]"', $html);
  2786. $this->assertContains('id="data-foo-foo"', $html);
  2787. $this->assertContains('id="data-foo-bar"', $html);
  2788. $this->assertContains('id="data-foo-baz"', $html);
  2789. }
  2790. public function testElementsRenderAsArrayMembersWhenRenderAsArrayToggled()
  2791. {
  2792. $this->setupElements();
  2793. $this->form->setName('data')
  2794. ->setIsArray(true);
  2795. $html = $this->form->render($this->getView());
  2796. $this->assertContains('name="data[foo]"', $html);
  2797. $this->assertContains('name="data[bar]"', $html);
  2798. $this->assertContains('name="data[baz]"', $html);
  2799. $this->assertContains('id="data-foo"', $html);
  2800. $this->assertContains('id="data-bar"', $html);
  2801. $this->assertContains('id="data-baz"', $html);
  2802. }
  2803. public function testElementsRenderAsMembersOfSubFormsWithElementsBelongTo()
  2804. {
  2805. $this->form->setName('data')
  2806. ->setIsArray(true);
  2807. $subForm = new Zend_Form_SubForm();
  2808. $subForm->setElementsBelongTo('billing[info]');
  2809. $subForm->addElement('text', 'name');
  2810. $subForm->addElement('text', 'number');
  2811. $this->form->addSubForm($subForm, 'sub');
  2812. $html = $this->form->render($this->getView());
  2813. $this->assertContains('name="data[billing][info][name]', $html);
  2814. $this->assertContains('name="data[billing][info][number]', $html);
  2815. $this->assertContains('id="data-billing-info-name"', $html);
  2816. $this->assertContains('id="data-billing-info-number"', $html);
  2817. }
  2818. public function testToStringProxiesToRender()
  2819. {
  2820. $this->setupElements();
  2821. $this->form->setView($this->getView());
  2822. $html = $this->form->__toString();
  2823. $this->checkMarkup($html);
  2824. }
  2825. public function raiseDecoratorException($content, $element, $options)
  2826. {
  2827. throw new Exception('Raising exception in decorator callback');
  2828. }
  2829. public function handleDecoratorErrors($errno, $errstr, $errfile = '', $errline = 0, array $errcontext = array())
  2830. {
  2831. $this->error = $errstr;
  2832. }
  2833. public function testToStringRaisesErrorWhenExceptionCaught()
  2834. {
  2835. $this->form->setDecorators(array(
  2836. array(
  2837. 'decorator' => 'Callback',
  2838. 'options' => array('callback' => array($this, 'raiseDecoratorException'))
  2839. ),
  2840. ));
  2841. $origErrorHandler = set_error_handler(array($this, 'handleDecoratorErrors'), E_USER_WARNING);
  2842. $text = $this->form->__toString();
  2843. restore_error_handler();
  2844. $this->assertTrue(empty($text));
  2845. $this->assertTrue(isset($this->error));
  2846. $this->assertContains('Raising exception in decorator callback', $this->error);
  2847. }
  2848. /**
  2849. * ZF-2718
  2850. */
  2851. public function testHiddenElementsGroupedWhenRendered()
  2852. {
  2853. $this->markTestIncomplete('Scheduling for future release');
  2854. $this->form->addElements(array(
  2855. array('type' => 'hidden', 'name' => 'first', 'options' => array('value' => 'first value')),
  2856. array('type' => 'text', 'name' => 'testone'),
  2857. array('type' => 'hidden', 'name' => 'second', 'options' => array('value' => 'second value')),
  2858. array('type' => 'text', 'name' => 'testtwo'),
  2859. array('type' => 'hidden', 'name' => 'third', 'options' => array('value' => 'third value')),
  2860. array('type' => 'text', 'name' => 'testthree'),
  2861. ));
  2862. $html = $this->form->render($this->getView());
  2863. if (!preg_match('#(<input type="hidden" name="[^>].*>\s*){3}#', $html, $matches)) {
  2864. $this->fail('Hidden elements should be grouped');
  2865. }
  2866. foreach (array('first', 'second', 'third') as $which) {
  2867. $this->assertRegexp('#<input[^]*name="' . $which . '"#', $matches[0]);
  2868. $this->assertRegexp('#<input[^]*value="' . $which . ' value"#', $matches[0]);
  2869. }
  2870. }
  2871. // Localization
  2872. public function testTranslatorIsNullByDefault()
  2873. {
  2874. $this->assertNull($this->form->getTranslator());
  2875. }
  2876. public function testCanSetTranslator()
  2877. {
  2878. require_once 'Zend/Translate/Adapter/Array.php';
  2879. $translator = new Zend_Translate('array', array('foo' => 'bar'));
  2880. $this->form->setTranslator($translator);
  2881. $received = $this->form->getTranslator($translator);
  2882. $this->assertSame($translator->getAdapter(), $received);
  2883. }
  2884. public function testCanSetDefaultGlobalTranslator()
  2885. {
  2886. $this->assertNull($this->form->getTranslator());
  2887. $translator = new Zend_Translate('array', array('foo' => 'bar'));
  2888. Zend_Form::setDefaultTranslator($translator);
  2889. $received = Zend_Form::getDefaultTranslator();
  2890. $this->assertSame($translator->getAdapter(), $received);
  2891. $received = $this->form->getTranslator();
  2892. $this->assertSame($translator->getAdapter(), $received);
  2893. $form = new Zend_Form();
  2894. $received = $form->getTranslator();
  2895. $this->assertSame($translator->getAdapter(), $received);
  2896. }
  2897. public function testLocalTranslatorPreferredOverDefaultGlobalTranslator()
  2898. {
  2899. $this->assertNull($this->form->getTranslator());
  2900. $translatorDefault = new Zend_Translate('array', array('foo' => 'bar'));
  2901. Zend_Form::setDefaultTranslator($translatorDefault);
  2902. $received = $this->form->getTranslator();
  2903. $this->assertSame($translatorDefault->getAdapter(), $received);
  2904. $translator = new Zend_Translate('array', array('foo' => 'bar'));
  2905. $this->form->setTranslator($translator);
  2906. $received = $this->form->getTranslator();
  2907. $this->assertNotSame($translatorDefault->getAdapter(), $received);
  2908. $this->assertSame($translator->getAdapter(), $received);
  2909. }
  2910. public function testTranslatorFromRegistryUsedWhenNoneRegistered()
  2911. {
  2912. $this->assertNull($this->form->getTranslator());
  2913. $translator = new Zend_Translate('array', array('foo' => 'bar'));
  2914. Zend_Registry::set('Zend_Translate', $translator);
  2915. $received = Zend_Form::getDefaultTranslator();
  2916. $this->assertSame($translator->getAdapter(), $received);
  2917. $received = $this->form->getTranslator();
  2918. $this->assertSame($translator->getAdapter(), $received);
  2919. $form = new Zend_Form();
  2920. $received = $form->getTranslator();
  2921. $this->assertSame($translator->getAdapter(), $received);
  2922. }
  2923. public function testCanDisableTranslation()
  2924. {
  2925. $this->testCanSetDefaultGlobalTranslator();
  2926. $this->form->setDisableTranslator(true);
  2927. $this->assertNull($this->form->getTranslator());
  2928. }
  2929. // Iteration
  2930. public function testFormObjectIsIterableAndIteratesElements()
  2931. {
  2932. $this->setupElements();
  2933. $expected = array('foo', 'bar', 'baz');
  2934. $received = array();
  2935. foreach ($this->form as $key => $value) {
  2936. $received[] = $key;
  2937. }
  2938. $this->assertSame($expected, $received);
  2939. }
  2940. public function testFormObjectIteratesElementsInExpectedOrder()
  2941. {
  2942. $this->setupElements();
  2943. $this->form->addElement('text', 'checkorder', array('order' => 2));
  2944. $expected = array('foo', 'bar', 'checkorder', 'baz');
  2945. $received = array();
  2946. foreach ($this->form as $key => $value) {
  2947. $received[] = $key;
  2948. $this->assertTrue($value instanceof Zend_Form_Element);
  2949. }
  2950. $this->assertSame($expected, $received);
  2951. }
  2952. public function testFormObjectIteratesElementsInExpectedOrderWhenAllElementsHaveOrder()
  2953. {
  2954. $this->form->addElement('submit', 'submit')->submit->setLabel('Submit')->setOrder(30);
  2955. $this->form->addElement('text', 'name')->name->setLabel('Name')->setOrder(10);
  2956. $this->form->addElement('text', 'email')->email->setLabel('E-mail')->setOrder(20);
  2957. $expected = array('name', 'email', 'submit');
  2958. $received = array();
  2959. foreach ($this->form as $key => $value) {
  2960. $received[] = $key;
  2961. $this->assertTrue($value instanceof Zend_Form_Element);
  2962. }
  2963. $this->assertSame($expected, $received);
  2964. }
  2965. public function testFormObjectIteratesElementsInExpectedOrderWhenFirstElementHasNoOrderSpecified()
  2966. {
  2967. $this->form->addElement(new Zend_Form_Element('a',array('label'=>'a')))
  2968. ->addElement(new Zend_Form_Element('b',array('label'=>'b', 'order' => 0)))
  2969. ->addElement(new Zend_Form_Element('c',array('label'=>'c', 'order' => 1)))
  2970. ->setView($this->getView());
  2971. $test = $this->form->render();
  2972. $this->assertContains('name="a"', $test);
  2973. if (!preg_match_all('/(<input[^>]+>)/', $test, $matches)) {
  2974. $this->fail('Expected markup not found');
  2975. }
  2976. $order = array();
  2977. foreach ($matches[1] as $element) {
  2978. if (preg_match('/name="(a|b|c)"/', $element, $m)) {
  2979. $order[] = $m[1];
  2980. }
  2981. }
  2982. $this->assertSame(array('b', 'c', 'a'), $order);
  2983. }
  2984. public function testFormObjectIteratesElementsAndSubforms()
  2985. {
  2986. $this->setupElements();
  2987. $this->setupSubForm();
  2988. $expected = array('foo', 'bar', 'baz', 'sub');
  2989. $received = array();
  2990. foreach ($this->form as $key => $value) {
  2991. $received[] = $key;
  2992. $this->assertTrue(($value instanceof Zend_Form_Element)
  2993. or ($value instanceof Zend_Form_SubForm));
  2994. }
  2995. $this->assertSame($expected, $received);
  2996. }
  2997. public function testFormObjectIteratesDisplayGroupsButSkipsDisplayGroupElements()
  2998. {
  2999. $this->setupElements();
  3000. $this->form->addDisplayGroup(array('foo', 'baz'), 'foobaz');
  3001. $expected = array('bar', 'foobaz');
  3002. $received = array();
  3003. foreach ($this->form as $key => $value) {
  3004. $received[] = $key;
  3005. $this->assertTrue(($value instanceof Zend_Form_Element)
  3006. or ($value instanceof Zend_Form_DisplayGroup));
  3007. }
  3008. $this->assertSame($expected, $received);
  3009. }
  3010. public function testRemovingFormItemsShouldNotRaiseExceptionsDuringIteration()
  3011. {
  3012. $this->setupElements();
  3013. $bar = $this->form->bar;
  3014. $this->form->removeElement('bar');
  3015. try {
  3016. foreach ($this->form as $item) {
  3017. }
  3018. } catch (Exception $e) {
  3019. $this->fail('Exceptions should not be raised by iterator when elements are removed; error message: ' . $e->getMessage());
  3020. }
  3021. $this->form->addElement($bar);
  3022. $this->form->addDisplayGroup(array('baz', 'bar'), 'bazbar');
  3023. $this->form->removeDisplayGroup('bazbar');
  3024. try {
  3025. foreach ($this->form as $item) {
  3026. }
  3027. } catch (Exception $e) {
  3028. $this->fail('Exceptions should not be raised by iterator when elements are removed; error message: ' . $e->getMessage());
  3029. }
  3030. $subForm = new Zend_Form_SubForm;
  3031. $subForm->addElements(array('foo' => 'text', 'bar' => 'text'));
  3032. $this->form->addSubForm($subForm, 'page1');
  3033. $this->form->removeSubForm('page1');
  3034. try {
  3035. foreach ($this->form as $item) {
  3036. }
  3037. } catch (Exception $e) {
  3038. $this->fail('Exceptions should not be raised by iterator when elements are removed; error message: ' . $e->getMessage());
  3039. }
  3040. }
  3041. public function testClearingAttachedItemsShouldNotCauseIterationToRaiseExceptions()
  3042. {
  3043. $form = new Zend_Form();
  3044. $form->addElements(array(
  3045. 'username' => 'text',
  3046. 'password' => 'text',
  3047. ));
  3048. $form->clearElements();
  3049. try {
  3050. foreach ($form as $item) {
  3051. }
  3052. } catch (Zend_Form_Exception $e) {
  3053. $message = "Clearing elements prior to iteration should not cause iteration to fail;\n"
  3054. . $e->getMessage();
  3055. $this->fail($message);
  3056. }
  3057. $form->addElements(array(
  3058. 'username' => 'text',
  3059. 'password' => 'text',
  3060. ))
  3061. ->addDisplayGroup(array('username', 'password'), 'login');
  3062. $form->clearDisplayGroups();
  3063. try {
  3064. foreach ($form as $item) {
  3065. }
  3066. } catch (Zend_Form_Exception $e) {
  3067. $message = "Clearing display groups prior to iteration should not cause iteration to fail;\n"
  3068. . $e->getMessage();
  3069. $this->fail($message);
  3070. }
  3071. $subForm = new Zend_Form_SubForm();
  3072. $form->addSubForm($subForm, 'foo');
  3073. $form->clearSubForms();
  3074. try {
  3075. foreach ($form as $item) {
  3076. }
  3077. } catch (Zend_Form_Exception $e) {
  3078. $message = "Clearing sub forms prior to iteration should not cause iteration to fail;\n"
  3079. . $e->getMessage();
  3080. $this->fail($message);
  3081. }
  3082. }
  3083. // Countable
  3084. public function testCanCountFormObject()
  3085. {
  3086. $this->setupElements();
  3087. $this->assertEquals(3, count($this->form));
  3088. }
  3089. public function testCountingFormObjectCountsSubForms()
  3090. {
  3091. $this->setupElements();
  3092. $this->setupSubForm();
  3093. $this->assertEquals(4, count($this->form));
  3094. }
  3095. public function testCountingFormCountsDisplayGroupsButOmitsElementsInDisplayGroups()
  3096. {
  3097. $this->testCountingFormObjectCountsSubForms();
  3098. $this->form->addDisplayGroup(array('foo', 'baz'), 'foobaz');
  3099. $this->assertEquals(3, count($this->form));
  3100. }
  3101. // Element decorators and plugin paths
  3102. public function testCanSetAllElementDecoratorsAtOnce()
  3103. {
  3104. $this->_checkZf2794();
  3105. $this->setupElements();
  3106. $this->form->setElementDecorators(array(
  3107. array('ViewHelper'),
  3108. array('Label'),
  3109. array('Fieldset'),
  3110. ));
  3111. foreach ($this->form->getElements() as $element) {
  3112. $this->assertFalse($element->getDecorator('Errors'));
  3113. $this->assertFalse($element->getDecorator('HtmlTag'));
  3114. $decorator = $element->getDecorator('ViewHelper');
  3115. $this->assertTrue($decorator instanceof Zend_Form_Decorator_ViewHelper);
  3116. $decorator = $element->getDecorator('Label');
  3117. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Label);
  3118. $decorator = $element->getDecorator('Fieldset');
  3119. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Fieldset);
  3120. }
  3121. }
  3122. /**
  3123. * @group ZF-3597
  3124. */
  3125. public function testSettingElementDecoratorsWithConcreteDecoratorShouldHonorOrder()
  3126. {
  3127. $this->form->setDecorators(array(
  3128. 'FormElements',
  3129. array('HtmlTag', array('tag' => 'table')),
  3130. 'Form',
  3131. ));
  3132. $this->form->addElementPrefixPath('My_Decorator', dirname(__FILE__) . '/_files/decorators/', 'decorator');
  3133. $this->form->addElement('text', 'test', array(
  3134. 'label' => 'Foo',
  3135. 'description' => 'sample description',
  3136. ));
  3137. require_once dirname(__FILE__) . '/_files/decorators/TableRow.php';
  3138. $decorator = new My_Decorator_TableRow();
  3139. $this->form->setElementDecorators(array(
  3140. 'ViewHelper',
  3141. $decorator,
  3142. ));
  3143. $html = $this->form->render($this->getView());
  3144. $this->assertRegexp('#<tr><td>Foo</td><td>.*?<input[^>]+>.*?</td><td>sample description</td></tr>#s', $html, $html);
  3145. }
  3146. /**
  3147. * @group ZF-3228
  3148. */
  3149. public function testShouldAllowSpecifyingSpecificElementsToDecorate()
  3150. {
  3151. $this->_checkZf2794();
  3152. $this->setupElements();
  3153. $this->form->setElementDecorators(
  3154. array(
  3155. 'Description',
  3156. 'Form',
  3157. 'Fieldset',
  3158. ),
  3159. array(
  3160. 'bar',
  3161. )
  3162. );
  3163. $element = $this->form->bar;
  3164. $this->assertFalse($element->getDecorator('ViewHelper'));
  3165. $this->assertFalse($element->getDecorator('Errors'));
  3166. $this->assertFalse($element->getDecorator('Label'));
  3167. $this->assertFalse($element->getDecorator('HtmlTag'));
  3168. $decorator = $element->getDecorator('Description');
  3169. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Description);
  3170. $decorator = $element->getDecorator('Form');
  3171. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Form);
  3172. $decorator = $element->getDecorator('Fieldset');
  3173. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Fieldset);
  3174. foreach (array('foo', 'baz') as $name) {
  3175. $element = $this->form->$name;
  3176. $this->assertFalse($element->getDecorator('Form'));
  3177. $this->assertFalse($element->getDecorator('Fieldset'));
  3178. }
  3179. }
  3180. public function testShouldAllowSpecifyingListOfElementsNotToDecorate()
  3181. {
  3182. $this->_checkZf2794();
  3183. $this->setupElements();
  3184. $this->form->setElementDecorators(
  3185. array(
  3186. 'Description',
  3187. 'Form',
  3188. 'Fieldset',
  3189. ),
  3190. array(
  3191. 'foo',
  3192. 'baz',
  3193. ),
  3194. false
  3195. );
  3196. $element = $this->form->bar;
  3197. $this->assertFalse($element->getDecorator('ViewHelper'));
  3198. $this->assertFalse($element->getDecorator('Errors'));
  3199. $this->assertFalse($element->getDecorator('Label'));
  3200. $this->assertFalse($element->getDecorator('HtmlTag'));
  3201. $decorator = $element->getDecorator('Description');
  3202. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Description);
  3203. $decorator = $element->getDecorator('Form');
  3204. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Form);
  3205. $decorator = $element->getDecorator('Fieldset');
  3206. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Fieldset);
  3207. foreach (array('foo', 'baz') as $name) {
  3208. $element = $this->form->$name;
  3209. $this->assertFalse($element->getDecorator('Form'));
  3210. $this->assertFalse($element->getDecorator('Fieldset'));
  3211. }
  3212. }
  3213. /**#@-*/
  3214. public function testCanSetAllElementFiltersAtOnce()
  3215. {
  3216. $this->_checkZf2794();
  3217. $this->setupElements();
  3218. $this->form->setElementFilters(array(
  3219. 'Alnum',
  3220. 'StringToLower'
  3221. ));
  3222. foreach ($this->form->getElements() as $element) {
  3223. $filter = $element->getFilter('Alnum');
  3224. $this->assertTrue($filter instanceof Zend_Filter_Alnum);
  3225. $filter = $element->getFilter('StringToLower');
  3226. $this->assertTrue($filter instanceof Zend_Filter_StringToLower);
  3227. }
  3228. }
  3229. public function testCanSetGlobalElementPrefixPath()
  3230. {
  3231. $this->setupElements();
  3232. $this->form->addElementPrefixPath('Zend_Foo', 'Zend/Foo/');
  3233. $this->form->addElement('text', 'prefixTest');
  3234. foreach ($this->form->getElements() as $element) {
  3235. $loader = $element->getPluginLoader('validate');
  3236. $paths = $loader->getPaths('Zend_Foo_Validate');
  3237. $this->assertFalse(empty($paths), $element->getName() . ':' . var_export($loader->getPaths(), 1));
  3238. $this->assertContains('Foo', $paths[0]);
  3239. $this->assertContains('Validate', $paths[0]);
  3240. $paths = $element->getPluginLoader('filter')->getPaths('Zend_Foo_Filter');
  3241. $this->assertFalse(empty($paths));
  3242. $this->assertContains('Foo', $paths[0]);
  3243. $this->assertContains('Filter', $paths[0]);
  3244. $paths = $element->getPluginLoader('decorator')->getPaths('Zend_Foo_Decorator');
  3245. $this->assertFalse(empty($paths));
  3246. $this->assertContains('Foo', $paths[0]);
  3247. $this->assertContains('Decorator', $paths[0]);
  3248. }
  3249. }
  3250. public function testCustomGlobalElementPrefixPathUsedInNewlyCreatedElements()
  3251. {
  3252. $this->_checkZf2794();
  3253. $this->form->addElementPrefixPath('My_Decorator', dirname(__FILE__) . '/_files/decorators', 'decorator');
  3254. $this->form->addElement('text', 'prefixTest');
  3255. $element = $this->form->prefixTest;
  3256. $label = $element->getDecorator('Label');
  3257. $this->assertTrue($label instanceof My_Decorator_Label, get_class($label));
  3258. }
  3259. /**
  3260. * @group ZF-3093
  3261. */
  3262. public function testSettingElementPrefixPathPropagatesToAttachedSubForms()
  3263. {
  3264. $subForm = new Zend_Form_SubForm();
  3265. $subForm->addElement('text', 'foo');
  3266. $this->form->addSubForm($subForm, 'subForm');
  3267. $this->form->addElementPrefixPath('Zend_Foo', 'Zend/Foo/');
  3268. $loader = $this->form->subForm->foo->getPluginLoader('decorator');
  3269. $paths = $loader->getPaths('Zend_Foo_Decorator');
  3270. $this->assertFalse(empty($paths));
  3271. $this->assertContains('Foo', $paths[0]);
  3272. $this->assertContains('Decorator', $paths[0]);
  3273. }
  3274. public function testCanSetElementValidatorPrefixPath()
  3275. {
  3276. $this->setupElements();
  3277. $this->form->addElementPrefixPath('Zend_Foo', 'Zend/Foo/', 'validate');
  3278. $this->form->addElement('text', 'prefixTest');
  3279. foreach ($this->form->getElements() as $element) {
  3280. $loader = $element->getPluginLoader('validate');
  3281. $paths = $loader->getPaths('Zend_Foo');
  3282. $this->assertFalse(empty($paths));
  3283. $this->assertContains('Foo', $paths[0]);
  3284. $this->assertNotContains('Validate', $paths[0]);
  3285. }
  3286. }
  3287. public function testCanSetElementFilterPrefixPath()
  3288. {
  3289. $this->setupElements();
  3290. $this->form->addElementPrefixPath('Zend_Foo', 'Zend/Foo/', 'filter');
  3291. $this->form->addElement('text', 'prefixTest');
  3292. foreach ($this->form->getElements() as $element) {
  3293. $loader = $element->getPluginLoader('filter');
  3294. $paths = $loader->getPaths('Zend_Foo');
  3295. $this->assertFalse(empty($paths));
  3296. $this->assertContains('Foo', $paths[0]);
  3297. $this->assertNotContains('Filter', $paths[0]);
  3298. }
  3299. }
  3300. public function testCanSetElementDecoratorPrefixPath()
  3301. {
  3302. $this->setupElements();
  3303. $this->form->addElementPrefixPath('Zend_Foo', 'Zend/Foo/', 'decorator');
  3304. $this->form->addElement('text', 'prefixTest');
  3305. foreach ($this->form->getElements() as $element) {
  3306. $loader = $element->getPluginLoader('decorator');
  3307. $paths = $loader->getPaths('Zend_Foo');
  3308. $this->assertFalse(empty($paths));
  3309. $this->assertContains('Foo', $paths[0]);
  3310. $this->assertNotContains('Decorator', $paths[0]);
  3311. }
  3312. }
  3313. // Display Group decorators and plugin paths
  3314. public function setupDisplayGroups()
  3315. {
  3316. $this->testCanAddAndRetrieveMultipleElements();
  3317. $this->form->addElements(array(
  3318. 'test1' => 'text',
  3319. 'test2' => 'text',
  3320. 'test3' => 'text',
  3321. 'test4' => 'text'
  3322. ));
  3323. $this->form->addDisplayGroup(array('bar', 'bat'), 'barbat');
  3324. $this->form->addDisplayGroup(array('foo', 'baz'), 'foobaz');
  3325. }
  3326. public function testCanSetAllDisplayGroupDecoratorsAtOnce()
  3327. {
  3328. $this->_checkZf2794();
  3329. $this->setupDisplayGroups();
  3330. $this->form->setDisplayGroupDecorators(array(
  3331. array('Callback', array('callback' => 'strip_tags')),
  3332. ));
  3333. foreach ($this->form->getDisplayGroups() as $element) {
  3334. $this->assertFalse($element->getDecorator('FormElements'));
  3335. $this->assertFalse($element->getDecorator('HtmlTag'));
  3336. $this->assertFalse($element->getDecorator('Fieldset'));
  3337. $this->assertFalse($element->getDecorator('DtDdWrapper'));
  3338. $decorator = $element->getDecorator('Callback');
  3339. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Callback);
  3340. }
  3341. }
  3342. public function testCanSetDisplayGroupPrefixPath()
  3343. {
  3344. $this->setupDisplayGroups();
  3345. $this->form->addDisplayGroupPrefixPath('Zend_Foo', 'Zend/Foo/');
  3346. $this->form->addDisplayGroup(array('test1', 'test2'), 'testgroup');
  3347. foreach ($this->form->getDisplayGroups() as $group) {
  3348. $loader = $group->getPluginLoader();
  3349. $paths = $loader->getPaths('Zend_Foo');
  3350. $this->assertFalse(empty($paths));
  3351. $this->assertContains('Foo', $paths[0]);
  3352. }
  3353. }
  3354. /**
  3355. * @group ZF-3213
  3356. */
  3357. public function testShouldAllowSettingDisplayGroupPrefixPathViaConfigOptions()
  3358. {
  3359. require_once 'Zend/Config/Ini.php';
  3360. $config = new Zend_Config_Ini(dirname(__FILE__) . '/_files/config/zf3213.ini', 'form');
  3361. $form = new Zend_Form($config);
  3362. $dg = $form->foofoo;
  3363. $paths = $dg->getPluginLoader()->getPaths('My_Decorator');
  3364. $this->assertTrue($paths !== false);
  3365. }
  3366. // Subform decorators
  3367. public function testCanSetAllSubFormDecoratorsAtOnce()
  3368. {
  3369. $this->_checkZf2794();
  3370. $this->setupSubForm();
  3371. $this->form->setSubFormDecorators(array(
  3372. array('Callback', array('callback' => 'strip_tags')),
  3373. ));
  3374. foreach ($this->form->getSubForms() as $subForm) {
  3375. $this->assertFalse($subForm->getDecorator('FormElements'));
  3376. $this->assertFalse($subForm->getDecorator('HtmlTag'));
  3377. $this->assertFalse($subForm->getDecorator('Fieldset'));
  3378. $this->assertFalse($subForm->getDecorator('DtDdWrapper'));
  3379. $decorator = $subForm->getDecorator('Callback');
  3380. $this->assertTrue($decorator instanceof Zend_Form_Decorator_Callback);
  3381. }
  3382. }
  3383. // Extension
  3384. public function testInitCalledPriorToLoadingDefaultDecorators()
  3385. {
  3386. $form = new Zend_Form_FormTest_FormExtension();
  3387. $decorators = $form->getDecorators();
  3388. $this->assertTrue(empty($decorators));
  3389. }
  3390. // Clone
  3391. /**
  3392. * @group ZF-3819
  3393. */
  3394. public function testCloningShouldCloneAllChildren()
  3395. {
  3396. $form = new Zend_Form();
  3397. $foo = new Zend_Form_SubForm(array(
  3398. 'name' => 'foo',
  3399. 'elements' => array(
  3400. 'one' => 'text',
  3401. 'two' => 'text',
  3402. ),
  3403. ));
  3404. $form->addElement('text', 'bar')
  3405. ->addElement('text', 'baz')
  3406. ->addElement('text', 'bat')
  3407. ->addDisplayGroup(array('bar', 'bat'), 'barbat')
  3408. ->addSubForm($foo, 'foo');
  3409. $bar = $form->bar;
  3410. $baz = $form->baz;
  3411. $bat = $form->bat;
  3412. $barbat = $form->barbat;
  3413. $cloned = clone $form;
  3414. $this->assertNotSame($foo, $cloned->foo);
  3415. $this->assertNotSame($bar, $cloned->bar);
  3416. $this->assertNotSame($baz, $cloned->baz);
  3417. $this->assertNotSame($bat, $cloned->bat);
  3418. $this->assertNotSame($barbat, $cloned->getDisplayGroup('barbat'));
  3419. $this->assertNotSame($foo->one, $cloned->foo->one);
  3420. $this->assertNotSame($foo->two, $cloned->foo->two);
  3421. }
  3422. // Reset
  3423. /**
  3424. * @group ZF-3227
  3425. */
  3426. public function testFormsShouldAllowResetting()
  3427. {
  3428. $form = new Zend_Form();
  3429. $foo = new Zend_Form_SubForm(array(
  3430. 'name' => 'foo',
  3431. 'elements' => array(
  3432. 'one' => 'text',
  3433. 'two' => 'text',
  3434. ),
  3435. ));
  3436. $form->addElement('text', 'bar')
  3437. ->addElement('text', 'baz')
  3438. ->addElement('text', 'bat')
  3439. ->addDisplayGroup(array('bar', 'bat'), 'barbat')
  3440. ->addSubForm($foo, 'foo');
  3441. $values = array(
  3442. 'bar' => 'Bar Value',
  3443. 'baz' => 'Baz Value',
  3444. 'bat' => 'Bat Value',
  3445. 'foo' => array(
  3446. 'one' => 'One Value',
  3447. 'two' => 'Two Value',
  3448. ),
  3449. );
  3450. $form->populate($values);
  3451. $test = $form->getValues();
  3452. $this->assertEquals($values, $test);
  3453. $form->reset();
  3454. $test = $form->getValues();
  3455. $this->assertNotEquals($values, $test);
  3456. $this->assertEquals(0, array_sum($test));
  3457. }
  3458. /**
  3459. * @group ZF-3217
  3460. */
  3461. public function testFormShouldOverloadToRenderDecorators()
  3462. {
  3463. $this->setupElements();
  3464. $this->form->setView($this->getView());
  3465. $html = $this->form->renderFormElements();
  3466. foreach ($this->form->getElements() as $element) {
  3467. $this->assertContains('id="' . $element->getFullyQualifiedName() . '"', $html, 'Received: ' . $html);
  3468. }
  3469. $this->assertNotContains('<dl', $html);
  3470. $this->assertNotContains('<form', $html);
  3471. $html = $this->form->renderForm('this is the content');
  3472. $this->assertContains('<form', $html);
  3473. $this->assertContains('</form>', $html);
  3474. $this->assertContains('this is the content', $html);
  3475. }
  3476. /**
  3477. * @group ZF-3217
  3478. * @expectedException Zend_Form_Exception
  3479. */
  3480. public function testOverloadingToInvalidMethodsShouldThrowAnException()
  3481. {
  3482. $html = $this->form->bogusMethodCall();
  3483. }
  3484. /**
  3485. * @group ZF-2950
  3486. */
  3487. public function testDtDdElementsWithLabelGetUniqueId()
  3488. {
  3489. $form = new Zend_Form();
  3490. $form->setView($this->getView());
  3491. $fooElement = new Zend_Form_Element_Text('foo');
  3492. $fooElement->setLabel('Foo');
  3493. $form->addElement($fooElement);
  3494. $html = $form->render();
  3495. $this->assertContains('<dt id="foo-label">', $html);
  3496. $this->assertContains('<dd id="foo-element">', $html);
  3497. }
  3498. /**
  3499. * @group ZF-2950
  3500. */
  3501. public function testDtDdElementsWithoutLabelGetUniqueId()
  3502. {
  3503. $form = new Zend_Form();
  3504. $form->setView($this->getView())
  3505. ->addElement(new Zend_Form_Element_Text('foo'));
  3506. $html = $form->render();
  3507. $this->assertContains('<dt id="foo-label">&#160;</dt>', $html);
  3508. $this->assertContains('<dd id="foo-element">', $html);
  3509. }
  3510. /**
  3511. * @group ZF-2950
  3512. */
  3513. public function testSubFormGetsUniqueIdWithName()
  3514. {
  3515. $form = new Zend_Form();
  3516. $form->setView($this->getView())
  3517. ->setName('testform')
  3518. ->addSubForm(new Zend_Form_SubForm(), 'testform');
  3519. $html = $form->render();
  3520. $this->assertContains('<dt id="testform-label">&#160;</dt>', $html);
  3521. $this->assertContains('<dd id="testform-element">', $html);
  3522. }
  3523. /**
  3524. * @group ZF-5370
  3525. */
  3526. public function testEnctypeDefaultsToMultipartWhenFileElementIsAttachedToForm()
  3527. {
  3528. $file = new Zend_Form_Element_File('txt');
  3529. $this->form->addElement($file);
  3530. $html = $this->form->render($this->getView());
  3531. $this->assertFalse(empty($html));
  3532. $this->assertRegexp('#<form[^>]+enctype="multipart/form-data"#', $html);
  3533. }
  3534. /**
  3535. * @group ZF-5370
  3536. */
  3537. public function testEnctypeDefaultsToMultipartWhenFileElementIsAttachedToSubForm()
  3538. {
  3539. $subForm = new Zend_Form_SubForm();
  3540. $subForm->addElement('file', 'txt');
  3541. $this->form->addSubForm($subForm, 'page1')
  3542. ->setView(new Zend_View);
  3543. $html = $this->form->render();
  3544. $this->assertContains('id="txt"', $html);
  3545. $this->assertContains('name="txt"', $html);
  3546. $this->assertRegexp('#<form[^>]+enctype="multipart/form-data"#', $html, $html);
  3547. }
  3548. /**
  3549. * @group ZF-5370
  3550. */
  3551. public function testEnctypeDefaultsToMultipartWhenFileElementIsAttachedToDisplayGroup()
  3552. {
  3553. $this->form->addElement('file', 'txt')
  3554. ->addDisplayGroup(array('txt'), 'txtdisplay')
  3555. ->setView(new Zend_View);
  3556. $html = $this->form->render();
  3557. $this->assertContains('id="txt"', $html);
  3558. $this->assertContains('name="txt"', $html);
  3559. $this->assertRegexp('#<form[^>]+enctype="multipart/form-data"#', $html, $html);
  3560. }
  3561. /**
  3562. * @group ZF-6070
  3563. */
  3564. public function testIndividualElementDecoratorsShouldOverrideGlobalElementDecorators()
  3565. {
  3566. $this->form->setOptions(array(
  3567. 'elementDecorators' => array(
  3568. 'ViewHelper',
  3569. 'Label',
  3570. ),
  3571. 'elements' => array(
  3572. 'foo' => array(
  3573. 'type' => 'text',
  3574. 'options' => array(
  3575. 'decorators' => array(
  3576. 'Errors',
  3577. 'ViewHelper',
  3578. ),
  3579. ),
  3580. ),
  3581. ),
  3582. ));
  3583. $element = $this->form->getElement('foo');
  3584. $expected = array('Zend_Form_Decorator_Errors', 'Zend_Form_Decorator_ViewHelper');
  3585. $actual = array();
  3586. foreach ($element->getDecorators() as $decorator) {
  3587. $actual[] = get_class($decorator);
  3588. }
  3589. $this->assertSame($expected, $actual);
  3590. }
  3591. /**
  3592. * @group ZF-5150
  3593. */
  3594. public function testIsValidShouldFailIfAddErrorHasBeenCalled()
  3595. {
  3596. $this->form->addError('Error');
  3597. $this->assertFalse($this->form->isValid(array()));
  3598. }
  3599. /**
  3600. * @group ZF-8494
  3601. */
  3602. public function testGetValidValues()
  3603. {
  3604. $data = array('valid' => 1234, 'invalid' => 'invalid', 'noElement' => 'noElement');
  3605. require_once "Zend/Validate/Int.php";
  3606. $validElement = new Zend_Form_Element("valid");
  3607. $validElement->addValidator(new Zend_Validate_Int());
  3608. $this->form->addElement($validElement);
  3609. $invalidElement = new Zend_Form_Element('invalid');
  3610. $invalidElement->addValidator(new Zend_Validate_Int());
  3611. $this->form->addElement($invalidElement);
  3612. $this->assertEquals(array('valid' => 1234), $this->form->getValidValues($data));
  3613. }
  3614. /**
  3615. * @group ZF-8494
  3616. */
  3617. public function testGetValidSubFormValues()
  3618. {
  3619. $data = array('sub' => array('valid' => 1234, 'invalid' => 'invalid', 'noElement' => 'noElement'));
  3620. require_once "Zend/Validate/Int.php";
  3621. $subForm = new Zend_Form_SubForm();
  3622. $validElement = new Zend_Form_Element("valid");
  3623. $validElement->addValidator(new Zend_Validate_Int());
  3624. $subForm->addElement($validElement);
  3625. $invalidElement = new Zend_Form_Element('invalid');
  3626. $invalidElement->addValidator(new Zend_Validate_Int());
  3627. $subForm->addElement($invalidElement);
  3628. $this->form->addSubForm($subForm, 'sub');
  3629. $this->assertEquals(array('sub' => array('valid' => 1234)), $this->form->getValidValues($data));
  3630. }
  3631. /**
  3632. * @group ZF-9275
  3633. */
  3634. public function testElementTranslatorNotOverriddenbyGlobalTranslatorDuringValidation()
  3635. {
  3636. $translator = new Zend_Translate('array', array('foo' => 'bar'));
  3637. Zend_Registry::set('Zend_Translate', $translator);
  3638. $this->form->addElement('text', 'foo');
  3639. $this->form->isValid(array());
  3640. $received = $this->form->foo->hasTranslator();
  3641. $this->assertSame(false, $received);
  3642. }
  3643. /**
  3644. * @group ZF-9275
  3645. */
  3646. public function testZendValidateDefaultTranslatorOverridesZendTranslateDefaultTranslator()
  3647. {
  3648. $translate = new Zend_Translate('array', array('isEmpty' => 'translate'));
  3649. Zend_Registry::set('Zend_Translate', $translate);
  3650. $translateValidate = new Zend_Translate('array', array('isEmpty' => 'validate'));
  3651. Zend_Validate_Abstract::setDefaultTranslator($translateValidate);
  3652. $this->form->addElement('text', 'foo', array('required'=>1));
  3653. $this->form->isValid(array());
  3654. $this->assertSame(array('isEmpty' => 'validate'), $this->form->foo->getMessages());
  3655. }
  3656. /**
  3657. * @group ZF-9494
  3658. */
  3659. public function testElementTranslatorNotOveriddenbyFormTranslator()
  3660. {
  3661. $translations = array(
  3662. 'isEmpty' => 'Element message',
  3663. );
  3664. $translate = new Zend_Translate('array', $translations);
  3665. $this->form->addElement('text', 'foo', array('required'=>true, 'translator'=>$translate));
  3666. $this->assertFalse($this->form->isValid(array('foo'=>'')));
  3667. $messages = $this->form->getMessages();
  3668. $this->assertEquals(1, count($messages));
  3669. $this->assertEquals('Element message', $messages['foo']['isEmpty']);
  3670. $this->assertFalse($this->form->isValidPartial(array('foo'=>'')));
  3671. $messages = $this->form->getMessages();
  3672. $this->assertEquals(1, count($messages));
  3673. $this->assertEquals('Element message', $messages['foo']['isEmpty']);
  3674. }
  3675. /**
  3676. * @group ZF-9364
  3677. */
  3678. public function testElementTranslatorPreferredOverFormTranslator()
  3679. {
  3680. $formTanslations = array(
  3681. 'isEmpty' => 'Form message',
  3682. );
  3683. $elementTanslations = array(
  3684. 'isEmpty' => 'Element message',
  3685. );
  3686. $formTranslate = new Zend_Translate('array', $formTanslations);
  3687. $elementTranslate = new Zend_Translate('array', $elementTanslations);
  3688. $this->form->setTranslator($formTranslate);
  3689. $this->form->addElement('text', 'foo', array('required'=>true, 'translator'=>$elementTranslate));
  3690. $this->form->addElement('text', 'bar', array('required'=>true));
  3691. $this->assertFalse($this->form->isValid(array('foo'=>'', 'bar'=>'')));
  3692. $messages = $this->form->getMessages();
  3693. $this->assertEquals(2, count($messages));
  3694. $this->assertEquals('Element message', $messages['foo']['isEmpty']);
  3695. $this->assertEquals('Form message', $messages['bar']['isEmpty']);
  3696. $this->assertFalse($this->form->isValidPartial(array('foo'=>'', 'bar'=>'')));
  3697. $messages = $this->form->getMessages();
  3698. $this->assertEquals(2, count($messages));
  3699. $this->assertEquals('Element message', $messages['foo']['isEmpty']);
  3700. $this->assertEquals('Form message', $messages['bar']['isEmpty']);
  3701. }
  3702. /**
  3703. * @group ZF-9364
  3704. */
  3705. public function testElementTranslatorPreferredOverDefaultTranslator()
  3706. {
  3707. $defaultTranslations = array(
  3708. 'isEmpty' => 'Default message',
  3709. );
  3710. $formTranslations = array(
  3711. 'isEmpty' => 'Form message',
  3712. );
  3713. $elementTranslations = array(
  3714. 'isEmpty' => 'Element message',
  3715. );
  3716. $defaultTranslate = new Zend_Translate('array', $defaultTranslations);
  3717. $formTranslate = new Zend_Translate('array', $formTranslations);
  3718. $elementTranslate = new Zend_Translate('array', $elementTranslations);
  3719. Zend_Registry::set('Zend_Translate', $defaultTranslate);
  3720. $this->form->setTranslator($formTranslate);
  3721. $this->form->addElement('text', 'foo', array('required'=>true, 'translator'=>$elementTranslate));
  3722. $this->form->addElement('text', 'bar', array('required'=>true));
  3723. $this->assertFalse($this->form->isValid(array('foo'=>'', 'bar'=>'')));
  3724. $messages = $this->form->getMessages();
  3725. $this->assertEquals(2, count($messages));
  3726. $this->assertEquals('Element message', $messages['foo']['isEmpty']);
  3727. $this->assertEquals('Form message', $messages['bar']['isEmpty']);
  3728. $this->assertFalse($this->form->isValidPartial(array('foo'=>'', 'bar'=>'')));
  3729. $messages = $this->form->getMessages();
  3730. $this->assertEquals(2, count($messages));
  3731. $this->assertEquals('Element message', $messages['foo']['isEmpty']);
  3732. $this->assertEquals('Form message', $messages['bar']['isEmpty']);
  3733. }
  3734. /**
  3735. * @group ZF-9540
  3736. */
  3737. public function testSubFormTranslatorPreferredOverDefaultTranslator()
  3738. {
  3739. $defaultTranslations = array('isEmpty' => 'Default message');
  3740. $subformTranslations = array('isEmpty' => 'SubForm message');
  3741. $defaultTranslate = new Zend_Translate('array', $defaultTranslations);
  3742. $subformTranslate = new Zend_Translate('array', $subformTranslations);
  3743. Zend_Registry::set('Zend_Translate', $defaultTranslate);
  3744. $this->form->addSubForm(new Zend_Form_SubForm(), 'subform');
  3745. $this->form->subform->setTranslator($subformTranslate);
  3746. $this->form->subform->addElement('text', 'foo', array('required'=>true));
  3747. $this->assertFalse($this->form->isValid(array('subform' => array('foo'=>''))));
  3748. $messages = $this->form->getMessages();
  3749. $this->assertEquals('SubForm message', $messages['subform']['foo']['isEmpty']);
  3750. $this->assertFalse($this->form->isValidPartial(array('subform' => array('foo'=>''))));
  3751. $messages = $this->form->getMessages();
  3752. $this->assertEquals('SubForm message', $messages['subform']['foo']['isEmpty']);
  3753. }
  3754. /**
  3755. * Used by test methods susceptible to ZF-2794, marks a test as incomplete
  3756. *
  3757. * @link http://framework.zend.com/issues/browse/ZF-2794
  3758. * @return void
  3759. */
  3760. protected function _checkZf2794()
  3761. {
  3762. if (strtolower(substr(PHP_OS, 0, 3)) == 'win' && version_compare(PHP_VERSION, '5.1.4', '=')) {
  3763. $this->markTestIncomplete('Error occurs for PHP 5.1.4 on Windows');
  3764. }
  3765. }
  3766. /**
  3767. * Prove the fluent interface on Zend_Form::loadDefaultDecorators
  3768. *
  3769. * @link http://framework.zend.com/issues/browse/ZF-9913
  3770. * @return void
  3771. */
  3772. public function testFluentInterfaceOnLoadDefaultDecorators()
  3773. {
  3774. $this->assertSame($this->form, $this->form->loadDefaultDecorators());
  3775. }
  3776. /**
  3777. * @group ZF-7552
  3778. */
  3779. public function testAddDecoratorsKeepsNonNumericKeyNames()
  3780. {
  3781. $this->form->addDecorators(array(array(array('td' => 'HtmlTag'),
  3782. array('tag' => 'td')),
  3783. array(array('tr' => 'HtmlTag'),
  3784. array('tag' => 'tr')),
  3785. array('HtmlTag', array('tag' => 'baz'))));
  3786. $t1 = $this->form->getDecorators();
  3787. $this->form->setDecorators($t1);
  3788. $t2 = $this->form->getDecorators();
  3789. $this->assertEquals($t1, $t2);
  3790. }
  3791. /**
  3792. * @group ZF-10411
  3793. */
  3794. public function testAddingElementToDisplayGroupManuallyShouldPreventRenderingByForm()
  3795. {
  3796. $form = new Zend_Form_FormTest_AddToDisplayGroup();
  3797. $html = $form->render($this->getView());
  3798. $this->assertEquals(1, substr_count($html, 'Customer Type'), $html);
  3799. }
  3800. /**
  3801. * @group ZF-10491
  3802. * @group ZF-10734
  3803. * @group ZF-10731
  3804. */
  3805. public function testAddElementToDisplayGroupByElementInstance()
  3806. {
  3807. $element = new Zend_Form_Element_Text('foo');
  3808. $elementTwo = new Zend_Form_Element_Text('baz-----');
  3809. $this->form->addElements(array($element, $elementTwo));
  3810. $this->form->addDisplayGroup(array($element, $elementTwo), 'bar');
  3811. $displayGroup = $this->form->getDisplayGroup('bar');
  3812. $this->assertNotNull($displayGroup->getElement('foo'));
  3813. $this->assertNotNull($displayGroup->getElement('baz'));
  3814. // clear display groups and elements
  3815. $this->form->clearDisplayGroups()
  3816. ->clearElements();
  3817. $this->form->addDisplayGroup(array($element, $elementTwo), 'bar');
  3818. $displayGroup = $this->form->getDisplayGroup('bar');
  3819. $this->assertNotNull($displayGroup->getElement('foo'));
  3820. $this->assertNotNull($displayGroup->getElement('baz'));
  3821. }
  3822. /**
  3823. * @group ZF-10149
  3824. */
  3825. public function testIfViewIsSetInTime()
  3826. {
  3827. try {
  3828. $form = new Zend_Form(array('view' => new MyTestView()));
  3829. $this->assertTrue($form->getView() instanceof MyTestView);
  3830. $form = new Zend_Form(array('view' => new StdClass()));
  3831. $this->assertNull($form->getView());
  3832. $result = $form->render();
  3833. }
  3834. catch (Zend_Form_Exception $e) {
  3835. $this->fail('Setting a view object using the options array should not throw an exception');
  3836. }
  3837. $this->assertNotEquals($result,'');
  3838. }
  3839. /**
  3840. * @group ZF-11088
  3841. */
  3842. public function testAddErrorOnElementMakesFormInvalidAndReturnsCustomError()
  3843. {
  3844. $element = new Zend_Form_Element_Text('foo');
  3845. $errorString = 'This element made a booboo';
  3846. $element->addError($errorString);
  3847. $errorMessages = $element->getErrorMessages();
  3848. $this->assertSame(1, count($errorMessages));
  3849. $this->assertSame($errorString, $errorMessages[0]);
  3850. $element2 = new Zend_Form_Element_Text('bar');
  3851. $this->form->addElement($element2);
  3852. $this->form->getElement('bar')->addError($errorString);
  3853. $errorMessages2 = $this->form->getElement('bar')->getErrorMessages();
  3854. $this->assertSame(1, count($errorMessages2));
  3855. $this->assertSame($errorString, $errorMessages2[0]);
  3856. }
  3857. /**
  3858. * @group ZF-10865
  3859. * @expectedException Zend_Form_Exception
  3860. */
  3861. public function testExceptionThrownWhenAddElementsIsGivenNullValue()
  3862. {
  3863. $form = new Zend_Form();
  3864. $form->addElement(NULL);
  3865. }
  3866. /**
  3867. * @group ZF-11729
  3868. */
  3869. public function testDashSeparatedElementsInDisplayGroupsShouldNotRenderOutsideDisplayGroup()
  3870. {
  3871. $form = new Zend_Form();
  3872. $form->addElement('text', 'random-element-name', array(
  3873. 'label' => 'This is weird',
  3874. 'value' => 'think its a bug',
  3875. ));
  3876. $form->addDisplayGroup(array('random-element-name'), 'foobar', array(
  3877. 'legend' => 'foobar',
  3878. ));
  3879. $html = $form->render($this->getView());
  3880. $count = substr_count($html, 'randomelementname-element');
  3881. $this->assertEquals(1, $count, $html);
  3882. }
  3883. /**
  3884. * @group ZF-11831
  3885. */
  3886. public function testElementsOfSubFormReceiveCorrectDefaultTranslator()
  3887. {
  3888. // Global default translator
  3889. $trDefault = new Zend_Translate(array(
  3890. 'adapter' => 'array',
  3891. 'content' => array(
  3892. Zend_Validate_NotEmpty::IS_EMPTY => 'Default'
  3893. ),
  3894. 'locale' => 'en'
  3895. ));
  3896. Zend_Registry::set('Zend_Translate', $trDefault);
  3897. // Translator to use for elements
  3898. $trElement = new Zend_Translate(array(
  3899. 'adapter' => 'array',
  3900. 'content' => array(
  3901. Zend_Validate_NotEmpty::IS_EMPTY =>'Element'
  3902. ),
  3903. 'locale' => 'en'
  3904. ));
  3905. Zend_Validate_Abstract::setDefaultTranslator($trElement);
  3906. // Change the form's translator
  3907. $form = new Zend_Form();
  3908. $form->addElement(new Zend_Form_Element_Text('foo', array(
  3909. 'required' => true,
  3910. 'validators' => array('NotEmpty')
  3911. )));
  3912. // Create a subform with it's own validator
  3913. $sf1 = new Zend_Form_SubForm();
  3914. $sf1->addElement(new Zend_Form_Element_Text('foosub', array(
  3915. 'required' => true,
  3916. 'validators' => array('NotEmpty')
  3917. )));
  3918. $form->addSubForm($sf1, 'Test1');
  3919. $form->isValid(array());
  3920. $messages = $form->getMessages();
  3921. $this->assertEquals(
  3922. 'Element',
  3923. @$messages['foo'][Zend_Validate_NotEmpty::IS_EMPTY],
  3924. 'Form element received wrong validator'
  3925. );
  3926. $this->assertEquals(
  3927. 'Element',
  3928. @$messages['Test1']['foosub'][Zend_Validate_NotEmpty::IS_EMPTY],
  3929. 'SubForm element received wrong validator'
  3930. );
  3931. }
  3932. }
  3933. class Zend_Form_FormTest_DisplayGroup extends Zend_Form_DisplayGroup
  3934. {
  3935. }
  3936. class Zend_Form_FormTest_FormExtension extends Zend_Form
  3937. {
  3938. public function init()
  3939. {
  3940. $this->setDisableLoadDefaultDecorators(true);
  3941. }
  3942. }
  3943. class Zend_Form_FormTest_WithDisplayGroup extends Zend_Form
  3944. {
  3945. public function init()
  3946. {
  3947. $this->addElement('text', 'el1', array(
  3948. 'label' => 'Title',
  3949. 'required' => true,
  3950. ));
  3951. $this->addDisplayGroup(array('el1'), 'group1', array(
  3952. 'legend' => 'legend 1',
  3953. ));
  3954. }
  3955. }
  3956. class Zend_Form_FormTest_AddToDisplayGroup extends Zend_Form_FormTest_WithDisplayGroup
  3957. {
  3958. public function init()
  3959. {
  3960. parent::init();
  3961. $element = new Zend_Form_Element_Text('el2', array(
  3962. 'label' => 'Customer Type',
  3963. ));
  3964. $this->addElement($element);
  3965. $this->group1->addElement($element);
  3966. }
  3967. }
  3968. class MyTestView extends Zend_View
  3969. {
  3970. }
  3971. if (PHPUnit_MAIN_METHOD == 'Zend_Form_FormTest::main') {
  3972. Zend_Form_FormTest::main();
  3973. }