How to save value for a field to node or user - Drupal 7 :: entity module

Introduction

The contributed Entity API module provides wrapper classes that make dealing with the values of an entity's properties and fields easier.

If you need to save a text or numeric value into a field you must pass the value as below,

<?php
$node = node_load($nid);//Node ID
$node_wrapper = entity_metadata_wrapper('node', $node);
$var = $node_wrapper->field_age->value() + 1;
$node_wrapper->field_age->set($var);
$node_wrapper->save();

?>
Note: to update the user value you can use user_load($uid);

If you need to save a file into a field you must pass the file object or an array with a ``fid`` key:

<?php
  $node = node_load($nid); //Node ID
  $containing_node = entity_metadata_wrapper('node', $node);

  // Load the file object in any way
  $file_obj = file_load($fid);
  $containing_node->field_attachment_content->file->set( $file_obj );
  // ..or pass an array with the fid
  $containing_node->field_attachment_content->set( array('fid' => $fid) );
  $containing_node->save();

  // If an image field supports title or alt, you can set them in 2 ways.
  // Set both file and title with an array.
  $containing_node->field_image->set(array('fid' => $fid, 'title' => $title));
  // Set both file and title separately.
  $image_obj = file_load($fid);
  $containing_node->field_image->file = $image_obj;
  $containing_node->field_image->title = $title;
  $containing_node->save();

?>

Note: to update the user value you can use user_load($uid);

Comments

Popular posts from this blog

PHP - How to increase size of POST value in php

D8 KernelEvents constants

D8 - Attach file programmatically to a node