0

I just want to use node_save() to change value of an image field in my article, and I am using the following code.

$node = node_load(1);
$node->field_image["und"][0]["filename"] = $file_name;
node_save($node);

When I press F5, the image in my article is not changed.

Is anything wrong in my code?

apaderno
  • 28,547
  • 16
  • 75
  • 90
tunghk_54
  • 135
  • 1
  • 4
  • 14
  • [This][1] might be of some help. [1]: http://api.drupalize.me/api/drupal/function/EntityMetadataIntegrationTestCase::testImageFields/7 – Kurt Zhong Mar 13 '13 at 08:26

2 Answers2

1

I find the easiest way to deal with problems like these is to use the Devel module.

In your code you could do this:

$node = node_load(1);
dsm($node);
....
node_save($node);
dsm($node);

Devel dsm() function will output the node's properties & you will be able to check any values you would like to edit.

In the example above, I can check before & after the edit. If everything looks correct, then it's just a question of clearing the caches.

PatrickS
  • 9,539
  • 2
  • 27
  • 31
0

Once i did something like this, it might not be the best but it worked for me:

$file = file_load($node->field_image['und'][0]['fid']);
unset($node->field_image['und'][0]);
file_delete($file);

$file_path = drupal_realpath('sites/default/files/image.png');
$file = (object) array(
          'uid' => 1,
          'uri' => $file_path,
          'filemime' => file_get_mimetype($file_path),
          'status' => 1,
 ); 
$file = file_copy($file, 'public://');
$node->field_im['und'][0] = (array) $file;