PageRenderTime 52ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/core/modules/field/src/Tests/FormTest.php

http://github.com/drupal/drupal
PHP | 691 lines | 470 code | 83 blank | 138 comment | 8 complexity | 8537bb6d6753495b5a7104bd679f5602 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  1. <?php
  2. namespace Drupal\field\Tests;
  3. use Drupal\Component\Utility\Html;
  4. use Drupal\Core\Entity\Entity\EntityFormDisplay;
  5. use Drupal\Core\Field\FieldStorageDefinitionInterface;
  6. use Drupal\Core\Form\FormState;
  7. use Drupal\entity_test\Entity\EntityTest;
  8. use Drupal\entity_test\Entity\EntityTestBaseFieldDisplay;
  9. use Drupal\field\Entity\FieldConfig;
  10. use Drupal\field\Entity\FieldStorageConfig;
  11. /**
  12. * Tests field form handling.
  13. *
  14. * @group field
  15. */
  16. class FormTest extends FieldTestBase {
  17. /**
  18. * Modules to enable.
  19. *
  20. * Locale is installed so that TranslatableMarkup actually does something.
  21. *
  22. * @var array
  23. */
  24. public static $modules = array('node', 'field_test', 'options', 'entity_test', 'locale');
  25. /**
  26. * An array of values defining a field single.
  27. *
  28. * @var array
  29. */
  30. protected $fieldStorageSingle;
  31. /**
  32. * An array of values defining a field multiple.
  33. *
  34. * @var array
  35. */
  36. protected $fieldStorageMultiple;
  37. /**
  38. * An array of values defining a field with unlimited cardinality.
  39. *
  40. * @var array
  41. */
  42. protected $fieldStorageUnlimited;
  43. /**
  44. * An array of values defining a field.
  45. *
  46. * @var array
  47. */
  48. protected $field;
  49. protected function setUp() {
  50. parent::setUp();
  51. $web_user = $this->drupalCreateUser(array('view test entity', 'administer entity_test content'));
  52. $this->drupalLogin($web_user);
  53. $this->fieldStorageSingle = array(
  54. 'field_name' => 'field_single',
  55. 'entity_type' => 'entity_test',
  56. 'type' => 'test_field',
  57. );
  58. $this->fieldStorageMultiple = array(
  59. 'field_name' => 'field_multiple',
  60. 'entity_type' => 'entity_test',
  61. 'type' => 'test_field',
  62. 'cardinality' => 4,
  63. );
  64. $this->fieldStorageUnlimited = array(
  65. 'field_name' => 'field_unlimited',
  66. 'entity_type' => 'entity_test',
  67. 'type' => 'test_field',
  68. 'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
  69. );
  70. $this->field = array(
  71. 'entity_type' => 'entity_test',
  72. 'bundle' => 'entity_test',
  73. 'label' => $this->randomMachineName() . '_label',
  74. 'description' => '[site:name]_description',
  75. 'weight' => mt_rand(0, 127),
  76. 'settings' => array(
  77. 'test_field_setting' => $this->randomMachineName(),
  78. ),
  79. );
  80. }
  81. function testFieldFormSingle() {
  82. $field_storage = $this->fieldStorageSingle;
  83. $field_name = $field_storage['field_name'];
  84. $this->field['field_name'] = $field_name;
  85. FieldStorageConfig::create($field_storage)->save();
  86. FieldConfig::create($this->field)->save();
  87. entity_get_form_display($this->field['entity_type'], $this->field['bundle'], 'default')
  88. ->setComponent($field_name)
  89. ->save();
  90. // Display creation form.
  91. $this->drupalGet('entity_test/add');
  92. // Create token value expected for description.
  93. $token_description = Html::escape($this->config('system.site')->get('name')) . '_description';
  94. $this->assertText($token_description, 'Token replacement for description is displayed');
  95. $this->assertFieldByName("{$field_name}[0][value]", '', 'Widget is displayed');
  96. $this->assertNoField("{$field_name}[1][value]", 'No extraneous widget is displayed');
  97. // Check that hook_field_widget_form_alter() does not believe this is the
  98. // default value form.
  99. $this->assertNoText('From hook_field_widget_form_alter(): Default form is true.', 'Not default value form in hook_field_widget_form_alter().');
  100. // Submit with invalid value (field-level validation).
  101. $edit = array(
  102. "{$field_name}[0][value]" => -1
  103. );
  104. $this->drupalPostForm(NULL, $edit, t('Save'));
  105. $this->assertRaw(t('%name does not accept the value -1.', array('%name' => $this->field['label'])), 'Field validation fails with invalid input.');
  106. // TODO : check that the correct field is flagged for error.
  107. // Create an entity
  108. $value = mt_rand(1, 127);
  109. $edit = array(
  110. "{$field_name}[0][value]" => $value,
  111. );
  112. $this->drupalPostForm(NULL, $edit, t('Save'));
  113. preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
  114. $id = $match[1];
  115. $this->assertText(t('entity_test @id has been created.', array('@id' => $id)), 'Entity was created');
  116. $entity = EntityTest::load($id);
  117. $this->assertEqual($entity->{$field_name}->value, $value, 'Field value was saved');
  118. // Display edit form.
  119. $this->drupalGet('entity_test/manage/' . $id . '/edit');
  120. $this->assertFieldByName("{$field_name}[0][value]", $value, 'Widget is displayed with the correct default value');
  121. $this->assertNoField("{$field_name}[1][value]", 'No extraneous widget is displayed');
  122. // Update the entity.
  123. $value = mt_rand(1, 127);
  124. $edit = array(
  125. "{$field_name}[0][value]" => $value,
  126. );
  127. $this->drupalPostForm(NULL, $edit, t('Save'));
  128. $this->assertText(t('entity_test @id has been updated.', array('@id' => $id)), 'Entity was updated');
  129. $this->container->get('entity.manager')->getStorage('entity_test')->resetCache(array($id));
  130. $entity = EntityTest::load($id);
  131. $this->assertEqual($entity->{$field_name}->value, $value, 'Field value was updated');
  132. // Empty the field.
  133. $value = '';
  134. $edit = array(
  135. "{$field_name}[0][value]" => $value
  136. );
  137. $this->drupalPostForm('entity_test/manage/' . $id . '/edit', $edit, t('Save'));
  138. $this->assertText(t('entity_test @id has been updated.', array('@id' => $id)), 'Entity was updated');
  139. $this->container->get('entity.manager')->getStorage('entity_test')->resetCache(array($id));
  140. $entity = EntityTest::load($id);
  141. $this->assertTrue($entity->{$field_name}->isEmpty(), 'Field was emptied');
  142. }
  143. /**
  144. * Tests field widget default values on entity forms.
  145. */
  146. function testFieldFormDefaultValue() {
  147. $field_storage = $this->fieldStorageSingle;
  148. $field_name = $field_storage['field_name'];
  149. $this->field['field_name'] = $field_name;
  150. $default = rand(1, 127);
  151. $this->field['default_value'] = array(array('value' => $default));
  152. FieldStorageConfig::create($field_storage)->save();
  153. FieldConfig::create($this->field)->save();
  154. entity_get_form_display($this->field['entity_type'], $this->field['bundle'], 'default')
  155. ->setComponent($field_name)
  156. ->save();
  157. // Display creation form.
  158. $this->drupalGet('entity_test/add');
  159. // Test that the default value is displayed correctly.
  160. $this->assertFieldByXpath("//input[@name='{$field_name}[0][value]' and @value='$default']");
  161. // Try to submit an empty value.
  162. $edit = array(
  163. "{$field_name}[0][value]" => '',
  164. );
  165. $this->drupalPostForm(NULL, $edit, t('Save'));
  166. preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
  167. $id = $match[1];
  168. $this->assertText(t('entity_test @id has been created.', array('@id' => $id)), 'Entity was created.');
  169. $entity = EntityTest::load($id);
  170. $this->assertTrue($entity->{$field_name}->isEmpty(), 'Field is now empty.');
  171. }
  172. function testFieldFormSingleRequired() {
  173. $field_storage = $this->fieldStorageSingle;
  174. $field_name = $field_storage['field_name'];
  175. $this->field['field_name'] = $field_name;
  176. $this->field['required'] = TRUE;
  177. FieldStorageConfig::create($field_storage)->save();
  178. FieldConfig::create($this->field)->save();
  179. entity_get_form_display($this->field['entity_type'], $this->field['bundle'], 'default')
  180. ->setComponent($field_name)
  181. ->save();
  182. // Submit with missing required value.
  183. $edit = array();
  184. $this->drupalPostForm('entity_test/add', $edit, t('Save'));
  185. $this->assertRaw(t('@name field is required.', array('@name' => $this->field['label'])), 'Required field with no value fails validation');
  186. // Create an entity
  187. $value = mt_rand(1, 127);
  188. $edit = array(
  189. "{$field_name}[0][value]" => $value,
  190. );
  191. $this->drupalPostForm(NULL, $edit, t('Save'));
  192. preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
  193. $id = $match[1];
  194. $this->assertText(t('entity_test @id has been created.', array('@id' => $id)), 'Entity was created');
  195. $entity = EntityTest::load($id);
  196. $this->assertEqual($entity->{$field_name}->value, $value, 'Field value was saved');
  197. // Edit with missing required value.
  198. $value = '';
  199. $edit = array(
  200. "{$field_name}[0][value]" => $value,
  201. );
  202. $this->drupalPostForm('entity_test/manage/' . $id . '/edit', $edit, t('Save'));
  203. $this->assertRaw(t('@name field is required.', array('@name' => $this->field['label'])), 'Required field with no value fails validation');
  204. }
  205. function testFieldFormUnlimited() {
  206. $field_storage = $this->fieldStorageUnlimited;
  207. $field_name = $field_storage['field_name'];
  208. $this->field['field_name'] = $field_name;
  209. FieldStorageConfig::create($field_storage)->save();
  210. FieldConfig::create($this->field)->save();
  211. entity_get_form_display($this->field['entity_type'], $this->field['bundle'], 'default')
  212. ->setComponent($field_name)
  213. ->save();
  214. // Display creation form -> 1 widget.
  215. $this->drupalGet('entity_test/add');
  216. $this->assertFieldByName("{$field_name}[0][value]", '', 'Widget 1 is displayed');
  217. $this->assertNoField("{$field_name}[1][value]", 'No extraneous widget is displayed');
  218. // Check if aria-describedby attribute is placed on multiple value widgets.
  219. $elements = $this->xpath('//table[@id="field-unlimited-values" and @aria-describedby="edit-field-unlimited--description"]');
  220. $this->assertTrue(isset($elements[0]), t('aria-describedby attribute is properly placed on multiple value widgets.'));
  221. // Press 'add more' button -> 2 widgets.
  222. $this->drupalPostForm(NULL, array(), t('Add another item'));
  223. $this->assertFieldByName("{$field_name}[0][value]", '', 'Widget 1 is displayed');
  224. $this->assertFieldByName("{$field_name}[1][value]", '', 'New widget is displayed');
  225. $this->assertNoField("{$field_name}[2][value]", 'No extraneous widget is displayed');
  226. // TODO : check that non-field inputs are preserved ('title'), etc.
  227. // Yet another time so that we can play with more values -> 3 widgets.
  228. $this->drupalPostForm(NULL, array(), t('Add another item'));
  229. // Prepare values and weights.
  230. $count = 3;
  231. $delta_range = $count - 1;
  232. $values = $weights = $pattern = $expected_values = array();
  233. $edit = array();
  234. for ($delta = 0; $delta <= $delta_range; $delta++) {
  235. // Assign unique random values and weights.
  236. do {
  237. $value = mt_rand(1, 127);
  238. } while (in_array($value, $values));
  239. do {
  240. $weight = mt_rand(-$delta_range, $delta_range);
  241. } while (in_array($weight, $weights));
  242. $edit["{$field_name}[$delta][value]"] = $value;
  243. $edit["{$field_name}[$delta][_weight]"] = $weight;
  244. // We'll need three slightly different formats to check the values.
  245. $values[$delta] = $value;
  246. $weights[$delta] = $weight;
  247. $field_values[$weight]['value'] = (string) $value;
  248. $pattern[$weight] = "<input [^>]*value=\"$value\" [^>]*";
  249. }
  250. // Press 'add more' button -> 4 widgets
  251. $this->drupalPostForm(NULL, $edit, t('Add another item'));
  252. for ($delta = 0; $delta <= $delta_range; $delta++) {
  253. $this->assertFieldByName("{$field_name}[$delta][value]", $values[$delta], "Widget $delta is displayed and has the right value");
  254. $this->assertFieldByName("{$field_name}[$delta][_weight]", $weights[$delta], "Widget $delta has the right weight");
  255. }
  256. ksort($pattern);
  257. $pattern = implode('.*', array_values($pattern));
  258. $this->assertPattern("|$pattern|s", 'Widgets are displayed in the correct order');
  259. $this->assertFieldByName("{$field_name}[$delta][value]", '', "New widget is displayed");
  260. $this->assertFieldByName("{$field_name}[$delta][_weight]", $delta, "New widget has the right weight");
  261. $this->assertNoField("{$field_name}[" . ($delta + 1) . '][value]', 'No extraneous widget is displayed');
  262. // Submit the form and create the entity.
  263. $this->drupalPostForm(NULL, $edit, t('Save'));
  264. preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
  265. $id = $match[1];
  266. $this->assertText(t('entity_test @id has been created.', array('@id' => $id)), 'Entity was created');
  267. $entity = EntityTest::load($id);
  268. ksort($field_values);
  269. $field_values = array_values($field_values);
  270. $this->assertIdentical($entity->{$field_name}->getValue(), $field_values, 'Field values were saved in the correct order');
  271. // Display edit form: check that the expected number of widgets is
  272. // displayed, with correct values change values, reorder, leave an empty
  273. // value in the middle.
  274. // Submit: check that the entity is updated with correct values
  275. // Re-submit: check that the field can be emptied.
  276. // Test with several multiple fields in a form
  277. }
  278. /**
  279. * Tests the position of the required label.
  280. */
  281. public function testFieldFormUnlimitedRequired() {
  282. $field_name = $this->fieldStorageUnlimited['field_name'];
  283. $this->field['field_name'] = $field_name;
  284. $this->field['required'] = TRUE;
  285. FieldStorageConfig::create($this->fieldStorageUnlimited)->save();
  286. FieldConfig::create($this->field)->save();
  287. entity_get_form_display($this->field['entity_type'], $this->field['bundle'], 'default')
  288. ->setComponent($field_name)
  289. ->save();
  290. // Display creation form -> 1 widget.
  291. $this->drupalGet('entity_test/add');
  292. // Check that the Required symbol is present for the multifield label.
  293. $element = $this->xpath('//h4[contains(@class, "label") and contains(@class, "js-form-required") and contains(text(), :value)]', array(':value' => $this->field['label']));
  294. $this->assertTrue(isset($element[0]), 'Required symbol added field label.');
  295. // Check that the label of the field input is visually hidden and contains
  296. // the field title and an indication of the delta for a11y.
  297. $element = $this->xpath('//label[@for=:for and contains(@class, "js-form-required") and contains(text(), :value)]', array(':for' => 'edit-field-unlimited-0-value', ':value' => $this->field['label'] . ' (value 1)'));
  298. $this->assertTrue(isset($element[0]), 'Required symbol not added for field input.');
  299. }
  300. /**
  301. * Tests widget handling of multiple required radios.
  302. */
  303. function testFieldFormMultivalueWithRequiredRadio() {
  304. // Create a multivalue test field.
  305. $field_storage = $this->fieldStorageUnlimited;
  306. $field_name = $field_storage['field_name'];
  307. $this->field['field_name'] = $field_name;
  308. FieldStorageConfig::create($field_storage)->save();
  309. FieldConfig::create($this->field)->save();
  310. entity_get_form_display($this->field['entity_type'], $this->field['bundle'], 'default')
  311. ->setComponent($field_name)
  312. ->save();
  313. // Add a required radio field.
  314. FieldStorageConfig::create(array(
  315. 'field_name' => 'required_radio_test',
  316. 'entity_type' => 'entity_test',
  317. 'type' => 'list_string',
  318. 'settings' => array(
  319. 'allowed_values' => array('yes' => 'yes', 'no' => 'no'),
  320. ),
  321. ))->save();
  322. $field = array(
  323. 'field_name' => 'required_radio_test',
  324. 'entity_type' => 'entity_test',
  325. 'bundle' => 'entity_test',
  326. 'required' => TRUE,
  327. );
  328. FieldConfig::create($field)->save();
  329. entity_get_form_display($field['entity_type'], $field['bundle'], 'default')
  330. ->setComponent($field['field_name'], array(
  331. 'type' => 'options_buttons',
  332. ))
  333. ->save();
  334. // Display creation form.
  335. $this->drupalGet('entity_test/add');
  336. // Press the 'Add more' button.
  337. $this->drupalPostForm(NULL, array(), t('Add another item'));
  338. // Verify that no error is thrown by the radio element.
  339. $this->assertNoFieldByXpath('//div[contains(@class, "error")]', FALSE, 'No error message is displayed.');
  340. // Verify that the widget is added.
  341. $this->assertFieldByName("{$field_name}[0][value]", '', 'Widget 1 is displayed');
  342. $this->assertFieldByName("{$field_name}[1][value]", '', 'New widget is displayed');
  343. $this->assertNoField("{$field_name}[2][value]", 'No extraneous widget is displayed');
  344. }
  345. function testFieldFormJSAddMore() {
  346. $field_storage = $this->fieldStorageUnlimited;
  347. $field_name = $field_storage['field_name'];
  348. $this->field['field_name'] = $field_name;
  349. FieldStorageConfig::create($field_storage)->save();
  350. FieldConfig::create($this->field)->save();
  351. entity_get_form_display($this->field['entity_type'], $this->field['bundle'], 'default')
  352. ->setComponent($field_name)
  353. ->save();
  354. // Display creation form -> 1 widget.
  355. $this->drupalGet('entity_test/add');
  356. // Press 'add more' button a couple times -> 3 widgets.
  357. // drupalPostAjaxForm() will not work iteratively, so we add those through
  358. // non-JS submission.
  359. $this->drupalPostForm(NULL, array(), t('Add another item'));
  360. $this->drupalPostForm(NULL, array(), t('Add another item'));
  361. // Prepare values and weights.
  362. $count = 3;
  363. $delta_range = $count - 1;
  364. $values = $weights = $pattern = $expected_values = $edit = array();
  365. for ($delta = 0; $delta <= $delta_range; $delta++) {
  366. // Assign unique random values and weights.
  367. do {
  368. $value = mt_rand(1, 127);
  369. } while (in_array($value, $values));
  370. do {
  371. $weight = mt_rand(-$delta_range, $delta_range);
  372. } while (in_array($weight, $weights));
  373. $edit["{$field_name}[$delta][value]"] = $value;
  374. $edit["{$field_name}[$delta][_weight]"] = $weight;
  375. // We'll need three slightly different formats to check the values.
  376. $values[$delta] = $value;
  377. $weights[$delta] = $weight;
  378. $field_values[$weight]['value'] = (string) $value;
  379. $pattern[$weight] = "<input [^>]*value=\"$value\" [^>]*";
  380. }
  381. // Press 'add more' button through Ajax, and place the expected HTML result
  382. // as the tested content.
  383. $commands = $this->drupalPostAjaxForm(NULL, $edit, $field_name . '_add_more');
  384. $this->setRawContent($commands[2]['data']);
  385. for ($delta = 0; $delta <= $delta_range; $delta++) {
  386. $this->assertFieldByName("{$field_name}[$delta][value]", $values[$delta], "Widget $delta is displayed and has the right value");
  387. $this->assertFieldByName("{$field_name}[$delta][_weight]", $weights[$delta], "Widget $delta has the right weight");
  388. }
  389. ksort($pattern);
  390. $pattern = implode('.*', array_values($pattern));
  391. $this->assertPattern("|$pattern|s", 'Widgets are displayed in the correct order');
  392. $this->assertFieldByName("{$field_name}[$delta][value]", '', "New widget is displayed");
  393. $this->assertFieldByName("{$field_name}[$delta][_weight]", $delta, "New widget has the right weight");
  394. $this->assertNoField("{$field_name}[" . ($delta + 1) . '][value]', 'No extraneous widget is displayed');
  395. }
  396. /**
  397. * Tests widgets handling multiple values.
  398. */
  399. function testFieldFormMultipleWidget() {
  400. // Create a field with fixed cardinality, configure the form to use a
  401. // "multiple" widget.
  402. $field_storage = $this->fieldStorageMultiple;
  403. $field_name = $field_storage['field_name'];
  404. $this->field['field_name'] = $field_name;
  405. FieldStorageConfig::create($field_storage)->save();
  406. FieldConfig::create($this->field)->save();
  407. entity_get_form_display($this->field['entity_type'], $this->field['bundle'], 'default')
  408. ->setComponent($field_name, array(
  409. 'type' => 'test_field_widget_multiple',
  410. ))
  411. ->save();
  412. // Display creation form.
  413. $this->drupalGet('entity_test/add');
  414. $this->assertFieldByName($field_name, '', 'Widget is displayed.');
  415. // Create entity with three values.
  416. $edit = array(
  417. $field_name => '1, 2, 3',
  418. );
  419. $this->drupalPostForm(NULL, $edit, t('Save'));
  420. preg_match('|entity_test/manage/(\d+)|', $this->url, $match);
  421. $id = $match[1];
  422. // Check that the values were saved.
  423. $entity_init = EntityTest::load($id);
  424. $this->assertFieldValues($entity_init, $field_name, array(1, 2, 3));
  425. // Display the form, check that the values are correctly filled in.
  426. $this->drupalGet('entity_test/manage/' . $id . '/edit');
  427. $this->assertFieldByName($field_name, '1, 2, 3', 'Widget is displayed.');
  428. // Submit the form with more values than the field accepts.
  429. $edit = array($field_name => '1, 2, 3, 4, 5');
  430. $this->drupalPostForm(NULL, $edit, t('Save'));
  431. $this->assertRaw('this field cannot hold more than 4 values', 'Form validation failed.');
  432. // Check that the field values were not submitted.
  433. $this->assertFieldValues($entity_init, $field_name, array(1, 2, 3));
  434. }
  435. /**
  436. * Tests fields with no 'edit' access.
  437. */
  438. function testFieldFormAccess() {
  439. $entity_type = 'entity_test_rev';
  440. // Create a "regular" field.
  441. $field_storage = $this->fieldStorageSingle;
  442. $field_storage['entity_type'] = $entity_type;
  443. $field_name = $field_storage['field_name'];
  444. $field = $this->field;
  445. $field['field_name'] = $field_name;
  446. $field['entity_type'] = $entity_type;
  447. $field['bundle'] = $entity_type;
  448. FieldStorageConfig::create($field_storage)->save();
  449. FieldConfig::create($field)->save();
  450. entity_get_form_display($entity_type, $entity_type, 'default')
  451. ->setComponent($field_name)
  452. ->save();
  453. // Create a field with no edit access. See
  454. // field_test_entity_field_access().
  455. $field_storage_no_access = array(
  456. 'field_name' => 'field_no_edit_access',
  457. 'entity_type' => $entity_type,
  458. 'type' => 'test_field',
  459. );
  460. $field_name_no_access = $field_storage_no_access['field_name'];
  461. $field_no_access = array(
  462. 'field_name' => $field_name_no_access,
  463. 'entity_type' => $entity_type,
  464. 'bundle' => $entity_type,
  465. 'default_value' => array(0 => array('value' => 99)),
  466. );
  467. FieldStorageConfig::create($field_storage_no_access)->save();
  468. FieldConfig::create($field_no_access)->save();
  469. entity_get_form_display($field_no_access['entity_type'], $field_no_access['bundle'], 'default')
  470. ->setComponent($field_name_no_access)
  471. ->save();
  472. // Test that the form structure includes full information for each delta
  473. // apart from #access.
  474. $entity = $this->container->get('entity_type.manager')
  475. ->getStorage($entity_type)
  476. ->create(array('id' => 0, 'revision_id' => 0));
  477. $display = entity_get_form_display($entity_type, $entity_type, 'default');
  478. $form = array();
  479. $form_state = new FormState();
  480. $display->buildForm($entity, $form, $form_state);
  481. $this->assertFalse($form[$field_name_no_access]['#access'], 'Field #access is FALSE for the field without edit access.');
  482. // Display creation form.
  483. $this->drupalGet($entity_type . '/add');
  484. $this->assertNoFieldByName("{$field_name_no_access}[0][value]", '', 'Widget is not displayed if field access is denied.');
  485. // Create entity.
  486. $edit = array(
  487. "{$field_name}[0][value]" => 1,
  488. );
  489. $this->drupalPostForm(NULL, $edit, t('Save'));
  490. preg_match("|$entity_type/manage/(\d+)|", $this->url, $match);
  491. $id = $match[1];
  492. // Check that the default value was saved.
  493. $storage = $this->container->get('entity_type.manager')
  494. ->getStorage($entity_type);
  495. $entity = $storage->load($id);
  496. $this->assertEqual($entity->$field_name_no_access->value, 99, 'Default value was saved for the field with no edit access.');
  497. $this->assertEqual($entity->$field_name->value, 1, 'Entered value vas saved for the field with edit access.');
  498. // Create a new revision.
  499. $edit = array(
  500. "{$field_name}[0][value]" => 2,
  501. 'revision' => TRUE,
  502. );
  503. $this->drupalPostForm($entity_type . '/manage/' . $id . '/edit', $edit, t('Save'));
  504. // Check that the new revision has the expected values.
  505. $storage->resetCache([$id]);
  506. $entity = $storage->load($id);
  507. $this->assertEqual($entity->$field_name_no_access->value, 99, 'New revision has the expected value for the field with no edit access.');
  508. $this->assertEqual($entity->$field_name->value, 2, 'New revision has the expected value for the field with edit access.');
  509. // Check that the revision is also saved in the revisions table.
  510. // $entity = entity_revision_load($entity_type, $entity->getRevisionId());
  511. $this->assertEqual($entity->$field_name_no_access->value, 99, 'New revision has the expected value for the field with no edit access.');
  512. $this->assertEqual($entity->$field_name->value, 2, 'New revision has the expected value for the field with edit access.');
  513. }
  514. /**
  515. * Tests hiding a field in a form.
  516. */
  517. function testHiddenField() {
  518. $entity_type = 'entity_test_rev';
  519. $field_storage = $this->fieldStorageSingle;
  520. $field_storage['entity_type'] = $entity_type;
  521. $field_name = $field_storage['field_name'];
  522. $this->field['field_name'] = $field_name;
  523. $this->field['default_value'] = array(0 => array('value' => 99));
  524. $this->field['entity_type'] = $entity_type;
  525. $this->field['bundle'] = $entity_type;
  526. FieldStorageConfig::create($field_storage)->save();
  527. $this->field = FieldConfig::create($this->field);
  528. $this->field->save();
  529. // We explicitly do not assign a widget in a form display, so the field
  530. // stays hidden in forms.
  531. // Display the entity creation form.
  532. $this->drupalGet($entity_type . '/add');
  533. // Create an entity and test that the default value is assigned correctly to
  534. // the field that uses the hidden widget.
  535. $this->assertNoField("{$field_name}[0][value]", 'The field does not appear in the form');
  536. $this->drupalPostForm(NULL, array(), t('Save'));
  537. preg_match('|' . $entity_type . '/manage/(\d+)|', $this->url, $match);
  538. $id = $match[1];
  539. $this->assertText(t('entity_test_rev @id has been created.', array('@id' => $id)), 'Entity was created');
  540. $storage = $this->container->get('entity_type.manager')
  541. ->getStorage($entity_type);
  542. $entity = $storage->load($id);
  543. $this->assertEqual($entity->{$field_name}->value, 99, 'Default value was saved');
  544. // Update the field to remove the default value, and switch to the default
  545. // widget.
  546. $this->field->setDefaultValue(array());
  547. $this->field->save();
  548. entity_get_form_display($entity_type, $this->field->getTargetBundle(), 'default')
  549. ->setComponent($this->field->getName(), array(
  550. 'type' => 'test_field_widget',
  551. ))
  552. ->save();
  553. // Display edit form.
  554. $this->drupalGet($entity_type . '/manage/' . $id . '/edit');
  555. $this->assertFieldByName("{$field_name}[0][value]", 99, 'Widget is displayed with the correct default value');
  556. // Update the entity.
  557. $value = mt_rand(1, 127);
  558. $edit = array("{$field_name}[0][value]" => $value);
  559. $this->drupalPostForm(NULL, $edit, t('Save'));
  560. $this->assertText(t('entity_test_rev @id has been updated.', array('@id' => $id)), 'Entity was updated');
  561. $storage->resetCache([$id]);
  562. $entity = $storage->load($id);
  563. $this->assertEqual($entity->{$field_name}->value, $value, 'Field value was updated');
  564. // Set the field back to hidden.
  565. entity_get_form_display($entity_type, $this->field->getTargetBundle(), 'default')
  566. ->removeComponent($this->field->getName())
  567. ->save();
  568. // Create a new revision.
  569. $edit = array('revision' => TRUE);
  570. $this->drupalPostForm($entity_type . '/manage/' . $id . '/edit', $edit, t('Save'));
  571. // Check that the expected value has been carried over to the new revision.
  572. $storage->resetCache(array($id));
  573. $entity = $storage->load($id);
  574. $this->assertEqual($entity->{$field_name}->value, $value, 'New revision has the expected value for the field with the Hidden widget');
  575. }
  576. /**
  577. * Tests the form display of the label for multi-value fields.
  578. */
  579. public function testLabelOnMultiValueFields() {
  580. $user = $this->drupalCreateUser(['administer entity_test content']);
  581. $this->drupalLogin($user);
  582. FieldStorageConfig::create([
  583. 'entity_type' => 'entity_test_base_field_display',
  584. 'field_name' => 'foo',
  585. 'type' => 'text',
  586. 'cardinality' => FieldStorageConfig::CARDINALITY_UNLIMITED,
  587. ])->save();
  588. FieldConfig::create([
  589. 'entity_type' => 'entity_test_base_field_display',
  590. 'bundle' => 'bar',
  591. 'field_name' => 'foo',
  592. // Set a dangerous label to test XSS filtering.
  593. 'label' => "<script>alert('a configurable field');</script>",
  594. ])->save();
  595. EntityFormDisplay::create([
  596. 'targetEntityType' => 'entity_test_base_field_display',
  597. 'bundle' => 'bar',
  598. 'mode' => 'default',
  599. ])->setComponent('foo', ['type' => 'text_textfield'])->enable()->save();
  600. $entity = EntityTestBaseFieldDisplay::create(['type' => 'bar']);
  601. $entity->save();
  602. $this->drupalGet('entity_test_base_field_display/manage/' . $entity->id());
  603. $this->assertResponse(200);
  604. $this->assertText('A field with multiple values');
  605. // Test if labels were XSS filtered.
  606. $this->assertEscaped("<script>alert('a configurable field');</script>");
  607. }
  608. }