On the fly / dynamic CakePhp 3 Validation and FormHelper

418 views Asked by At

I am creating a 'form editor' in CakePHP.

The interface allows the user to choose validations to apply to the fields, e.g. Numeric, Email etc.

As such I need to dynamically create validation for the model based on the user input. For this I can use the Validation object: https://book.cakephp.org/3.0/en/core-libraries/validation.html

I want to take advantage of the features of FormHelper, for example, automatically outputting error messages for fields.

I can see how to use a hard-coded validator from the model to do this by setting the validator in the context option for Form->create() - but how do I use a customer $Validator object which has been dynamically created?

Clarification:

I have some code in my controller:

//get the form configuration
$form = $this->Forms->get($id, ['contain'=>['FormFields'=>['Validations']]]);


//set up validation based on the configuration

$validator = new Validator();
foreach($form->form_fields as $field){
  ...
  if($field->required) $validator->notBlank($field->field_name);

}


$table = TableRegistry::get($form->type);

$table->setValidator($validator);

Unfortunately setValidator() is not a method of TableRegistry.

If I set the validation up in the model, I would need the $id parameter to look up the correct form configuration.

1

There are 1 answers

0
Tom Cowle On

I added the following code to my model:

protected $validator = null;  

public function validationDefault(Validator $validator){
  if($this->validator != null) return $this->validator;
  return $validator;
}

public function setValidator(Validator $validator){
  $this->validator = $validator;
}

So the default validator can effectively be set via the setValidator method.

Then in my controller:

//get the form configuration
$form = $this->Forms->get($id, ['contain'=>['FormFields'=>['Validations']]]);


//set up validation based on the configuration

$validator = new Validator();
foreach($form->form_fields as $field){
   ...
   if($field->required) $validator->notBlank($field->field_name);

}


$table = TableRegistry::get($form->type);

$table->setValidator($validator);

I hope this is useful for others.