Drupal 8.x
I would like to alter the value of all/any ckeditor/text fields on a node.
Currently working with HOOK_node_presave().
Ideally, I'd like an agnostic approach that doesn't mind where the field is coming from, e.g. paragraph, node, taxonomy, etc.
How can I loop through all fields, check the field type, get and replace the value?
MYMODULE.module
Working with the below code gets me close I think:
use Drupal\Core\Entity\EntityInterface;
function MYMODULE_node_presave(EntityInterface $entity) {
$fieldsArray = \Drupal::service('entity_field.manager')->getFieldMapByFieldType('text_long');
foreach($fieldsArray as $longTextName=>$key) {
kpr($key); // This returns an array of the values I need.
if ($entity->hasField($key)) {
$entity->get($result)->value = preg_replace(
$toReplace,
$replaceWith,
$entity->get($result)->value
);
}
}
}
Try #2;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
function MYMODULE_presave(EntityInterface $entity) {
// Get form config.
// Get config Node field names.
// Get config Paragraph names.
// Get config Paraghraph field names.
// Loop through our Node field names.
foreach($nodeFieldNames as $fieldName) {
// Check if the entity has field.
if ($entity->hasField($fieldName)) {
// Get the field.
$entity->get($fieldName)->value = $newValue;
}
}
// Loop through our Paragraph names.
foreach($paragraphNames as $paragraphName) {
// Check if the entity has field.
if ($entity->hasField($paragraphName)) {
$paragraphs = $entity->$paragraphName->getValue();
foreach ($paragraphs as $paragraphItem) {
$p = \Drupal\paragraphs\Entity\Paragraph::load( $paragraphItem['target_id'] );
foreach($paragraphFieldNames as $paragraphFieldNamesitem) {
if ($p->get($paragraphFieldNamesitem)->value) {
// kpr($p->get($paragraphFieldNamesitem)->value);
$p->get($paragraphFieldNamesitem)->value = $newvalue;
// kpr($p->get($paragraphFieldNamesitem)->value);
// This does alter the value, just does not get saved.
}
}
}
}
}