Jump to content

[Solved] Set table field via a hook


ngrmm
 Share

Recommended Posts

I would like to run this via a hook:

$page->of(false);
foreach($page->table as $row) {
	if($row->pass == "") {
		$pass = new Password();
		$string = $pass->randomAlnum(22);
		$row->pass = $string;
	}
}
$page->save('table');

and tried this:

$this->addHookAfter('Pages::save', function($event) {
	$p = $event->arguments('page');		
	if($p->id == 1599) return; // my page
	$p->of(false);
	foreach($p->table as $row) {
		if($row->pass == "") {
			$pass = new Password();
			$string = $pass->randomAlnum(22);
			$row->pass = $string;
		}
	}
	$p->save('table');
});

But I get a 500 error. Is it an infinite loop?

 

SOLVED

Edited by ngrmm
solved
Link to comment
Share on other sites

this worked
 

$this->addHookBefore('Pages::save', function($event) {
	$p = $event->arguments("page");
	if($p->id == "1599") {
		$p->of(false);
		foreach($p->table as $row) {
			if($row->pass == "") {
				$pass = new Password();
				$string = $pass->randomAlnum(22);
				$row->pass = $string;
			}
		}
	}
});

 

  • Like 1
Link to comment
Share on other sites

  • ngrmm changed the title to [Solved] Set table field via a hook

Great you solve it. Jut for explanation: if you hook after Pages::save and save the page again within that hook, this will cause an infinite loop as you already have observed.

To avoid this you can either use a before hook like you did or take advantage of the the $page->save([options]) by using `$page->save(['noHooks' => true])`

  • Like 2
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

×
×
  • Create New...