function block_content_add_body_field

Adds the default body field to a 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.

Deprecated

in drupal:11.3.0 and is removed from drupal:12.0.0. There is no replacement.

See also

https://www.drupal.org/node/3535528

File

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

Code

function block_content_add_body_field($block_type_id, $label = 'Body') {
  @trigger_error(__FUNCTION__ . '() is deprecated in drupal:11.3.0 and is removed from drupal:12.0.0. There is no replacement. See https://www.drupal.org/node/3535528', E_USER_DEPRECATED);
  // 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,
        'allowed_formats' => [],
      ],
    ]);
    $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.