Community

Update values with db_update() but custom field doesn't update until after cache cleared

Hello,

I created a custom field in the user profile titled 'field_node_count' that is hidden to all users. This field contains the number of nodes each user creates and is then being used in a view for featured profiles. If the user creates/deletes a node, it updates the column with db_update() and is triggered from within node.pages.inc. The calculation works perfectly and the database values are updated just fine, but the field itself does not update until I clear the cache.

How can I clear the cache for that specific user, or that specific custom field after the db_update() is called? I don't want to flush all caches every time a new node is created. Thanks!

Comments

After updating the table I

After updating the table I think you want

$cid = 'field:user:' . {user_id_you_are_updating_for};
cache_clear_all($cid, 'cache_field');

Replacing {user_id_you_are_updating_for} with the appropriate value, probably $node->uid

Awesomeness

That did it. You were correct in your usage of $node->uid as well. Here is the complete code that increments the value by 1 when a new node is created:

<?php
 
//Update Data Field
 
$node_owner = $node->uid;
 
db_update('field_data_field_node_count')
    ->
expression('field_node_count_value', 'field_node_count_value + :field_node_count_value', array(':field_node_count_value' => 1))
    ->
condition('entity_id', $node_owner)
    ->
execute();
   
//Update Revision Field   
 
db_update('field_revision_field_node_count')
    ->
expression('field_node_count_value', 'field_node_count_value + :field_node_count_value', array(':field_node_count_value' => 1))
    ->
condition('entity_id', $node_owner)
    ->
execute();

 
//Clear cache on field to display field's updated value on front end       
 
$cid = 'field:user:' . $node->uid;
 
cache_clear_all($cid, 'cache_field');
?>

Awesome, like wow, like totally freak me out, I mean, right on! Nevets sure is number one! Go Nevets!

nobody click here