How to prevent user multiple form submissions? PRG pattern / token?

I’m trying to avoid forms being sent and saved multiple times to the database, for example, if the user click the submit button multiple times or refresh page

I saw two ways: prg pattern and form tokens whats the most recomended form? is there any cakephp 3 plugin for this?

Im using this add function to test without sucess the prg pattern:

    public function add(){
        $user = $this->Users->newEntity();
        
        if ($this->request->is('post')) {
        
            $user = $this->Users->patchEntity($user, $this->request->data);

            if ($this->Users->save($user)) {
                $this->Flash->success(__('User saved.'));

                //$this->setAction('prg_add'); this could work maybe?
                // thats it? or should i pass all the submited data via get to the prg_add action and then process the save() and redirect to index
                return $this->redirect(['controller' => 'Users', 'action' => 'prg_add'], 303);
            }
            $this->Flash->error(__('User not saved.'));
            
        }
        $this->set('user', $user);
    }
 
 
    public function prg_add()
    {
        //what to do here? It would be part of the GET right?
        return $this->redirect(['action' => 'index']);
    }

Perhaps a jquery routine to disable submit button once clicked.

yes, i already have done this but i need a server side solution too

Hmm, normally I’d also only use jQuery to disable the submit button after submission, but if it’s necessary, form tokens should be a fairly reliable solution, not sure about the prg pattern.

You would simply create a hash in the controller action, save it to a session and pass it to the view containing the form. Then add it as a value in a hidden field.

After submission, you would compare the value of your hidden token field with the session value. If it’s the same, save it and delete the session value. Otherwise, show an error.

1 Like