crm_core-8.x-3.x-dev/modules/crm_core_contact/tests/src/Functional/OrganizationEditFormTest.php
modules/crm_core_contact/tests/src/Functional/OrganizationEditFormTest.php
<?php
namespace Drupal\Tests\crm_core_contact\Functional;
use Drupal\crm_core_contact\OrganizationInterface;
use Drupal\user\Entity\User;
/**
* Create an organization and test organization edit functionality.
*
* @group crm_core
*/
class OrganizationEditFormTest extends ContactTestBase {
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* A normal logged in user.
*
* @var \Drupal\user\UserInterface
*/
protected $webUser;
/**
* A user with permission to bypass content access checks.
*
* @var \Drupal\user\UserInterface
*/
protected $adminUser;
/**
* The organization storage.
*
* @var \Drupal\Core\Entity\Sql\SqlContentEntityStorage
*/
protected $organizationStorage;
/**
* Modules to enable.
*
* @var string[]
*/
protected static $modules = ['block', 'crm_core_contact', 'datetime'];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->webUser = $this->drupalCreateUser([
'view any crm_core_organization entity of bundle company',
'edit any crm_core_organization entity of bundle company',
'create crm_core_organization entities of bundle company',
]);
$this->adminUser = $this->drupalCreateUser([
'administer crm_core_organization entities',
]);
$this->drupalPlaceBlock('local_tasks_block');
$this->organizationStorage = $this->container->get('entity_type.manager')->getStorage('crm_core_organization');
}
/**
* Checks organization edit functionality.
*/
public function testOrganizationEdit() {
$this->drupalLogin($this->webUser);
$name_key = 'name[0][value]';
// Create organization to edit.
$edit = [];
$edit[$name_key] = $this->randomMachineName(8);
$this->drupalGet('crm-core/organization/add/company');
$this->submitForm($edit, 'Save Company');
// Check that the organization exists in the database.
$organization = $this->drupalGetOrganizationByName($edit[$name_key]);
$this->assertNotEmpty($organization, 'Organization found in database.');
// Check that "edit" link points to correct page.
$this->clickLink('Edit');
$this->assertSession()->addressEquals($organization->toUrl('edit-form'));
// Check that the name field is displayed with the correct values.
$this->assertSession()->fieldValueEquals($name_key, $edit[$name_key]);
// Edit the content of the organization.
$edit = [];
$edit[$name_key] = $this->randomMachineName(8);
// Stay on the current page, without reloading.
$this->submitForm($edit, 'Save Company');
// Check that the name field is displayed with the updated values.
$this->assertSession()->pageTextContains($edit[$name_key]);
// Log in as a second administrator user.
$second_web_user = $this->drupalCreateUser([
'administer crm_core_organization entities',
'edit any crm_core_organization entity',
]);
$this->drupalLogin($second_web_user);
// Edit the same organization, creating a new revision.
$this->drupalGet("crm-core/organization/" . $organization->id() . "/edit");
$edit = [];
$edit['name[0][value]'] = $this->randomMachineName(8);
$edit['revision'] = TRUE;
$this->submitForm($edit, 'Save Company');
// Ensure that the organization revision has been created.
$revised_organization = $this->drupalGetOrganizationByName($edit['name[0][value]'], TRUE);
$this->assertNotSame($organization->getRevisionId(), $revised_organization->getRevisionId(), 'A new revision has been created.');
// Ensure that the organization owner is preserved when it was not changed
// in the edit form.
$this->assertSame($organization->getOwnerId(), $revised_organization->getOwnerId(), 'The organization owner has been preserved.');
// Ensure that the revision authors are different since the revisions were
// made by different users.
$first_organization_version = $this->organizationStorage->loadRevision($organization->getRevisionId());
$second_organization_version = $this->organizationStorage->loadRevision($revised_organization->getRevisionId());
$this->assertNotSame($first_organization_version->getRevisionUser()->id(), $second_organization_version->getRevisionUser()->id(), 'Each revision has a distinct user.');
// Check if the organization revision checkbox is rendered on edit form.
$this->drupalGet('crm-core/organization/' . $organization->id() . '/edit');
$this->assertSession()->fieldExists('edit-revision');
// Check that details form element opens when there are errors on child
// elements.
$this->drupalGet('crm-core/organization/' . $organization->id() . '/edit');
$edit = [];
// This invalid date will trigger an error.
$edit['created[0][value][date]'] = $this->randomMachineName(8);
// Get the current amount of open details elements.
$open_details_elements = count($this->cssSelect('details[open="open"]'));
$this->submitForm($edit, 'Save Company');
// The organization owner details must be open.
// Only one extra details element should now be open.
$open_details_elements++;
$this->assertCount($open_details_elements, $this->cssSelect('details[open="open"]'), 'Exactly one extra open <details> element found.');
// Edit the same organization, save it and verify it's unpublished after
// unchecking the 'Active' boolean_checkbox and clicking 'Save'.
$this->drupalGet("crm-core/organization/" . $organization->id() . "/edit");
$edit = ['status[value]' => FALSE];
$this->submitForm($edit, 'Save Company');
$this->organizationStorage->resetCache([$organization->id()]);
$organization = $this->organizationStorage->load($organization->id());
$this->assertFalse($organization->isPublished(), 'Organization is inactive');
}
/**
* Tests changing a organization's "owned by" field.
*/
public function testOrganizationEditOwnedBy() {
$this->drupalLogin($this->adminUser);
// Create organization to edit.
$edit = [];
$edit['name[0][value]'] = $this->randomMachineName(8);
$this->drupalGet('crm-core/organization/add/company');
$this->submitForm($edit, 'Save');
// Check that the organization was authored by the currently logged in user.
$organization = $this->drupalGetOrganizationByName($edit['name[0][value]']);
$this->assertSame($this->adminUser->id(), $organization->getOwnerId(), 'Organization owned by admin user.');
$this->checkVariousAuthoredByValues($organization, 'uid[0][target_id]');
// Check that normal users cannot change the authored by information.
$this->drupalLogin($this->webUser);
$this->drupalGet('crm-core/organization/' . $organization->id() . '/edit');
$this->assertSession()->fieldNotExists('uid[0][target_id]');
// Now test with the Autocomplete (Tags) field widget.
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
$form_display = \Drupal::entityTypeManager()->getStorage('entity_form_display')->load('crm_core_organization.company.default');
if (empty($form_display)) {
$form_display_values = [
'targetEntityType' => 'crm_core_organization',
'bundle' => 'company',
'mode' => 'default',
'status' => TRUE,
];
$form_display = \Drupal::entityTypeManager()
->getStorage('entity_form_display')
->create($form_display_values);
}
$widget = $form_display->getComponent('uid');
$widget['type'] = 'entity_reference_autocomplete_tags';
$widget['settings'] = [
'match_operator' => 'CONTAINS',
'size' => 60,
'placeholder' => '',
];
$form_display->setComponent('uid', $widget);
$form_display->save();
$this->drupalLogin($this->adminUser);
// Save the organization without making any changes.
$this->drupalGet('crm-core/organization/' . $organization->id() . '/edit');
$this->submitForm([], 'Save');
$this->organizationStorage->resetCache([$organization->id()]);
$organization = $this->organizationStorage->load($organization->id());
$this->assertSame($this->webUser->id(), $organization->getOwner()->id());
$this->checkVariousAuthoredByValues($organization, 'uid[target_id]');
// Hide the 'authored by' field from the form.
$form_display->removeComponent('uid')->save();
// Check that saving the organization without making any changes keeps the
// proper author ID.
$this->drupalGet('crm-core/organization/' . $organization->id() . '/edit');
$this->submitForm([], 'Save');
$this->organizationStorage->resetCache([$organization->id()]);
$organization = $this->organizationStorage->load($organization->id());
$this->assertSame($this->webUser->id(), $organization->getOwner()->id());
}
/**
* Tests the organization meta information.
*/
public function testOrganizationMetaInformation() {
// Check that regular users (i.e. without the
// 'administer crm_core_organization entities' permission) can not see the
// meta information.
$this->drupalLogin($this->webUser);
$this->drupalGet('crm-core/organization/add/company');
$this->assertSession()->pageTextNotContains('Not saved yet');
// Create organization to edit.
$edit['name[0][value]'] = $this->randomMachineName(8);
$this->submitForm($edit, 'Save');
$organization = $this->drupalGetOrganizationByName($edit['name[0][value]']);
$this->drupalGet("crm-core/organization/" . $organization->id() . "/edit");
$this->assertSession()->pageTextNotContains('Published');
$this->assertSession()->pageTextNotContains($this->container->get('date.formatter')->format($organization->getChangedTime(), 'short'));
// Check that users with the 'administer crm_core_organization entities'
// permission can see the meta information.
$this->drupalLogin($this->adminUser);
$this->drupalGet('crm-core/organization/add/company');
$this->assertSession()->pageTextContains('Not saved yet');
// Create organization to edit.
$edit['name[0][value]'] = $this->randomMachineName(8);
$this->submitForm($edit, 'Save');
$organization = $this->drupalGetOrganizationByName($edit['name[0][value]']);
$this->drupalGet("crm-core/organization/" . $organization->id() . "/edit");
$this->assertSession()->pageTextContains('Active');
$this->assertSession()->pageTextContains($this->container->get('date.formatter')->format($organization->getChangedTime(), 'short'));
}
/**
* Checks that the "authored by" works correctly with various values.
*
* @param \Drupal\crm_core_contact\OrganizationInterface $organization
* An organization object.
* @param string $form_element_name
* The name of the form element to populate.
*/
protected function checkVariousAuthoredByValues(OrganizationInterface $organization, $form_element_name) {
// Try to change the 'authored by' field to an invalid user name.
$edit = [
$form_element_name => 'invalid-name',
];
$this->drupalGet('crm-core/organization/' . $organization->id() . '/edit');
$this->submitForm($edit, 'Save');
$this->assertSession()->pageTextContains('There are no users matching "invalid-name".');
// Change the authored by field to an empty string, which should assign
// authorship to the anonymous user (uid 0).
$edit[$form_element_name] = '';
$this->drupalGet('crm-core/organization/' . $organization->id() . '/edit');
$this->submitForm($edit, 'Save');
$this->organizationStorage->resetCache([$organization->id()]);
$organization = $this->organizationStorage->load($organization->id());
$uid = $organization->getOwnerId();
// Most SQL database drivers stringify fetches but entities are not
// necessarily stored in a SQL database. At the same time, NULL/FALSE/""
// won't do.
$this->assertTrue($uid === 0 || $uid === '0', 'Organization owned by anonymous user.');
// Go back to the edit form and check that the correct value is displayed
// in the author widget.
$this->drupalGet('crm-core/organization/' . $organization->id() . '/edit');
$anonymous_user = User::getAnonymousUser();
$expected = $anonymous_user->label() . ' (' . $anonymous_user->id() . ')';
$this->assertSession()->fieldValueEquals($form_element_name, $expected);
// Change the authored by field to another user's name (that is not
// logged in).
$edit[$form_element_name] = $this->webUser->getAccountName();
$this->submitForm($edit, 'Save');
$this->organizationStorage->resetCache([$organization->id()]);
$organization = $this->organizationStorage->load($organization->id());
$this->assertSame($this->webUser->id(), $organization->getOwnerId(), 'Organization owned by normal user.');
}
}
