Back in Drupal 9.3 we introduced the ResourceTypeBuildEvent allows modules to disable resource type fields via the ResourceTypeBuildEvent::disableField method.
Some sites may want to override modules that have disabled fields by re-enabling them. The ResourceTypeBuildEvent now has a method, ResourceTypeBuildEvent::enableField, that subscribers can now re-enable fields that were previously disabled.
For example, to re-enable a field like (drupal_internal__order_id) that was disabled by the commerce_api module you can use the following code:
class CommerceApiOrderIdSubscriber implements EventSubscriberInterface {
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
return [
ResourceTypeBuildEvents::BUILD => 'onResourceTypeBuild',
];
}
/**
* Enable the drupal_internal__order_id field again.
*
* @param \Drupal\jsonapi\ResourceType\ResourceTypeBuildEvent $event
* The event.
*/
public function onResourceTypeBuild(ResourceTypeBuildEvent $event): void {
$resourceTypeName = $event->getResourceTypeName();
if ($resourceTypeName === 'order--default') {
foreach ($event->getFields() as $field) {
if ($field->getPublicName() === 'drupal_internal__order_id') {
if (!$field->isFieldEnabled()) {
$event->enableField($field);
}
}
}
}
}
}
You should take note, sometimes you need to set the priority of your event in order to execute the handler after the enabled module. You can control this by adding the priority to the subscribed event as follows:
public static function getSubscribedEvents() {
return [
ResourceTypeBuildEvents::BUILD => ['onResourceTypeBuild', 100],
];
}