Mikhail Kulbizhekov
Mikhail Kulbizhekov

Reputation: 11

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();
}

Upvotes: 0

Views: 679

Answers (2)

Mikhail Kulbizhekov
Mikhail Kulbizhekov

Reputation: 11

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.

Upvotes: 1

Ranjan
Ranjan

Reputation: 300

You can do like that, I am using this in one of my work, so hope its help (just test image)

$data = file_get_contents("https://cdn.hackernoon.com/hn-images/0*xMaFF2hSXpf_kIfG.jpg");
$file = file_save_data($data, "public://0*xMaFF2hSXpf_kIfG.jpg", FILE_EXISTS_REPLACE);

$nid = 34; // your nid
$node = Node::load($nid);

$field_image = array(
     'target_id' => $file->id(),
     'alt' => "Image",
     'title' => "Update Program",
);
$node->field_image = $field_image;       
$node->save();

For invalidate cache, it will auto invalidate once node is save, either manually or by program, and if your set any node specfic cache that you need to invalidate that to get it worked.

Upvotes: 0

Related Questions