I am parsing pdf's in a field for a custom content type in a cron job. I have a boolean on each node that determines whether their pdf has already been parsed. I grab the ones I need like so:
$query = \Drupal::entityQuery('node')
->condition('status',1)
->condition('type', 'issue')
->exists('field_pdf')
->condition('field_indexed',false)
->sort('created','ASC');
if($range > 0){
$query->range(0,$range);
}
$issue_nids = $query->execute();
$issue_nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($issue_nids);
foreach ($issue_nodes as $issue_node){
//do my pdf parsing magic on field_pdf
$node->field_indexed->value = true;
$node->save();
}
This works fine but if the user replaces field_pdf and uploads a new one I want to make field_indexed false again so I know to reindex it. The problem is I don't really have a way of knowing whether the field changed.
I considered using a presave hook but I didn't see a way to compare the form state to what was currently on the node.
Is there a way I can detect when a field has changed when a node has saved?
$entity->original
, which contains the original’s field values. Use those for comparison