CakePHP 2.x Validating Forms without a Database Model

Written by James McDonald

June 19, 2019

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

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

Controller/NoTableController.php

// 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.

You May Also Like…

Squarespace Image Export

To gain continued access to your Squarespace website images after cancelling your subscription you have several...

MySQL 8.x GRANT ALL STATEMENT

-- CREATE CREATE USER 'tgnrestoreuser'@'localhost' IDENTIFIED BY 'AppleSauceLoveBird2024'; GRANT ALL PRIVILEGES ON...

Exetel Opt-Out of CGNAT

If your port forwards and inbound and/or outbound site-to-site VPN's have failed when switching to Exetel due to their...