I have a custom field type that I create with a custom module. It is a plain text field where the user type in a string. I want to retain two copies of this field:
- The exact string value as typed by the user.
- A safe value of the same string.
This is how I create the field:
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,
],
],
];
}
…
}
I assume I should generate a safevalue
of the string in hook_node_presave()
and somehow get into the entity there (but corrections to these assumptions are welcome).
I have no problem getting the string value as typed by the user and to compute a safe value:
$value = $entity->field_myfield->getString();
$safevalue = makeSafe($value);
But I do not know how to get the $safevalue
stored in the database.
Edit
I see that this has two nearly identical answers. Both work fine if the cardinality of the field is one, so I've upvoted both. Since I cannot accept both, I've accepted the one from apaderno for the extra detail about propertyDefinitions()
.
I am still not able to get this to work with a multivalue field, but I think that probably need to be a separate question.