0

How can I intercept the data of a field when the user add's a node?

Below is the use case:

The user can input a address in a field, when the user submits the node. Drupal should make a rest request to the google maps distance matrix api. Then the returning value should be posted in that node. I can find enough example modules to export data from drupal through rest but not the other way around.

1

That sounds like a job for hook_node_presave(NodeInterface $node) to me.

That is always called before a node is saved. To optimize it, you probably want to limit your call to only do it for new nodes or when the value changed (compare your field value with the value of $node->original, note that that only exits when updating, so you want to check something like this:

if (!empty($node->field_yourfield->value) && ($node->isNew() || $node->field_yourfield->value != $node->original->field_yourfield->value)) {
  // do your call here, change $node in any way you want and it will be saved with those updated values
}

The same works for any entity type. You could also limit it to running on form submissions, but this has the advantage that it also works in case nodes are updated or created through other ways.

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.