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.'));
}
}
}
}
0 Comments