I have Commerce products for which I'm showing or hiding the add-to-cart link, if that product is or isn't in the current cart. In my code:

function mymodule_commerce_product_view_alter(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display) {
    $myservice = \Drupal::service('myservice');
    if ($myservice->isProductInCurrentCart($entity->id()) {
        $build['add_to_cart_link']['#access'] = FALSE;

That works fine, however, when the product entities are rendered, they retain their cache and will continue to display, or not display, the add-to-cart link until the cache is cleared.

In my view_alter hook, how can I clear the cache for the current user for that entity before it's rendered? Can I set a cache tag?


At first I disabled the cache for the link, but the entity was cached, preventing the link from being shown or hidden. Therefore, I disabled the cache for the entity and that worked.

In the alter hook:

$build['#cache']['max-age'] = 0

The entity is now rendered with the proper state of the cart link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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