Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a field value with the field API?

I'm using the Drupal 7 field API, which seems great: I can add a custom field for the 'user' entity type, and edit in the GUI.

I use field_get_items($entity_type, $entity, $field) to get the custom field values.

I now need to programmatically set the value of my custom field.

How do I do that? I can't find a field_set_items() function call anywhere in the Drupal API documentation.

like image 429
Keith Palmer Jr. Avatar asked Apr 07 '12 15:04

Keith Palmer Jr.


1 Answers

There isn't a function to set the value of a field. You can generally set the value of a field with the following code.

$entity->$fieldname[$language][$delta] = $value;

What changes for every field is the array you pass in $value. For example, the body field of a node uses the following structure.

array(
  'value' => 'Empty text. Revision 3.',
  'summary' => '',
  'format' => 'full_html',
  'safe_value' => '<p>Empty text. Revision 3.</p>',
  'safe_summary' => '',
);

The structure used for a taxonomy term is the following one.

array(
  'tid' => 4,
);

$delta is a value that is normally 0, but for fields with multiple values it can have any value, as long as it is not higher than the maximum number of values it can get (which can be set in the user interface for a specific field).
$language is the language ID, and it can also be set to LANGUAGE_NONE.

like image 179
apaderno Avatar answered Sep 22 '22 12:09

apaderno