Suggest a feature
×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: PHP
Posted by: Abdul Gaffar
Added: Oct 23, 2020 8:15 AM
Modified: Oct 23, 2020 8:38 AM
Views: 13
  1. /**
  2.  * Implements hook_entity_presave().
  3.  */
  4. function MODULE_entity_presave(EntityInterface $entity) {
  5.   if ($entity->bundle() == 'CONTENT_TYPE_MACHINE_NAME') {
  6.     $db = \Drupal::database();
  7.     // Get a single value out of the database.
  8.     $myval = $db->query("SELECT entity_id FROM {mytable} WHERE entity_id = :id", [':id' => $entity->id()])->fetchField();
  9.     if (!empty($myval)) {
  10.       $result = $db->update('mytable')
  11.         ->fields([
  12.           'entity_id' => $entity->id(),
  13.           'myfield' => $entity->get('node_field')->get(0)->value,
  14.         ])
  15.         ->execute();
  16.     }
  17.     else {
  18.       $result = $db->insert('mytable')
  19.         ->fields([
  20.           'entity_id' => $entity->id(),
  21.           'my_field' => $entity->get('node_field')->get(0)->value,
  22.         ])
  23.         ->execute();
  24.     }
  25.   }
  26. }