Definizione di un blocco in un modulo Drupal
Parte V di Guida pratica alla creazione di moduli base in Drupal 8
Dallo .info ai test, solo le basi
Ricordate, all’inizio di questa lezione ho detto che avremmo definito un blocco con un form? Bene, è arrivato il momento di occuparci di questo.
/src/Form/LoremIpsumBlockForm.php
<?php
namespace Drupal\loremipsum\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
* Lorem Ipsum block form
*/
class LoremIpsumBlockForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'loremipsum_block_form';
}
Questo file è molto simile al file delle impostazioni, tranne per il fatto che estende la classe FormBase.
Ha anche un metodo buildForm() come questo:
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
// Quanti paragrafi?
$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?'),
];
// Quante frasi?
$form['phrases'] = [
'#type' => 'textfield',
'#title' => $this->t('Phrases'),
'#default_value' => '20',
'#description' => $this->t('Maximum per paragraph'),
];
// Submit.
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Generate'),
];
return $form;
}
Questo metodo viene usato per inserire il form in un blocco, con cui gli utenti possono configurare quanta parte di testo fittizio vogliono generare.
Non dimenticare anche i metodi validateForm() e 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'),
]);
}
}
E ora il blocco vero e proprio.
<?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;
/**
* Fornisce un blocco Lorem Ipsum con cui generare testo fittizio ovunque.
*
* @Block(
* id = "loremipsum_block",
* admin_label = @Translation("Lorem ipsum block"),
* )
*/
class LoremIpsumBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
// Restituisce il form @ Form/LoremIpsumBlockForm.php.
return \Drupal::formBuilder()->getForm('Drupal\loremipsum\Form\LoremIpsumBlockForm');
}
La classe LoremIpsumBlock estende BlockBase e, come tale, ha quattro metodi che devono essere implementati: build(), blockAccess(), blockForm() e blockSubmit(). Il primo mostra semplicemente il form definito nel nostro passo precedente.
Poi gestiamo il controllo degli accessi:
/**
* {@inheritdoc}
*/
protected function blockAccess(AccountInterface $account) {
return AccessResult::allowedIfHasPermission($account, 'generate lorem ipsum');
}
Definiamo il nostro form di configurazione del blocco per la schermata di amministrazione:
/**
* {@inheritdoc}
*/
public function blockForm($form, FormStateInterface $form_state) {
$form = parent::blockForm($form, $form_state);
$config = $this->getConfiguration();
return $form;
}
Gestore dell’invio:
/**
* {@inheritdoc}
*/
public function blockSubmit($form, FormStateInterface $form_state) {
$this->setConfigurationValue('loremipsum_block_settings', $form_state->getValue('loremipsum_block_settings'));
}
}
Ora il nostro blocco dovrebbe essere funzionante.