Définition d’un bloc dans un module Drupal
Partie V de Guide pratique pour créer des modules basiques Drupal 8
De .info aux tests, uniquement les bases
Vous vous souvenez, dans le début de ce tutoriel, j'avais dit que nous allions définir un bloc avec un formulaire ? Eh bien, il est temps d’y venir.
/src/Form/LoremIpsumBlockForm.php
<?php
namespace Drupal\loremipsum\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
* Formulaire du bloc Lorem Ipsum
*/
class LoremIpsumBlockForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'loremipsum_block_form';
}
Ce fichier ressemble beaucoup à un fichier de configuration, sauf qu’il étend FormBase.
Il possède aussi une méthode buildForm() comme ceci :
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
// Combien de paragraphes ?
// $options = new array();
$options = array_combine(range(1, 10), range(1, 10));
$form['paragraphs'] = [
'#type' => 'select',
'#title' => $this->t('Paragraphs'),
'#options' => $options,
'#default_value' => 4,
'#description' => $this->t('How many?'),
];
// Combien de phrases ?
$form['phrases'] = [
'#type' => 'textfield',
'#title' => $this->t('Phrases'),
'#default_value' => '20',
'#description' => $this->t('Maximum per paragraph'),
];
// Bouton de soumission.
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Generate'),
];
return $form;
}
Cette méthode place le formulaire dans le bloc, permettant aux utilisateurs de configurer combien de texte factice ils veulent générer.
N’oubliez pas non plus les méthodes validateForm() et submitForm() :
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$phrases = $form_state->getValue('phrases');
if (!is_numeric($phrases)) {
$form_state->setErrorByName('phrases', $this->t('Please use a number.'));
}
if (floor($phrases) != $phrases) {
$form_state->setErrorByName('phrases', $this->t('No decimals, please.'));
}
if ($phrases < 1) {
$form_state->setErrorByName('phrases', $this->t('Please use a number greater than zero.'));
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$form_state->setRedirect('loremipsum.generate', [
'paragraphs' => $form_state->getValue('paragraphs'),
'phrases' => $form_state->getValue('phrases'),
]);
}
}
Passons maintenant au bloc lui-même.
<?php
namespace Drupal\loremipsum\Plugin\Block;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
/**
* Fournit un bloc Lorem ipsum avec lequel vous pouvez générer du texte factice n'importe où.
*
* @Block(
* id = "loremipsum_block",
* admin_label = @Translation("Bloc Lorem ipsum"),
* )
*/
class LoremIpsumBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
// Retourne le formulaire défini dans Form/LoremIpsumBlockForm.php.
return \Drupal::formBuilder()->getForm('Drupal\loremipsum\Form\LoremIpsumBlockForm');
}
La classe LoremIpsumBlock étend BlockBase et possède donc quatre méthodes à implémenter : build(), blockAccess(), blockForm() et blockSubmit(). Le premier affiche simplement le formulaire défini précédemment.
Voici la gestion du contrôle d’accès :
/**
* {@inheritdoc}
*/
protected function blockAccess(AccountInterface $account) {
return AccessResult::allowedIfHasPermission($account, 'generate lorem ipsum');
}
Définition du formulaire de bloc pour l’écran d’administration du bloc :
/**
* {@inheritdoc}
*/
public function blockForm($form, FormStateInterface $form_state) {
$form = parent::blockForm($form, $form_state);
$config = $this->getConfiguration();
return $form;
}
Le gestionnaire de soumission :
/**
* {@inheritdoc}
*/
public function blockSubmit($form, FormStateInterface $form_state) {
$this->setConfigurationValue('loremipsum_block_settings', $form_state->getValue('loremipsum_block_settings'));
}
}
Maintenant, votre bloc devrait être fonctionnel.