Outils pour utilisateurs

Outils du site


drupal9:modules:form

Ceci est une ancienne révision du document !


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 functin 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) {
 
}

Soumission du formulaire

mymodule/src/Form/MyForm.php
public function submitForm(array &$form, FormStateInterface $form_state) {
 
}
drupal9/modules/form.1613540691.txt.gz · Dernière modification: 2021/02/17 05:44 (modification externe)