Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manipulate value before node is saved in Drupal 8?

I have an editing node form. When user enters new value and clicks on submit to edit the node, I first want to get the old node back, manipulate the value and then just save/update the node.

Below is my solution, but it does not work.

function custom_module_form_node_form_alter(&$form, FormStateInterface $form_state) {
    $editing_entity = $form_state->getFormObject()->getEntity();

    if (!$editing_entity->isNew()) {
        $form['actions']['submit']['#submit'][] = 'custom_module_node_form_submit';
    }
}

function custom_module_node_form_submit($form, FormStateInterface $form_state) {
   $editing_entity = $form_state->getFormObject()->getEntity();

   $entity = Drupal::entityTypeManager()->getStorage('node')->load($editing_entity->id());
}

In the form_submit hook, I tried to get the old node back but it is already too late and the node is already updated/saved. How can I get the old node back and manipulate the value before updating/saving the node in Drupal 8?

like image 379
O Connor Avatar asked Jan 03 '23 08:01

O Connor


1 Answers

Try using hook_entity_presave():

/**
 * Implements hook_entity_presave().
 */
function YOUR_MODULE_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  switch ($entity->bundle()) {
    // Here you modify only your day content type
    case 'day':
      // Setting the title with the value of field_date.
      $entity->setTitle($entity->get('field_date')->value);
     break;
  }
}

Solution taken from here: https://drupal.stackexchange.com/questions/194456/how-to-use-presave-hook-to-save-a-field-value-as-node-title

Also you can get old value like: $entity->original. Check it out here:

https://drupal.stackexchange.com/questions/219559/how-to-get-the-original-entity-on-hook-entity-presave

like image 59
MilanG Avatar answered Jan 08 '23 20:01

MilanG