cmcintosh's picture

How to create a custom Drupal 8 Form

If your like many of the Drupal 7 developers or other php developers just getting started with Drupal 8 you may be scratching your head about some of the major changes that have happened to Drupal.  With the change to using Symfony for the core api for Drupal 8, many of the old ways of creating custom forms wont work now.  Now you need to define your forms in an Object Oriented form, and let Drupal know about it by placing it in the right spot.  So in this article I hope to go over a bit how you can create a custom form for Drupal 8 in a way that will make it easy for you to unerstand.

There are several types of forms in Drupal 8 deriving from the ConfigFormBase, EntityForm, and FormBase.  Below I will mostly just be going over the FormBase type of forms, but the others can be useful to understand as well.

To start the form, we need to define it's namespace as well as include a few other classes in order to perform the tasks we need.  We also need to create a getFormId function, this will be used by Drupal 8 for notifying the system of the id of your form, which is also used as part of the hook_form_alter capability in Drupal 8. Once we have those basics in place we then need to create three primary functions that match up with how the old Drupal 7 Form API worked.  Those three are buildForm, validateForm, submitForm these are similar how you would create a form, validation function, and submit function Drupal 7.  Below you can see this code in action.

Our first function, buildForm returns a render array that contains our Form deffinition that will then be rendered by the Drupal 8 API. Once the user clicks the submit function the Validation function is then called which allows you to validate any input that the user has provided and throw errors where you need to.

We finally are coming to the end of our form code, where we are going to actually act on the form data in the submit function and then the process for our form is complete.  This is of course the bare minimum for a custom form.  You can extend this with AJAX functionality, and include various javascript libraries to improve your user's experience.

Planned Topic: