Suppose you have a custom module called my_module in which you want to create the form.
Step 1: Intially we will need to add the menu for form in my_module.routing.yml
my_module_form.form: path: '/my-form' defaults: _title: 'My form' _form: '\Drupal\my_module\Form\MyForm' requirements: _permission: 'access content'
Step 2: Now in the my_module create a folder "Form" inside src folder(create src folder if it does not exist).Inside Form folder create MyForm.php and add the below code
namespace Drupal\my_module\Form; use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormStateInterface; use Drupal\Component\Utility\UrlHelper; /** * Contribute form. */ class MyForm extends FormBase { /** * {@inheritdoc} */ public function getFormId() { return 'my_form'; } /** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $form['user_name'] = array( '#type' => 'textfield', '#title' => $this->t('User Name') ); return $form; }
Step 3: Implement submit function
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { drupal_set_message($this->t('Welcome @user', array('@user' => $form_state->getValue('user_name')))); } }
Step 4: Enable the module and test the form in /my-form