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?

  • 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? – Andrew Welch Nov 13 '12 at 13:19
  • Have you tried $wrapper->vimn_related_subjects[] = $value;? – Clive Nov 13 '12 at 17:14
31

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); – AlxVallejo Jan 27 '15 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 Nov 21 '16 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, privacy policy and cookie policy

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