I created a custom field but I don't know how to set a value. I can read values with


The field consists of several elements: value, data, api_key

I'm loading the entity and would like to set the values of the field programatically, I tried:

$entity->set('field_myfield', ['data' => 'some data'], 'value' => 'some value');

This doesn't work.

  • This is a single value field with multiple properties? Then the one level array in the example should work, you only need to move the closing square bracket to the end. BTW you get the full two level array with all properties and values from getValue() in the first line, which you could, after modifying it, use in the second line to set the field.
    – 4uk4
    Jul 4, 2018 at 16:32
  • Silly mistake with the brackets. But it still doesn't work. If I try and save the entity, the field is completly empty, i.e. the row in the field table is removed.
    – Peter
    Jul 4, 2018 at 16:45
  • This is easy to debug when you look at the output of $entity->get('field_myfield')->getValue(), this is what the second parameter of set() should look like.
    – 4uk4
    Jul 4, 2018 at 16:55
  • I'll have a look, in the meantime I followed your second suggestion and was able to update one property by using: $data = $entity->get('field_myfield')->getValue()[0]['data']; $data->setValue('some data'); $entity->save()
    – Peter
    Jul 4, 2018 at 17:05
  • One property you could simply: $data = $entity->field_my_field->data; or $entity->field_my_field->data = 'some_data';
    – 4uk4
    Jul 4, 2018 at 17:12

1 Answer 1


You don't need to worry as the entity API should take care of the specific structure and just set it via:

$entity->set('field_myfield', 'some value');

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.