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 :
<?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