I need to add a new string field called instagram_owner to all bundles of nodes, media and file entities. If new bundles are created, I need the field on them too. This is what I have so far in my MODULE_NAME.module file.
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Entity\EntityTypeBundleInfo;
use Drupal\Core\Entity\EntityFieldManager;
/**
* Implements hook_entity_base_field_info().
*/
function MODULE_NAME_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
$entity_type_id = $entity_type->id();
$field_name = 'instagram_owner';
// Check for the entity types
if ($entity_type_id === 'node' || $entity_type_id === 'media' || $entity_type_id === 'file') {
// Specify new Instagram owner field
$fields[$field_name] = BaseFieldDefinition::create('string')
->setLabel(new TranslatableMarkup("Instagram owner id"))
->setDescription(new TranslatableMarkup("This is the owners Instagram ID"))
->setSettings(["max_length" => 255, "text_processing" => 0])
->setDefaultValue("")
->setDisplayOptions("view", ["label" => "above", "type" => "string", "weight" => -3])
->setDisplayOptions("form", ["type" => "string_textfield", "weight" => -3]);
// Get the bundles for this entity type
$bundle_service = \Drupal::service('entity_type.bundle.info');
$bundles = $bundle_service->getBundleInfo($entity_type_id);
foreach($bundles as $bundle_id => $bundle) {
// Check to see if our field already exists on this bundle
$bundle_fields = \Drupal::service('entity_field.manager')->getFieldDefinitions($entity_type_id, $bundle_id);
if (!isset($bundle_fields[$field_name])) {
// If not, install it...
// not sure if this will install the field either?
// Where do I get $storage_definition from? This has never been uncommented.
// BaseFieldDefinition::installFieldStorageDefinition($field_name, $entity_type_id, $bundle_id, FieldStorageDefinitionInterface $storage_definition);
}
}
return $fields;
}
}
I know that the problematic line seems to be this one. It's this that throws a 503 error page:
$bundle_fields = \Drupal::service('entity_field.manager')->getFieldDefinitions($entity_type_id, $bundle_id);
In devels php block I get the expected results. I'm using this for testing:
$entity_type_id = 'node';
$field_name = 'instagram_owner';
if ($entity_type_id === 'node' || $entity_type_id === 'media' || $entity_type_id === 'file') {
$bundle_service = \Drupal::service('entity_type.bundle.info');
$bundles = $bundle_service->getBundleInfo($entity_type_id);
dpm($bundles);
$field_service = \Drupal::service('entity_field.manager');
foreach($bundles as $bundle_id => $bundle) {
$bundle_fields = $field_service->getFieldDefinitions($entity_type_id, $bundle_id);
if (!isset($bundle_fields[$field_name])) {
$ready_to_install = 'yes';
dpm($ready_to_install);
}
}
dpm($bundle_fields);
}
Any help would be greatly appreciated.