FieldDefaultValueCallbackTest.php in Drupal 8
File
core/modules/field/tests/src/Functional/FieldDefaultValueCallbackTest.php
View source
<?php
namespace Drupal\Tests\field\Functional;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\Tests\BrowserTestBase;
class FieldDefaultValueCallbackTest extends BrowserTestBase {
public static $modules = [
'node',
'field_test',
'field_ui',
];
protected $defaultTheme = 'stark';
private $fieldName;
protected function setUp() {
parent::setUp();
$this->fieldName = 'field_test';
if ($this->profile != 'standard') {
$this
->drupalCreateContentType([
'type' => 'article',
'name' => 'Article',
]);
}
}
public function testDefaultValueCallbackForm() {
FieldStorageConfig::create([
'field_name' => $this->fieldName,
'entity_type' => 'node',
'type' => 'text',
])
->save();
$field_config = FieldConfig::create([
'entity_type' => 'node',
'field_name' => $this->fieldName,
'bundle' => 'article',
]);
$field_config
->save();
$this
->drupalLogin($this->rootUser);
$this
->drupalGet('/admin/structure/types/manage/article/fields/node.article.field_test');
$this
->assertFieldByName('default_value_input[field_test][0][value]', NULL, 'The default field form is visible.');
$default_value = $this
->randomString();
$field_config
->setDefaultValue([
[
'value' => $default_value,
],
])
->save();
$this
->drupalGet('/admin/structure/types/manage/article/fields/node.article.field_test');
$this
->assertFieldByName('default_value_input[field_test][0][value]', $default_value, 'The default field form is visible.');
$default_value = $this
->randomString();
$field_config
->setDefaultValue($default_value)
->save();
$this
->drupalGet('/admin/structure/types/manage/article/fields/node.article.field_test');
$this
->assertFieldByName('default_value_input[field_test][0][value]', $default_value, 'The default field form is visible.');
$field_config
->setDefaultValueCallback('\\Drupal\\field_test\\FieldDefaultValueCallbackProvider::calculateDefaultValue')
->save();
$this
->drupalGet('/admin/structure/types/manage/article/fields/node.article.field_test');
$this
->assertNoFieldByName('default_value_input[field_test][0][value]', 'Calculated default value', 'The default field form is not visible when a callback is defined.');
}
}