As the content of your field is dynamically generated, it sounds like you need a computed field. Which will remove the issue you are running into. A computed field is one that is generated dynamically, rather than through user input. As it is a field, it can be managed like any other field in Drupal (though integration with Views requires some additional efforts). Fields are also cached with Drupal's various cache APIs.
To create a computed field, first extend Drupal\Core\Field\FieldItemList
, use
the Drupal\Core\TypedData\ComputedItemListTrait
, and implement the computeValue()
method:
namespace Drupal\[EXAMPLE]\Plugin\Field;
use Drupal\Core\Field\FieldItemList;
use Drupal\Core\TypedData\ComputedItemListTrait;
class SomeDynamicField extends FieldItemList {
use ComputedItemListTrait;
/**
* {@inheritdoc}
*/
protected function computeValue() {
$values = some_function_to_get_an_array_of_values();
foreach ($values as $index => $value) {
$this->list[$delta] = $this->createItem($delta, $value);
}
}
}
Next, this field needs to be added to each entity type that you need, in hook_entity_base_field_info_alter():
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
/**
* Implements hook_entity_base_field_info_alter().
*/
function EXAMPLE_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
// Add/alter entity types as necessary.
$applicable_entity_types = ['node'];
if (in_array($entity_type->id(), $applicable_entity_types)) {
$fields['my_computed_field'] = BaseFieldDefinition::create('string')
->setName('example_field')
->setLabel(t('Example Calculated Field'))
->setDescription(t('An example of a calculated field'))
// Set the field as a computed field.
->setComputed(TRUE)
// Set the class that generates the field value(s).
->setClass('\Drupal\[EXAMPLE]\Plugin\Field\Computed\SomeDynamicField');
}
}