function BodyFieldCreationTrait::createBodyField
Creates a field of an body field storage on the specified bundle.
Parameters
string $entityType: The type of entity the field will be attached to.
string $bundle: The bundle name of the entity the field will be attached to.
string $fieldName: (optional) The name of the field. Defaults to 'body'.
string $fieldLabel: (optional) The label for the field. Defaults to 'Body'.
int $cardinality: (optional) The cardinality of the field. Defaults to 1.
1 call to BodyFieldCreationTrait::createBodyField()
- ContentTypeCreationTrait::createContentType in core/
modules/ node/ tests/ src/ Traits/ ContentTypeCreationTrait.php - Creates a custom content type based on default settings.
File
-
core/
modules/ field/ tests/ src/ Traits/ BodyFieldCreationTrait.php, line 29
Class
- BodyFieldCreationTrait
- Provides a method to create a body field for a given bundle.
Namespace
Drupal\Tests\field\TraitsCode
protected function createBodyField(string $entityType, string $bundle, string $fieldName = 'body', string $fieldLabel = 'Body', int $cardinality = 1) : void {
// Look for or add the specified field to the requested entity bundle.
$fieldStorage = FieldStorageConfig::loadByName($entityType, $fieldName);
if (!$fieldStorage) {
FieldStorageConfig::create([
'field_name' => $fieldName,
'type' => 'text_with_summary',
'entity_type' => $entityType,
'cardinality' => $cardinality,
])->save();
}
if (!FieldConfig::loadByName($entityType, $bundle, $fieldName)) {
FieldConfig::create([
'field_storage' => $fieldStorage,
'bundle' => $bundle,
'label' => $fieldLabel,
'settings' => [
'display_summary' => TRUE,
'allowed_formats' => [],
],
])->save();
/** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
$display_repository = \Drupal::service('entity_display.repository');
// Assign widget settings for the default form mode.
$display_repository->getFormDisplay($entityType, $bundle)
->setComponent('body', [
'type' => 'text_textarea_with_summary',
])
->save();
// Assign display settings for the 'default' and 'teaser' view modes.
$display_repository->getViewDisplay($entityType, $bundle)
->setComponent('body', [
'label' => 'hidden',
'type' => 'text_default',
])
->save();
// The teaser view mode is created by the Standard profile and might
// not exist.
$view_modes = $display_repository->getViewModes($entityType);
if (isset($view_modes['teaser'])) {
$display_repository->getViewDisplay($entityType, $bundle, 'teaser')
->setComponent('body', [
'label' => 'hidden',
'type' => 'text_summary_or_trimmed',
])
->save();
}
}
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.