Jump to content

How to prevent saving with a hook


Inxentas
 Share

Recommended Posts

Hi there! I am making a webapp where the admin can create Surveys, Questions and Answers. These are all Pages with a normal Parent / Child relationship. I want to prevent the admin from making changes to a Survey or it's children as soon as the submissions roll in. For that purpose I am using this code inside a hook, which basicly checks what template the soon-to-be-saved page is. I then find the proper Survey and check whether we have submissions for that Survey in an external table:

public function testSave($event)
    {
        $page = $event->arguments('page');
        $survey = null;
        switch($page->template->name){
            case 'survey':
                $survey = $page;
                break;
            case 'question':
                $survey = $page->parent;
                break;
            case 'answer-choice':
            case 'answer-open':
            case 'answer-rating-1-10':
            case 'answer-rating-1-100':
            case 'answer-rating-likert':
                $survey = $page->parent->parent;
                break;
        }
        if ($survey) {
            $res = $this->db->query("SELECT * FROM submissions WHERE surveyId = " . $survey->id);
            if($res->num_rows > 0){
                $this->error("There are already " . $res->num_rows . " submissions for " . $survey->title);
            }   
        }
    }

Works like a charm, with one exception. I do wish to prevent the page from being saved, but throwing an error doesn't prevent this. It doesn't seem to matter how I implement this in my module's init() method. These two lines of code have the exact same effect: the red warning appears, but values are still saved.

$this->pages->addHookBefore('Pages::save', $this, 'testSave'); 
$this->pages->addHookBefore('Pages::saveReady', $this, 'testSave'); 

Is there a way to tell ProcessWire to NOT save the page when a certain condition is met? Thanks for your future replies!

Link to comment
Share on other sites

What about using

$page->addStatus(Page::statusLocked);

on the first save occourence?
So when a page belonging to a survey is first saved, the next time is accessed it would have a status "locked". I'm not sure if your "admin" user also corresponds to a "super-user" role. In that case I would suggest assign to him a different role, in which case you should dismiss the hook logic and define granular edit permissions for those survey pages.

  • 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

  • Recently Browsing   0 members

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