Basic usage

Last updated on
23 March 2018

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

Changed Fields API is built on "Observer" pattern. The idea is pretty simple: attach observers to a node subject which will notify all of them about changes in node fields.

Observer

Define class that implements CFObserverInterface interface. This interface provides two methods: CFObserverInterface::getInfo() and CFObserverInterface::update(SplSubject $nodeSubject). First method should return an associative array keyed by content type names which in turn contain a list of field names you want to observe. Second method is a place where you can react on changed fields and do something with a node. It will be called only if some of listed fields were changed.

<?php

/**
 * @file
 * Observer example.
 */

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

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

  /**
   * {@inheritdoc}
   */
  public function update(SplSubject $nodeSubject) {
    $node = $nodeSubject->getNode();
    $changedFields = $nodeSubject->getChangedFields();

    // Do something with $node depends on $changedFields.
  }

}

Node presave

In order to detect changed fields in a node we need to do several steps:

  1. Wrap a node object into instance of CFNodeSubject and set up the field comparator. Field comparator is an object which checks needed fields and returns differences between old and new field values. Default comparator is CFDefaultFieldComparator but you can define your own by extending default one. 
  2. Then attach your observer BasicUsageObserver to instance of CFNodeSubject.
  3. Finally execute CFNodeSubject::notify() method and react on this event in BasicUsageObserver::update(SplSubject $nodeSubject) if some of field values of registered node types have been changed.
<?php

/**
 * @file
 * Basic field comparator usage example.
 */

/**
 * Implements hook_node_presave().
 */
function hook_node_presave(stdClass $node) {
  // Create CFNodeSubject object that will check node fields with CFDefaultFieldComparator.
  $nodeSubject = new CFNodeSubject($node, new CFDefaultFieldComparator());

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

  // Notify all attached observers about changed fields.
  $nodeSubject->notify();
}

Includes and dependencies

Do not forget to include a file with defined observer and add dependency to Changed Fields API module to your *.info file:

  • files[] = path/to_your_file_with_observer.inc
  • dependencies[] = changed_fields

More info

See changed_fields_basic_usage module for more information.

Help improve this page

Page status: No known problems

You can: