Jump to content

Hook with Page(template=order)::changed() called twice


suntrop
 Share

Recommended Posts

I have a field 'history' to track some field's changes. When changing, for example, the field 'state' in the PW backend I get correct result (1 entry).

But when I set 'state' from a template file with:

$page->of(false);
$page->state = 1138; // field state is Page reference and 1138 is a state with title New
$page->save('state');
$page->of(true);

… I have two entries in the 'history' field:

2020-02-06 16:19:40    State -/- => New
2020-02-06 16:19:40    State -/- => -/-
$this->addHookAfter('Page(template=testtemplate)::changed()', function($event) {

	/* @var $event HookEvent */
	/* @var $page Page */
	$page = $event->object;
	$field = $event->arguments(0); // field
	$old = $event->arguments(1); // old value
	$new = $event->arguments(2); // new value

	$track_fields = ['title', 'state', 'items'];
	if (!in_array($field, $track_fields)) return;

	$label = fields()->get($field)->getLabel();
	bd($old, $label . ' old');
	bd($new, $label . ' new');


	$old_value = ($old instanceof Page) ? $old->title : '-/-';
	$new_value = ($new instanceof Page) ? $new->title : '-/-';


	$history = date('Y-m-d H:i:s') . "\t" . $label . ' ' . $old_value . ' => ' . $new_value;

	// $page->history = $page->history . PHP_EOL . $history;
	$page->setAndSave('history', $page->history . PHP_EOL . $history);
});

Running this in TracyDebugger will result in two entries as well:

$page->setAndSave('state', 'new');

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...