I have a custom module that creates a field type. It is a plain text field abd I’ve added it to a content type using the Drupal UI. The cardinality of this field is "Unlimited".
This is how I create the field in code:
class MyItem extends FieldItemBase { /** * {@inheritdoc} */ public static function schema(FieldStorageDefinitionInterface $field_definition) { return [ 'columns' => [ 'value' => [ 'type' => 'text', 'size' => 'tiny', 'not null' => FALSE, ], 'safevalue' => [ 'type' => 'text', 'size' => 'tiny', 'not null' => FALSE, ], ], ]; } /** * {@inheritdoc} */ public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) { $properties['value'] = DataDefinition::create('string') ->setLabel(t('Value')); $properties['savevalue'] = DataDefinition::create('string') ->setLabel(t('Safe value')) ->setComputed(TRUE); return $properties; } }
As you can see, there are two columns: value
is supposed to store raw user input. safevalue
is supposed to store a sanitized version of the data.
For testing this. I am just doing this inside hook_node_presave()
:
function mymodule_node_presave(DrupalCoreEntityEntityInterface $entity) { switch ($entity->getBundle()) { case 'mybundle': $entity->field_myfield = ['one', 'two', 'three']; $entity->field_myfield->safevalue = ['one', 'two', 'three']; break; } }
If the field has a cardinality 1 (i.e. the values inserted are scalars), this works fine.
However, if I insert arrays, when I examine the database, and look at the table node__field_myfield
, I see that the columns field_myfield_value
and field_myfield_safevalue
both exist with identical configurations.
If I create a node using the UI, I observe this:
field_myfield_value
column contains three rows with the strings ‘one’, ‘two’ and ‘three’. That’s correct.field_myfield_safevalue
have the string ‘Array’ in its first row, and NULL in the two others. That’s wrong.
I guess that what makes things go wrong is that this is a multivalue field and that I need to use some other action to get the values correctly inserted.
How can I get a multivalue field correctly inserted in the safevalue
column?