1

In my code I am inserting a new value into the database directly using db_insert (i.e. inserting an entirely new row). The type of field, however, already exists in Drupal which is called "field_data_field_email_address". Previous to the insert call no value existed in the database which is associated with an entity.

Later in code I am relying on entity_metadata_wrapper to retrieve the values associated with the entity. The problem is that the wrapper doesn't retrieve the most recently inserted value but instead returns nothing. Yet when I look in the database table I can clearly see the existence of the newly inserted value.

As you may have already guessed I narrowed the issue down to a caching issue because if I clear the Drupal cache the wrapper returns the newly created value just fine.

My question is this: How can I force the entity_metadata_wrapper call to not retrieve the cached version but refresh and return to me the actual current values that exist in the database. I need my wrapper to represent the freshest data and not the cached version.

Thank you in advance!

4
  • 1
    The short answer is to never bypass the Field API to update an entity. The long answer depends on what caching strategies / modules your site is using.
    – mpdonadio
    Commented Sep 30, 2014 at 16:15
  • Actually I think after my db_insert call I can use entity_load() and set the optional parameter $reset to true to update its internal cache. Testing now, will respond with results in a second.
    – Art Geigel
    Commented Sep 30, 2014 at 16:23
  • Bam! That worked perfectly.
    – Art Geigel
    Commented Sep 30, 2014 at 16:28
  • Related drupal.stackexchange.com/questions/108188/…
    – mikeytown2
    Commented Sep 30, 2014 at 21:23

2 Answers 2

2

The cache can actually be cleared using the entity_load function and passing a value of true for $reset which will clear the cache and update future references to it including wrappers retrieved from entity_metadata_wrapper:

entity_load("node", array($nid), null, true);
3
  • I am actually not 100% sure this is accurate. IIRC, the $reset has to do with the static cache, and not {cache_field} nor the entity cache tables.
    – mpdonadio
    Commented Sep 30, 2014 at 17:10
  • Hmm... the result I was looking for worked. Any insight into what was going on for it to work the way I intended then?
    – Art Geigel
    Commented Oct 1, 2014 at 18:03
  • I am not sure. I would want someone more familiar with the Entity controllers to weigh in, though mikeytown2 did give a detailed link (and he is a smart dude).
    – mpdonadio
    Commented Oct 1, 2014 at 18:29
0

For nodes, I found this snippet on hook_node insert helpful:

entity_get_controller('node')->resetCache(array($w->getIdentifier()));

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.