Adds a Paragraphs field to a given entity type.
string $bundle: bundle to be used.
string $paragraphs_field_name: Paragraphs field name to be used.
string $entity_type: Entity type where to add the field.
string $widget_type: (optional) Declares if we use stable or legacy widget. Defaults to 'paragraphs' for stable widget. Use 'entity_reference_paragraphs' for legacy widget.
protected function addParagraphsField($bundle, $paragraphs_field_name, $entity_type, $widget_type = 'paragraphs') {
$field_storage = FieldStorageConfig::loadByName($entity_type, $paragraphs_field_name);
if (!$field_storage) {
// Add a paragraphs field.
$field_storage = FieldStorageConfig::create([
'field_name' => $paragraphs_field_name,
'entity_type' => $entity_type,
'type' => 'entity_reference_revisions',
'cardinality' => '-1',
'settings' => [
'target_type' => 'paragraph',
],
]);
$field_storage
->save();
}
$field = FieldConfig::create([
'field_storage' => $field_storage,
'bundle' => $bundle,
'settings' => [
'handler' => 'default:paragraph',
'handler_settings' => [
'target_bundles' => NULL,
],
],
]);
$field
->save();
$form_display = \Drupal::service('entity_display.repository')
->getFormDisplay($entity_type, $bundle);
$form_display = $form_display
->setComponent($paragraphs_field_name, [
'type' => $widget_type,
]);
$form_display
->save();
$view_display = \Drupal::service('entity_display.repository')
->getViewDisplay($entity_type, $bundle);
$view_display
->setComponent($paragraphs_field_name, [
'type' => 'entity_reference_revisions_entity_view',
]);
$view_display
->save();
}