CakePHP 2.x Validating Forms without a Database Model

by | Jun 19, 2019 | IT Tips | 0 comments

I have a CakePHP form that I need to validate but the form fields don't equate to anything in a database table or model.

To get it to work I create a dummy 'Model' using ClassRegistry::init, attach all the necessary validation rules, set the POST data from the form to the Model and then validate it

View/NoTable/index.ctp

1
2
3
4
5
6
// view
<?=$this->Html->tag('h2', 'TestForm form');?>
<?=$this->Form->create('TestForm');?>
<?=$this->Form->input('input1');?>
<?=$this->Form->submit();?>
<?=$this->Form->end();?>

Controller/NoTableController.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// controller & action
class NoTableController extends Controller
{
    public function index()
    {
        if ($this->request->is('POST')) {
            $this->log('POST');
            $this->log($this->request->data);
            $this->log(array_keys($this->request->data)[0]);
 
            /**
             * Create a model using the form name
             */
            $model = ClassRegistry::init(
                [
                    'class' => array_keys($this->request->data)[0],
                    'table' => false,
                    'type' => 'Model'
                ]
            );
 
            /**
             * Add your validation rules here. Just like in a model
             */
            $model->validate = [
                'input1' => [
                    'notBlank' => [
                        'rule' => 'notBlank',
                        'required' => true,
                        'message' => 'Please enter some text'
                    ]
                ]
            ];
 
            $model->set($this->request->data);
 
            if ($model->validates()) {
                // do stuff because validation passes
                $this->Flash->success(__('Thanks for the data'));
            } else {
 
                $this->Flash->error(__('Missing data. Please re-try.'));
 
            }
        }
 
    }
}
Form at start
Form Submitted with text input empty triggers 'noBlank' validation rule
Form submitted with correct content passes validation

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.