Articles


How to Create a custom forms in Drupal 8

How to Create a custom forms in Drupal 8



Posted byUttam Kotekar,1st Oct 2015

Drupal 8 forms are represented with nested render array structures as the Drupal 7 and there is a separate validation and submission step as well. Although in Drupal 8 there are some new (HTML 5) elements available then rest its very similiar to Drupal 7 FORM API.

So lets start creating a simple custom forms. Lets say we created a module called "custom_form". So initially we'll create a menu for the form in custom_form.routing.yml file


    custom_form.form:
      path: '/custom-form'
      defaults:
        _title: 'Custom form'
        _form: '\Drupal\custom_form\Form\CustomForm'
      requirements:
    _permission: 'access content'
    

After creating the menu, we need to create a folder called "Form" inside the custom_form module folder. Inside the "Form" folder, lets created a file called "CustomForm.php" and add the below code which we create a simple email forms with validation.


    
    /**
     * @file
     * Contains \Drupal\custom_form\Form\CustomForm.
     */

    namespace Drupal\custom_form\Form;

    use Drupal\Core\Form\FormBase;
    use Drupal\Core\Form\FormStateInterface;
    use Drupal\Component\Utility\UrlHelper;

    /**
     * Contribute form.
     */
    class CustomForm extends FormBase {
      /**
       * {@inheritdoc}
       */
      public function getFormId() {
	return 'custom_form';
      }

      /**
       * {@inheritdoc}
       */
      public function buildForm(array $form, FormStateInterface $form_state) {
      	$form['email_address'] = array(
	        '#type' => 'email',
	        '#title' => $this->t('Your Email Address')
	      );
        return $form;
      }

      /**
       * {@inheritdoc}
       */
      public function validateForm(array &$form, FormStateInterface $form_state) {
        
        if (!filter_var($form_state->getValue('email_address', FILTER_VALIDATE_EMAIL))) {
          $form_state->setErrorByName('email_address', $this->t('The Email Address you have provided is invalid.'));
        }      
        
      }

      /**
       * {@inheritdoc}
       */
      public function submitForm(array &$form, FormStateInterface $form_state) {
        drupal_set_message($this->t('Your Email Address is @email', array('@email' => $form_state->getValue('email_address'))));
      }
    }
    
  

Thats it. Hope this short article has been helpful. Use the comment box below to share your views and doubts regarding this article here