9

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
  • this is how I was set the value $wrapper->vimn_related_subjects->set(array($key)); but if I wanted to add a value to the end of the array? is that possible? Commented Nov 13, 2012 at 13:19
  • Have you tried $wrapper->vimn_related_subjects[] = $value;?
    – Clive
    Commented Nov 13, 2012 at 17:14

2 Answers 2

32

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;
2
  • "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);
    – AlxVallejo
    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.
    – Incredible
    Commented Nov 21, 2016 at 14:50
3

I found that

$wrapper->field_example[]->set($new_value);

was a fatal failure. But

$wrapper->field_example[NULL]->set($new_value);

was allowed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.