Jump to content

Custom Template save validation


Adam Kiss
 Share

Recommended Posts

You'd have to hook into Pages::save ($pages->save), not Page::save. If you use a 'before' hook, you could throw an exception if you want to abort the save. This is what I recommend doing. But if throwing an exception doesn't meet your needs, you can also use a 'replace' hook:

If you use a 'replace' hook, $pages->save will never be called on it's own, so you'll have to take over the call. In order to avoid a recursive loop when you call it from your hook, you'll want to call $pages->___save() instead (which bypasses any hooks).

Link to comment
Share on other sites

Hey Ryan,

thanks. Just to illustrate (I don't want exception :)), I'd do it like this?:

 $this->addHookBefore('Pages::save', $this, 'savePageValidation');

 function savePageValidation(){
   if ($everythingIsOk === true) {
     $pages->___save();
   }
 }

?

Also how about that exception - I understand I'd probably need to try catch something, but I'm not too certain.

Link to comment
Share on other sites

Adam, sorry I linked to the wrong message in that thread before. Here's the instructions for the 'replace' hook:

http://processwire.c...ndpost__p__7435

You don't want to call $pages->___save() unless you are using a 'replace' hook. For all other hooks, the original method that you hooked is still called (either before or after your hook). So a 'replace' hook is different in that it tells PW you are completely taking over the implementation. These have not been used a lot, and there is potential for conflicts with other modules hooking the same function. So that's why I say it's probably better to throw an exception where possible. In that case, your hook would look like this:

function savePageValidation($event) {
$page = $event->arguments[0];

$everythingIsOkay = true;

if($page->other != $page->that) {  // pseudocode
	$everthingIsOkay = false;
}

if(!$everythingIsOkay) throw new WireException("Aborted save because other != that");
}

A replace hook would look like this:

function savePageValidation($event) {
$event->replace = true;
$page = $event->arguments[0];
$options = $event->arguments[1];

$everythingIsOkay = true;
if($page->other != $page->that) { // pseudocode
	$everythingIsOkay = false;
}

if($everythingIsOkay) {
	$event->return = wire('pages')->___save($page, $options);
} else {
	$event->return = false;
	$this->error('Page was not saved because other != that');
}
}
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...