Search code examples
drupaldrupal-8

Clear cache after update node image field programmatically


I have a node with an image field, if I update it on the node edit page after submitting the form, the image updates, but if I do it programmatically and reload the page, the image will not update. But if i reload the page with Ctrl + F5 (clear browser cache), it will update too. As I understand it, I have to invalidate some kind of cache, but I don't know which one.

$replace = move_uploaded_file($tmp_name, $poster_dir . '/' . $poster_name);
  if ($replace) {
    $poster_uri = 'public://user_files/' . $owner_id . '/posters/' . $model_id . '/' . $poster_name;
    $file = File::create([
      'filename' => $poster_name,
      'uri' => $poster_uri,
      'status' => 1,
    ]);
    $file->setPermanent();
    $file->save();
    $node->set('field_model_poster', ['target_id' => $file->id()]);
    $node->save();
}

Solution

  • The fact is that when generating the image, I left the same file name, so the browser cache was not updated. The solution is to change the name of the image to a new one each time.