View source
<?php
namespace Drupal\FunctionalJavascriptTests\Ajax;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
class MultiFormTest extends WebDriverTestBase {
protected static $modules = [
'node',
'form_test',
];
protected $defaultTheme = 'stark';
protected function setUp() : void {
parent::setUp();
$this
->drupalCreateContentType([
'type' => 'page',
'name' => 'Page',
]);
$field_name = 'field_ajax_test';
FieldStorageConfig::create([
'entity_type' => 'node',
'field_name' => $field_name,
'type' => 'text',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
])
->save();
FieldConfig::create([
'field_name' => $field_name,
'entity_type' => 'node',
'bundle' => 'page',
])
->save();
\Drupal::service('entity_display.repository')
->getFormDisplay('node', 'page', 'default')
->setComponent($field_name, [
'type' => 'text_textfield',
])
->save();
$this
->drupalLogin($this
->drupalCreateUser([
'create page content',
]));
}
public function testMultiForm() {
$field_name = 'field_ajax_test';
$form_xpath = '//form[starts-with(@id, "node-page-form")]';
$field_xpath = '//div[contains(@class, "field--name-field-ajax-test")]';
$button_name = $field_name . '_add_more';
$button_value = t('Add another item');
$button_xpath_suffix = '//input[@name="' . $button_name . '"]';
$field_items_xpath_suffix = '//input[@type="text"]';
$this
->drupalGet('form-test/two-instances-of-same-form');
$this
->assertSession()
->assertWaitOnAjaxRequest();
$session = $this
->getSession();
$page = $session
->getPage();
$fields = $page
->findAll('xpath', $form_xpath . $field_xpath);
$this
->assertCount(2, $fields);
foreach ($fields as $field) {
$this
->assertCount(1, $field
->findAll('xpath', '.' . $field_items_xpath_suffix), 'Found the correct number of field items on the initial page.');
$this
->assertNotNull($field
->find('xpath', '.' . $button_xpath_suffix), 'Found the "add more" button on the initial page.');
}
$this
->assertSession()
->pageContainsNoDuplicateId();
for ($i = 0; $i < 2; $i++) {
$forms = $page
->find('xpath', $form_xpath);
foreach ($forms as $offset => $form) {
$button = $form
->findButton($button_value);
$this
->assertNotNull($button, 'Add Another Item button exists');
$button
->press();
$this
->assertSession()
->assertWaitOnAjaxRequest();
$page_updated = $session
->getPage();
$field = $page_updated
->findAll('xpath', '.' . $field_xpath);
$this
->assertCount($i + 2, $field[0]
->find('xpath', '.' . $field_items_xpath_suffix), 'Found the correct number of field items after an AJAX submission.');
$this
->assertNotNull($field[0]
->find('xpath', '.' . $button_xpath_suffix), 'Found the "add more" button after an AJAX submission.');
$this
->assertSession()
->pageContainsNoDuplicateId();
}
}
}
}