On this page
Basic usage
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:
- Wrap a node object into instance of
CFNodeSubjectand 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 isCFDefaultFieldComparatorbut you can define your own by extending default one. - Then attach your observer
BasicUsageObserverto instance ofCFNodeSubject. - Finally execute
CFNodeSubject::notify()method and react on this event inBasicUsageObserver::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.incdependencies[] = changed_fields
More info
See changed_fields_basic_usage module for more information.
Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion