Drupal 8/9 blocks are implemented as plugins. Sometimes you want that plugin to have some configuration that is specific to it's instance, here's how.
Let's create a simple block plugin that accepts a text value (some slander specifically) and spits it back out directly in your face. Note: you will first need to have a custom module created, if you're not sure how to do that, then get outta here you dirty cheater and checkout Creating Custom Modules
Next we'll create the block. Create the following file /modules/custom/my_module/src/Plugin/Block/Slander.php
php
/**
* Provides a block to place slander on the site.
*
* @Block(
* id = "slander",
* admin_label = @Translation("Slanderous Statement"),
* category = @Translation("Custom")
* )
*/
class Slander extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
$build['comment'] = [
'#markup' => $this->t('Bryan stole the cookie from the cookie jar.'),
];
return $build;
}
}
Great, Now we have a block to work with, but the slander is pretty lame, so lets allow the user to define it. Luckily, most of this work is already done, we're already extending BlockBase which has both a BlockForm() and BlockSubmit() method ready for us to use.
Lets add the text field:
php
/**
* {@inheritdoc}
*/
public function blockForm($form, FormStateInterface $form_state) {
$form['custom_slander'] = [
'#title' => $this->t('Custom slander about Bryan.'),
'#type' => 'textfield',
'#default_value' => $this->configuration['custom_slander'],
];
return $form;
}
/**
* {@inheritdoc}
*/
public function blockSubmit($form, FormStateInterface $form_state) {
$this->configuration['custom_slander'] = $form_state->getValue('custom_slander');
}
You'll notice I assume that the configuration exists, that's because I've moved the original comment to be the default like this:
php
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'custom_slander' => $this->t('Bryan stole the cookie from the cookie jar.')
];
}
And now we can output our custom configuration in the build() method:
php
/**
* {@inheritdoc}
*/
public function build() {
$build['comment'] = [
'#markup' => $this->configuration['custom_slander'],
];
return $build;
}
WOOOOOOOOO:
