Modelless Forms

  • class Cake\Form\Form

Most of the time you will have forms backed by ORM entitiesand ORM tables or other persistent stores,but there are times when you’ll need to validate user input and then perform anaction if the data is valid. The most common example of this is a contact form.

Creating a Form

Generally when using the Form class you’ll want to use a subclass to define yourform. This makes testing easier, and lets you re-use your form. Forms are putinto src/Form and usually have Form as a class suffix. For example,a simple contact form would look like:

  1. // in src/Form/ContactForm.php
  2. namespace App\Form;
  3.  
  4. use Cake\Form\Form;
  5. use Cake\Form\Schema;
  6. use Cake\Validation\Validator;
  7.  
  8. class ContactForm extends Form
  9. {
  10. protected function _buildSchema(Schema $schema)
  11. {
  12. return $schema->addField('name', 'string')
  13. ->addField('email', ['type' => 'string'])
  14. ->addField('body', ['type' => 'text']);
  15. }
  16.  
  17. protected function validationDefault(Validator $validator)
  18. {
  19. $validator->add('name', 'length', [
  20. 'rule' => ['minLength', 10],
  21. 'message' => 'A name is required'
  22. ])->add('email', 'format', [
  23. 'rule' => 'email',
  24. 'message' => 'A valid email address is required',
  25. ]);
  26.  
  27. return $validator;
  28. }
  29.  
  30. protected function _execute(array $data)
  31. {
  32. // Send an email.
  33. return true;
  34. }
  35. }

In the above example we see the 3 hook methods that forms provide:

  • _buildSchema is used to define the schema data that is used by FormHelperto create an HTML form. You can define field type, length, and precision.
  • validationDefault Gets a Cake\Validation\Validator instancethat you can attach validators to.
  • _execute lets you define the behavior you want to happen whenexecute() is called and the data is valid.

You can always define additional public methods as you need as well.

Processing Request Data

Once you’ve defined your form, you can use it in your controller to processand validate request data:

  1. // In a controller
  2. namespace App\Controller;
  3.  
  4. use App\Controller\AppController;
  5. use App\Form\ContactForm;
  6.  
  7. class ContactController extends AppController
  8. {
  9. public function index()
  10. {
  11. $contact = new ContactForm();
  12. if ($this->request->is('post')) {
  13. if ($contact->execute($this->request->getData())) {
  14. $this->Flash->success('We will get back to you soon.');
  15. } else {
  16. $this->Flash->error('There was a problem submitting your form.');
  17. }
  18. }
  19. $this->set('contact', $contact);
  20. }
  21. }

In the above example, we use the execute() method to run our form’s_execute() method only when the data is valid, and set flash messagesaccordingly. We could have also used the validate() method to only validatethe request data:

  1. $isValid = $form->validate($this->request->getData());

Setting Form Values

You can set default values for modelless forms using the setData() method.Values set with this method will overwrite existing data in the form object:

  1. // In a controller
  2. namespace App\Controller;
  3.  
  4. use App\Controller\AppController;
  5. use App\Form\ContactForm;
  6.  
  7. class ContactController extends AppController
  8. {
  9. public function index()
  10. {
  11. $contact = new ContactForm();
  12. if ($this->request->is('post')) {
  13. if ($contact->execute($this->request->getData())) {
  14. $this->Flash->success('We will get back to you soon.');
  15. } else {
  16. $this->Flash->error('There was a problem submitting your form.');
  17. }
  18. }
  19.  
  20. if ($this->request->is('get')) {
  21. $contact->setData([
  22. 'name' => 'John Doe',
  23. 'email' => 'john.doe@example.com'
  24. ]);
  25. }
  26.  
  27. $this->set('contact', $contact);
  28. }
  29. }

Values should only be defined if the request method is GET, otherwiseyou will overwrite your previous POST Data which might have validation errorsthat need corrections.

Getting Form Errors

Once a form has been validated you can retrieve the errors from it:

  1. $errors = $form->getErrors();
  2. /* $errors contains
  3. [
  4. 'email' => ['A valid email address is required']
  5. ]
  6. */

Invalidating Individual Form Fields from Controller

It is possible to invalidate individual fields from the controller without theuse of the Validator class. The most common use case for this is when thevalidation is done on a remote server. In such case, you must manuallyinvalidate the fields accordingly to the feedback from the remote server:

  1. // in src/Form/ContactForm.php
  2. public function setErrors($errors)
  3. {
  4. $this->_errors = $errors;
  5. }

According to how the validator class would have returned the errors, $errorsmust be in this format:

  1. ["fieldName" => ["validatorName" => "The error message to display"]]

Now you will be able to invalidate form fields by setting the fieldName, thenset the error messages:

  1. // In a controller
  2. $contact = new ContactForm();
  3. $contact->setErrors(["email" => ["_required" => "Your email is required"]]);

Proceed to Creating HTML with FormHelper to see the results.

Creating HTML with FormHelper

Once you’ve created a Form class, you’ll likely want to create an HTML form forit. FormHelper understands Form objects just like ORM entities:

  1. echo $this->Form->create($contact);
  2. echo $this->Form->control('name');
  3. echo $this->Form->control('email');
  4. echo $this->Form->control('body');
  5. echo $this->Form->button('Submit');
  6. echo $this->Form->end();

The above would create an HTML form for the ContactForm we defined earlier.HTML forms created with FormHelper will use the defined schema and validator todetermine field types, maxlengths, and validation errors.