Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

Compare Two entity programmatically

By editor , 18 April, 2016
Question

How to compare two nodes programmatically ?
Get the diff of nodes programmatically, when saving or updating a node  to know the difference ?

Example:

function mymodule_entity_update($entity, $type) {
  if ($type == 'user' || $type == 'node') {
    if (!empty($entity->nid)) {
      $entity_old = node_load($entity->nid);
    }
    else {
      $entity_old = user_load($entity->uid);
    }
    $dif = _mymodule_entity_compare($entity, $entity_old);
  }
}


function _mymodule_entity_compare($entity_new, $entity_old) {

  $old = (array) $entity_old;
  $new = (array) $entity_new;
  $dif = array();

  $count = 0;
  foreach ($new as $key => $val) {
    if (isset($old[$key]) && ($key === 'title' || strstr($key, 'field_'))) {
        $field_new = $new[$key];
        $field_old= $old[$key];
        $field_dif = $field_new;
         _mymodule_getfielddiffs($field_new, $field_old, $field_dif);
        if($field_dif){
          $dif[$key]=$field_dif;
        }
    }
  }

  return $dif;
}

function _mymodule_getfielddiffs($field_new, $field_old, &$field_dif) {

  if (is_array($field_new)) {
    foreach ($field_new as $key => $value) {
      if (isset($field_dif[$key])) {
        if (!_mymodule_getfielddiffs($field_new[$key], $field_old[$key], $field_dif[$key])) {
          unset($field_dif[$key]);
        }
      }
    }
    if(!count($field_dif)){
      return FALSE;
    }
    return TRUE;
  }
  else {
    if ($field_new == $field_old) {
      return FALSE;//No Diff
    }
    else {
      $field_dif = $field_old; // Save old value in to Diff Table (so save)
      return TRUE; // Diff
    }
  }
}

Tags

  • Drupal 8
  • Code
  • Drupal 7

Comments

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer