0

I'm trying to alter the value of entity text fields upon node save, even the custom-made fields

so far I've managed to do that with the title and default body field but not with a custom field, I'm trying to target any field that might be a text field, here's my code:

function MODULENAME_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  $replacement_pattern = array("/a/", "/b/"); 
  $replacement = array("c", "d");

  /* Check whether it's a node */
  if ($entity instanceof \Drupal\node\NodeInterface) {
    // Node title
    $nodeTitle = $entity->getTitle();
    $entity->setTitle(preg_replace($replacement_pattern, $replacement , $nodeTitle));

    // Body main
    if(!empty($entity->body->value)) {
      $entity->body->value = preg_replace($replacement_pattern, $replacement , $entity->body->value);
    }

    // Body Summary
    if(!empty($entity->body->summary)) {
      $entity->body->summary = preg_replace($replacement_pattern, $replacement , $entity->body->summary);
    }
  }
}
2

1 Answer 1

0

Another approach by checking field name. I think this will get you the "custom" field part, but not the "all" fields part:

MYMODULE.module:

use Drupal\Core\Entity\EntityInterface;

function MYMODULE_node_presave(EntityInterface $entity) {
  if ($entity->hasField('field_name')) {
    $entity->get('field_name')->value = preg_replace(
      $toReplace,
      $newText,
      $entity->get('field_name')->value
    );
  }
}

But this only checks for fields of that name. I am also looking for a way to alter the value of a ckeditor/text field by testing field type instead of field name.

I would have hoped setting the field name value to something like text_long would have worked. This is a base field hook suggestion, but I am not having any luck at this time.

To add to the use case, it would be nice to alter ckeditor/text fields whether attached directly to the node, or via a Paragraph type.

The answer in the comment link above is helpful, but I have not succeeded in implementation.

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.