Um in Drupal 8 per Code einen Block zu erschaffen wird im wesentlichen
- Klasse
BlockBase
erweitert - und dabei die Funktion
build()
überschrieben.
Zu beachten ist die übliche PSR-4 Struktur, damit Drupal den Block auch findet.
Für ein Module my_module
(üblichweise in modules/custom/my_module/
) braucht es dann src/Plugin/Block/MyBlock.php
:
<?php
namespace Drupal\my_module\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Provides a 'MyBlock' block.
*
* @Block(
* id = "my_block",
* admin_label = @Translation("My first block"),
* )
*/
class MyBlock extends BlockBase {
/**
* Builds my block..
*
* {@inheritdoc}
*/
public function build() {
return ['#markup' => $this->t('This is my block :)')];
}
}
Das wars schon. drush cr
und der Block kann ganz normal via Struktur -> Blocklayout eingebunden werden.
Konfiguration
Um den Block aber nicht ganz so billig zu lassen, spendieren wir noch einen eigenen Konfigurations-Parameter. Dazu wird
blockForm()
überschrieben, dasparent::blockForm()
aufruft, um die Grundeinstellungen zu behalten- und neue Form-Elemente hinzufügt
/**
* Configuration form for our block.
*
* {@inheritdoc}
*/
public function blockForm($form, FormStateInterface $form_state) {
$form = parent::blockForm($form, $form_state);
$config = $this->getConfiguration();
$form['my_new_parameter'] = array(
'#title' => $this->t('New Parameter'),
'#description' => $this->t('A cool description.'),
'#type' => 'textfield',
'#default_value' => isset($config['my_new_parameter']) ? $config['my_new_parameter'] : '',
);
return $form;
}
Dann noch eine blockSubmit()
Funktion, die unsere Werte speichert:
/**
* Submit configuration form for our block - saves 'form mode'.
*
* {@inheritdoc}
*/
public function blockSubmit($form, FormStateInterface $form_state) {
$this->setConfigurationValue('my_new_parameter', $form_state->getValue('my_new_parameter'));
}
Den neuen Parameter können wir dann in build() abfragen:
public function build() {
$config = $this->getConfiguration();
if (!isset($config['my_new_parameter']) || empty($config['my_new_parameter'])) {
$my_new_parameter = 'MY DEFAULT VALUE';
} else {
$my_new_parameter = $config['my_new_parameter'];
}
return ['#markup' => $this->t('This is my block - parameter "@par"', ['@par' => $my_new_parameter])];
}
Neuen Kommentar hinzufügen