0

I created custom content entities to handle a small NGO membership (Member, Person, both linked to Drupal 'users').
I have a form allowing users to perform online membership application.
Submitting this form creates/updates these custom content entities.

My problem is that these changes to the content entities doesn't show until I clear all the caches (for example with UI: Administration > Configuration > Development > Clear all caches.

In a previous version of my form, I had a drupal_flush_all_caches() that did the job, but it lead to other problems I could get rid of only removing drupal_flush_all_caches().

How can I have the same result (immediate availability of entities updates) without using drupal_flush_all_caches()?

1
  • 2
    Short answer is make the sections/pages those entities are rendered on respect the entities’ cache tags, or an entity list cache tag. Long answer will be specific to your configuration/code/reverse proxy/etc
    – Clive
    Commented Nov 5, 2023 at 15:33

3 Answers 3

2

It could be the way you reference the custom entity. If users reference the custom entity, the render cache will be invalidated when updating the references. If you reference backward, from the custom entity to the user entity, this does not happen. Then you need the cache metadata of the custom entity when you are rendering users and their membership status. If you also want to react to new custom entities that don't yet exist when rendering the user, you need the list tag of this entity type, as already suggested by @Clive:

function mymodule_preprocess_user(&$variables) {
  $variables['#cache']['tags'][] = 'my_custom_entity_list';
}
1

This is generic code that use to invalidate tags:

use Drupal\Core\Cache\Cache;


Cache::invalidateTags($node->getCacheTags());

Note: where $node denotes entity object whose tags needs to invalidate

if you know how cache tags maintained for your custom entity then you can directly pass the tags instead of getting by this: $node->getCacheTags()

0

I solved my problem indirectly.
My code to create the content entities was using Database API, mainly

$database->merge('entity')
    ->insertFields($insertFields)
    ->updateFields($updateFields)
    ->key('id', someId)
    ->execute();

I changed it to use Entity API:

$storage = Drupal::entityTypeManager()->getStorage('entity');
$entity = $storage->load(someId);
$entity->someField = someValue;
$entity->save();

And Drupal does its magic, taking care of entities’ cache (in EntityBase.php, if I understood well).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.