Difference between 8.x-2.x and 8.x-3.x branches

Last updated on
23 March 2018

Observer

In 8.x-3.x module supports any entity type. Therefore ObserverInterface::getInfo() should return an associative array keyed by entity types with values as an associative array keyed by bundle names with an array of field names as values.

8.x-2.x

<?php

/**
 * @file
 * Contains BasicUsageObserver.php.
 */

namespace Drupal\changed_fields_basic_usage;

use Drupal\changed_fields\ObserverInterface;
use SplSubject;

/**
 * Class BasicUsageObserver.
 */
class BasicUsageObserver implements ObserverInterface {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    return [
      'article' => [
        'title',
        'body',
      ],
    ];
  }

}

8.x-3.x

<?php

namespace Drupal\changed_fields_basic_usage;

use Drupal\changed_fields\ObserverInterface;
use SplSubject;

/**
 * Class BasicUsageObserver.
 */
class BasicUsageObserver implements ObserverInterface {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    return [
      'node' => [
        'article' => [
          'title',
          'body',
        ],
      ],
    ];
  }

}

Node presave

In 8.x-3.x we can react on changed fields in any entity. Therefore, hook_node_presave can be changed to hook_ENTITY_TYPE_presave or in general to hook_entity_presave. Additionally, NodeSubject class is replaced by more generic EntitySubject class. Please note that module supports only content entities - those who implement ContentEntityInterface interface.

8.x-2.x

<?php

/**
 * @file
 * Contains changed_fields_basic_usage.module.
 */

use Drupal\changed_fields\NodeSubject;
use Drupal\changed_fields_basic_usage\BasicUsageObserver;
use Drupal\node\NodeInterface;

/**
 * Implements hook_node_presave().
 */
function changed_fields_basic_usage_node_presave(NodeInterface $node) {
  // Create NodeSubject object that will check node fields by DefaultFieldComparator.
  $nodeSubject = new NodeSubject($node, 'default_field_comparator');

  // Add your observer object to NodeSubject.
  $nodeSubject->attach(new BasicUsageObserver());

  // Check if node fields have been changed.
  $nodeSubject->notify();
}

8.x-3.x

<?php

use Drupal\changed_fields\EntitySubject;
use Drupal\changed_fields_basic_usage\BasicUsageObserver;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityInterface;

/**
 * Implements hook_entity_presave().
 */
function changed_fields_entity_presave(EntityInterface $entity) {
  if ($entity instanceof ContentEntityInterface) {
    // Create EntitySubject object that will check entity fields by DefaultFieldComparator.
    $entity_subject = new EntitySubject($entity);

    // Add your observer object to EntitySubject.
    $entity_subject->attach(new BasicUsageObserver());

    // Check if entity fields have been changed.
    $entity_subject->notify();
  }
}

Help improve this page

Page status: No known problems

You can: