How do I in code, create a new field value, add it to a content entity, and then have it saved to the DB?
Field API is dead. Long live Entity Field API! clearly shows how to read values, but doesn't mention inserts/updates.
How do I in code, create a new field value, add it to a content entity, and then have it saved to the DB?
Field API is dead. Long live Entity Field API! clearly shows how to read values, but doesn't mention inserts/updates.
I'm not sure what you mean with "field value", do you mean field items with multiple values?
It's the same as reading them, nothing special:
// Those are identical, not specifying [0] results in that using by default.
$entity->some_field->value = 'Whatever';
$entity->some_field[0]->value = 'Whatever';
// To add a value for the second item:
$entity->some_field[1]->value = 'Something';
// And persist to DB:
$entity->save();
Edit, the following script works for me and gives me the following output:
<?php
use Drupal\node\Entity\Node;
$node = Node::create(array('type' => 'article'));
$node->field_tags->target_id = 5;
var_dump($node->field_tags->getValue());
$node->field_tags[] = 6;
$node->field_tags[] = array('target_id' => 7);
var_dump($node->field_tags->getValue());
unset($node->field_tags[1]);
var_dump($node->field_tags->getValue());
Output:
array(1) {
[0] =>
array(1) {
'target_id' =>
int(5)
}
}
array(3) {
[0] =>
array(1) {
'target_id' =>
int(5)
}
[1] =>
array(1) {
'target_id' =>
int(6)
}
[2] =>
array(1) {
'target_id' =>
int(7)
}
}
array(2) {
[0] =>
array(1) {
'target_id' =>
int(5)
}
[2] =>
array(1) {
'target_id' =>
int(7)
}
}
The delta is off then in the last example, but this will probably be fixed in https://www.drupal.org/node/2164601, which might also affect how the code above works..
$entity->$field[count($field)]->value
, or is there a shortcut for this?
Commented
Nov 5, 2014 at 18:43
Here's what I've ended up doing. In my examples, I'm adding and removing an entity reference.
How to add a new field value:
// Insert a new field value:
$field = 'field_name';
$fieldItems = $entity->$field->getValue();
$entity->$field->setValue(
array_merge(
$entity->$field->getValue(),
array($target_entity)
)
);
$entity->save();
I found no way of removing field items directly, so instead I overwrite all of them.
// Removing a field value. In this example, an entity reference.
foreach ($fieldItems as $delta => $fieldItem) {
if ($fieldItem['target_id'] === $target_entity_id) {
unset($fieldItems[$delta]);
$entity->$field->setValue($fieldItems);
$entity->save();
break;
}
}