Programmatically manage bundle fields with ConfigurableFieldManager

1 minute read

Drupal’s ORM and Field API is rather powerful, but it can be a bear to understand after entities and their fields are initially installed. If you’re writing a custom entity type, its base fields are pulled from ContentEntityInterface::baseFieldDefinitions(). Bundle fields can either be added through the field_ui module’s interface or programmatically with entity module’s bundle plugins.

What if you want to add or edit fields after the fact? Drupal’s documentation covers adding and editing base fields, but bundle fields are different still.

This blog post exists simply to call your attention to Commerce module’s excellent ConfigurableFieldManager, which is not at all Commerce-specific. Use it to update bundle fields, either as part of an update hook or in a one-off if you’re working in custom code that does not require an upgrade path:

<?php

use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\entity\BundleFieldDefinition;

$field_storage_definition = BundleFieldDefinition::create('commerce_remote_id')
  ->setName('remote_id')
  ->setTargetEntityTypeId('entity_type_id')
  ->setTargetBundle('bundle_id')
  ->setLabel('Remote ID')
  ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED)
  ->setRequired(TRUE)
  ->setDisplayConfigurable('form', FALSE)
  ->setDisplayConfigurable('view', FALSE);

/** @var \Drupal\commerce\ConfigurableFieldManagerInterface $configurableFieldManager */
$configurableFieldManager = \Drupal::service('commerce.configurable_field_manager');

$configurableFieldManager->createField($field_storage_definition);

There’s an issue to bring this code into Entity API module, but there’s no need to wait.

This great little helper service follows in a fine tradition of Commerce-born enhancements to the Entity API. I’ve found clever uses for the Entity Traits pattern in projects, for instance. The above example also leverages Commerce Core’s remote ID field type, applicable in many non-commerce applications.

Work smarter, not harder!

(Funny story about that mindset: I once was being introduced to a company’s staff after joining as a consultant, and I included “An advocate for working smarter, not harder” in my slide deck. Management took it out. I don’t work there anymore. They apparently liked working harder for its own sake.)

Updated: