0

I have a config entity with a form which extends Drupal\Core\Entity\EntityForm, which has a public form() and a public save() methods. They both work fine and dandy. I want to validate some information before saving the form. As far as I can tell there's a validateForm() method already built in via the class it extends.

I can't seem to find much information on how to do that. I've tried the obvious, simply setting a return false in the validateForm method but it doesn't seem to be called at all.

I don't have much experience with Drupal in general so I'm obviously doing something wrong.

If anybody could point me in the right direction here, I'd be grateful.

I'd also like to keep the field values in case of an error. I can only assume that that happens by default, but then again I may be wrong.

1

You can override the validateForm method in your own form class. Just declare a method like so:

public function validateForm(array &$form, FormStateInterface $form_state) {
  // Your custom validation code.
}

Since the Drupal\Core\Form\FormBase (parent of Drupal\Core\Entity\EntityForm) class has no validation, just a blank method, there is no need to call the parent method from your own class.

  • I did overwrite the parent method in my own classs, but it doesn't seem to be called at all. As I said, I assume I'm doing something wrong. – Andrew Jun 26 '17 at 10:17
  • It should call the validateForm(), I just checked in one of my own entity forms. What happens if you place an exit() in the validateForm() method? P.S. Errors can be added by calling the setErrorByName() or setError() methods on the $form_state not by returning FALSE. – Gun5m0k3 Jun 26 '17 at 10:32
  • You were correct. I keep forgetting to clear the cache. It works properly now. Thanks a bunch. – Andrew Jun 26 '17 at 10:34
  • You're welcome. Glad to help! – Gun5m0k3 Jun 26 '17 at 10:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.