I need to save a new value to a field on an entity and I was wondering if it was possible to use entity_metadata_wrapper or is it only possible to set an existing value?
2 Answers
When dealing with multi-value fields, the associated entity metadata wrapper object is an instance of EntityListWrapper (It may be a good idea to browse the API to look at the available methods. Also note this class implements the ArrayAccess interface)
So the simplest way to add new values to an EntityListWrapper is by using the "[]" operator:
$wrapper->field_example[] = $new_value;
This creates a new entry and assigns it the value. With this methods, the delta (the offset within the list of value) is created automatically. You can also set the offset yourself if you wish. Any of the three following methods are equivalent:
$wrapper->field_example[$delta] = $new_value;
$wrapper->field_example->offsetSet($delta, $new_value);
$wrapper->field_example->get($delta)->set($new_value);
In all three cases this will overwrite values if the delta already exists, and create a new entry if not.
You could also directly set an array of value on the field itself. Both of the methods are equivalent:
$value = array
0 => array('property_example' => 'hello'),
1 => array('property_example' => 'world')
);
$wrapper->field_example = $value;
$wrapper->field_example->set($value);
However this requires you to know the internal structure of the field you're assigning to as you're not using the field's metadata wrapper.
Finally you can empty a multi value field by setting it to an empty value. All three methods are equivalent :
$wrapper->field_example->set();
$wrapper->field_example = array();
$wrapper->field_example = NULL;
-
"EntityMetadataWrapperException: Unknown data property Array. in EntityStructureWrapper->getPropertyInfo()" I'm trying your second approach, although i'm targeting a specific language. ie, $wrapper->language($lang)->{$field}->set($new_array); Commented Jan 27, 2015 at 13:04
-
$w->field_allowed_regions->set(array(null));
is the only clearing option that worked for my multi-value taxonomy reference field. Commented Nov 21, 2016 at 14:50
I found that
$wrapper->field_example[]->set($new_value);
was a fatal failure. But
$wrapper->field_example[NULL]->set($new_value);
was allowed.
$wrapper->vimn_related_subjects[] = $value;
?