I wanted to create a module named "my_module" which list out a simple form, I achieved this in drupal 8 with the following steps
- Create a folder named "my_module" in "/sites/all/modules". Create "all/modules" directory if it does not exist
- Create info file my_module.info.yml with following information
name: My module description: Hanldes my custom functionalities. type: module version: '1.0' core: '8.x'
- Create my_module.routing.ym file which handles menu for my custom module, In my custom module I want to display a custom form which is handled as below
my_module_form.form: path: '/my-form' defaults: _title: 'My form' _form: '\Drupal\my_module\Form\MyForm' // You can specify forms or controllers in this section requirements: _permission: 'access content'
- 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; }
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')))); } }
- Enable "my_module" at admin/modules
- Clear cache at admin/config/development/performance
- Load and test page in /my-form
Hope this hepls!