Problem/Motivation
I'm inquiry about a high-level challenge where I believe the issue lies with Crop API and its support of the JSON API; however, I need some additional information about how entity share registers that there is a change.
If Crop Api added fields like 'changed' and 'created' how would Entity Share pick up that there is a change? I went down a little of rabbit hole today to do this but even after changing the schema to support these new fields and validating that these entries changed and were available in a json request when I went to pull the entity there was no registered change.
This is on a content type where we embed media and then have crop api applied to the media.
I eventually got this to work by using a custom entity update hook, but my gut makes me feel this is a hack rather than a Drupal way especially since the way I found depends on entity_usage.
Should I be looking at a plugin or crop processor for Entity Share?
Any feedback is greatly appreciated
This is the hook that eventually got everything working.
/**
* Implements hook_entity_update().
*/
function uclahs_custom_entity_update(EntityInterface $entity) {
if ($entity->getEntityTypeId() === 'crop') {
$uri = $entity->get('uri')->value;
if (!$uri) {
return;
}
// Load the file entity from the URI.
$files = \Drupal::entityTypeManager()
->getStorage('file')
->loadByProperties(['uri' => $uri]);
if (empty($files)) {
return;
}
$file = reset($files);
// Get usages of the file.
$usages = \Drupal::service('file.usage')->listUsage($file);
foreach ($usages as $module => $usage) {
foreach ($usage as $entity_type => $entities) {
foreach ($entities as $entity_id => $count) {
$used_entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load($entity_id);
// If the file is used in a Media entity, find where that Media entity is used.
if ($used_entity && $used_entity->getEntityTypeId() === 'media') {
$referencing_entities = \Drupal::service('entity_usage.usage')->listSources($used_entity);
foreach ($referencing_entities as $source_type => $source_ids) {
foreach ($source_ids as $source_id => $records) {
$parent_entity = \Drupal::entityTypeManager()->getStorage($source_type)->load($source_id);
if ($parent_entity && $parent_entity->hasField('changed')) {
$parent_entity->set('changed', \Drupal::time()->getRequestTime());
$parent_entity->save();
\Drupal::logger('uclahs_custom')->notice('Updated parent entity from media usage: ' . $parent_entity->id());
}
}
}
}
}
}
}
}
}
Comments
Comment #2
pbabin commentedComment #3
pbabin commentedI made some updates to the patch that required this workaround. It is no longer needed.
https://www.drupal.org/project/crop/issues/2890651#comment-16505039