function block_content_add_body_field

Same name in other branches
  1. 9 core/modules/block_content/block_content.module \block_content_add_body_field()
  2. 10 core/modules/block_content/block_content.module \block_content_add_body_field()
  3. 11.x core/modules/block_content/block_content.module \block_content_add_body_field()

Adds the default body field to a custom block type.

Parameters

string $block_type_id: Id of the block type.

string $label: (optional) The label for the body instance. Defaults to 'Body'

Return value

\Drupal\field\Entity\FieldConfig A Body field object.

15 calls to block_content_add_body_field()
BlockContentCacheTagsTest::createEntity in core/modules/block_content/tests/src/Functional/BlockContentCacheTagsTest.php
Creates the entity to be tested.
BlockContentResourceTestBase::createEntity in core/modules/block_content/tests/src/Functional/Rest/BlockContentResourceTestBase.php
Creates the entity to be tested.
BlockContentTest::createEntity in core/modules/jsonapi/tests/src/Functional/BlockContentTest.php
Creates the entity to be tested.
BlockContentTestBase::createBlockContentType in core/modules/block_content/tests/src/Functional/Views/BlockContentTestBase.php
Creates a custom block type (bundle).
BlockContentTestBase::createBlockContentType in core/modules/block_content/src/Tests/Views/BlockContentTestBase.php
Creates a custom block type (bundle).

... See full list

File

core/modules/block_content/block_content.module, line 82

Code

function block_content_add_body_field($block_type_id, $label = 'Body') {
    // Add or remove the body field, as needed.
    $field = FieldConfig::loadByName('block_content', $block_type_id, 'body');
    if (empty($field)) {
        $field = FieldConfig::create([
            'field_storage' => FieldStorageConfig::loadByName('block_content', 'body'),
            'bundle' => $block_type_id,
            'label' => $label,
            'settings' => [
                'display_summary' => FALSE,
            ],
        ]);
        $field->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('block_content', $block_type_id)
            ->setComponent('body', [
            'type' => 'text_textarea_with_summary',
        ])
            ->save();
        // Assign display settings for default view mode.
        $display_repository->getViewDisplay('block_content', $block_type_id)
            ->setComponent('body', [
            'label' => 'hidden',
            'type' => 'text_default',
        ])
            ->save();
    }
    return $field;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.