Définir une route qui mène au formulaire :
mymodule.form: path: '/mon-formulaire' defaults: _form: '\Drupal\mymodule\Form\MyForm' _title: 'Mon premier formulaire' requirements: _permission: 'access content'
<?php namespace Drupal\mymodule\Form; use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormStateInterface; class MyForm extends FormBase { public function getFormId() { return 'mymodule_first_form'; } public function buildForm( array $form, FormStateInterface $form_state) { //... } public function validateForm( array &$form, FormStateInterface $form_state ) { //... } public function submitForm( array &$form, FormStateInterface $form_state ) { //... } }
public function buildForm( array $form, FormStateInterface $form_state ) { $node = \Drupal::routeMatch()->getParameter('node'); $nid = $node->nid->value; // CHAMP DE TYPE TEXTE $form['name'] = [ '#title' => t('Name'), '#type' => 'textfield', '#size' => 50, '#description' => t("Your name."), '#required' => True, ]; // CHAMP DE TYPE EMAIL $form['email'] = [ '#title' => t('Email Address'), '#type' => 'email', '#size' => 25, '#description' => t("We'll send update to this address."), '#required' => True, ]; // BOUTON SUBMIT $form['submit'] = [ '#type' => 'submit', '#value' => t('Save'), ]; // CHAMP CACHÉ $form['nid'] = [ '#type' => 'hidden', '#value' => $nid, ]; return $form; }
public function validateForm( array &$form, FormStateInterface $form_state ) { $value = $form_state->getValue('email'); if(!\Drupal::service('email.validator')->isValid($value)) { $form_state->setErrorByName( 'email', t('The email address %mail is not valid.', ['%mail' => $value]) ); } }
L'appel à setErrorByName stoppe le traitement du formulaire, et submitForm ne sera pas appelé.
Le formulaire est réaffiché et le message d'erreur est inclus sur la page.
public function submitForm( array &$form, FormStateInterface $form_state ) { // Afficher un message à l'utilisateur \Drupal::messenger()->addMessage("Le formulaire a été correctement posté."); }