Outils pour utilisateurs

Outils du site


drupal9:modules:form

Formulaire

Définir une route qui mène au formulaire :

mymodule/mymodule.routing.yml
mymodule.form:
  path: '/mon-formulaire'
  defaults:
    _form: '\Drupal\mymodule\Form\MyForm'
    _title: 'Mon premier formulaire'
  requirements:
    _permission: 'access content'
mymodule/src/Form/MyForm.php
<?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
  ) {
    //...
  }
}

Construction du formulaire

mymodule/src/Form/MyForm.php
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;
}

Validation du formulaire

mymodule/src/Form/MyForm.php
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.

Soumission du formulaire

mymodule/src/Form/MyForm.php
public function submitForm(
  array &$form,
  FormStateInterface $form_state
) {
 
  // Afficher un message à l'utilisateur
  \Drupal::messenger()->addMessage("Le formulaire a été correctement posté.");
 
}
drupal9/modules/form.txt · Dernière modification: 2021/02/17 07:05 (modification externe)