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…