Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Form::setData([]) to remove input values of a contact form after sending email not working in CakePHP?

I’ve created a contact form in Cakephp 4 refering to the doc (https://book.cakephp.org/4/en/core-libraries/form.html).

I have a problem to remove input values after the email has been sent.

Here’s my ContactController.php :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<?php

namespace App\Controller;

use App\Controller\AppController;
use App\Form\ContactForm;

class ContactController extends AppController
{
    public function index()
    {
        $contact = new ContactForm();

        if ($this->request->is('post')) {
            if ($contact->execute($this->request->getData())) {
                $this->Flash->success('We will get back to you soon.');
                $contact->setData([]); // I want to remove data in contact form after the email has been sent, but it doesn't work
            } else {
                $this->Flash->error('There was a problem submitting your form.');
            }
        }

        $this->set('contact', $contact);
    }
}

Why is $contact->setData([]); in the code abode not removing data in my contact form ?

>Solution :

The form helper will prefer request data, eg the POST data from your form submit, otherwise the input would always get lost when a validation error occurs.

If you want to show the form page again after successful submit, then you should redirect to the current page, that’s called the PRG (Post-Redirect-Get) pattern.

So instead of $contact->setData([]);, do:

return $this->redirect(['action' => 'index']);

That’s also what your baked controllers will do for add and edit actions.

See also

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading