Skip to main content
edited tags
Link
avpaderno
  • 97.9k
  • 15
  • 164
  • 284
Source Link

Custom field type validation in field type definition class

Scenario: I created custom field type and need to add my own custom constraint/validation prior to saving.

Problem: failed to add custom constraint plugin so I implemented the function in

public function preSave() {
$return = $this->custom_check($this->value, $this->getSetting('check_options'));
if(!$return[0]){
  drupal_set_message($return[1]->__toString(), 'error');
  $url = \Drupal::service('path.current')->getPath();
  $response = new RedirectResponse($url);
  $response->send();
  exit;
}
}

function custom_check($value, $check_options){
//checking goes here
}

I user drupal_set_message() and RedirectResponse as I couldn't get the $form or $formState of the node/%nid/edit to set the error at field and dor form rebuid.

I know that solution is not the best practice and I have to create my own constraints and validation but I spent time with no luck to work and I didn't found a working example that suits my case escpicially I need to validate based on field settings so I have to pass two parameters value and setting.

Please help getting the current form array and formstate in presave to rebuild instead of redirect. or show me how to write simple constraint that takes parameters and how to add it to my custom defined field type.

Thanks in advance.