View source
<?php
namespace Drupal\Tests\cck_select_other\Functional;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\Tests\BrowserTestBase;
use Drupal\Tests\node\Traits\NodeCreationTrait;
abstract class CckSelectOtherTestBase extends BrowserTestBase {
use NodeCreationTrait;
protected $defaultTheme = 'stable';
protected static $modules = [
'node',
'field_ui',
'options',
'cck_select_other',
];
protected $contentType;
protected $adminUser;
protected $webUser;
public function setUp() {
parent::setUp();
$this->contentType = $this
->createContentType();
$this->adminUser = $this
->createUser([
'administer content types',
'administer site configuration',
]);
$this->webUser = $this
->createUser([
'access content',
'create ' . $this->contentType
->id() . ' content',
'delete any ' . $this->contentType
->id() . ' content',
'bypass node access',
]);
}
protected function createSelectOtherListField($type = 'list_string', array $fieldInfo = [], array $instanceInfo = []) {
$random = $this
->getRandomGenerator();
$storage_values = NestedArray::mergeDeep($fieldInfo, [
'field_name' => strtolower($random
->name(8, TRUE)),
'entity_type' => 'node',
'type' => $type,
]);
$fieldStorage = FieldStorageConfig::create($storage_values);
$fieldStorage
->save();
$this
->assertNotNull($fieldStorage
->id(), 'Successfully saved field storage configuration.');
$field_values = NestedArray::mergeDeep($instanceInfo, [
'field_name' => $fieldStorage
->getName(),
'entity_type' => 'node',
'bundle' => $this->contentType
->id(),
'label' => $random
->string(15),
]);
$field = FieldConfig::create($field_values);
$field
->save();
$this
->assertNotNull($field
->id(), 'Successfully saved field configuration.');
$display_id = 'node.' . $this->contentType
->id() . '.default';
$formDisplay = EntityFormDisplay::load($display_id);
$formDisplay
->setComponent($fieldStorage
->getName(), [
'type' => 'cck_select_other',
]);
$formDisplay
->save();
$viewDisplay = EntityViewDisplay::load($display_id);
$viewDisplay
->setComponent($fieldStorage
->getName(), [
'type' => 'cck_select_other',
]);
$viewDisplay
->save();
return $fieldStorage;
}
public function getRandomOption(array $options) {
$option = array_rand($options);
return [
$option,
$options[$option],
];
}
public function createOptions($num = 5, $type = 'list_string') {
$options = [];
for ($i = 0; $i < $num; $i++) {
if ($type === 'list_string') {
$label = $this
->getRandomGenerator()
->word(10);
$key = strtolower($label);
}
else {
$label = $i;
$key = $i;
}
$options[$key] = $label;
}
return $options;
}
public function allowedValuesString(array $values) {
$lines = [];
foreach ($values as $key => $value) {
$lines[] = "{$key}|{$value}";
}
return implode("\n", $lines);
}
}