On this page
Basic usage
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 ObserverInterface interface. This interface provides two methods: ObserverInterface::getInfo() and ObserverInterface::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
* 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',
],
];
}
/**
* {@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
NodeSubjectand 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 isdefault_field_comparatorbut you can define your own by extending default one. - Then attach your observer
BasicUsageObserverto instance ofNodeSubject - Finally execute
NodeSubject::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
* 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();
}
Dependencies
Do not forget to include a file with defined observer and add dependency to Changed Fields API module to your *.info.yml file:
dependencies:
- changed_fieldsMore 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