Blocks can provide a setting form. This recipe provides the text My Company for the copyright text. Instead, this can be defined through a text field in the block's setting form.
Let's readdress the Copyright.php file that holds our block's class. We will override methods provided by our base class. The following methods will be added to the class written in this recipe.
A block can override the default defaultConfiguration method, which returns an array of setting keys and their default values. The blockForm method can then override the \Drupal\Core\Block\BlockBase empty array implementation to return a Form API array to represent the settings form:
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'company_name' => '',
];
}
/**
* {@inheritdoc}
*/
public function blockForm($form, \Drupal\Core\Form\FormStateInterface $form_state) {
$form['company_name'] = [
'#type' => 'textfield',
'#title' => t('Company name'),
'#default_value' => $this->configuration['company_name'],
];
return $form;
}
The blockSubmit method must then be implemented, which updates the block's configuration:
/**
* {@inheritdoc}
*/
public function blockSubmit($form, \Drupal\Core\Form\FormStateInterface $form_state) {
$this->configuration['company_name'] = $form_state->getValue('company_name');
}
Finally, the build method can be updated to use the new configuration item:
/**
* {@inheritdoc}
*/
public function build() {
$date = new \DateTime();
return [
'#markup' => t('Copyright @year© @company', [
'@year' => $date->format('Y'),
'@company' => $this->configuration['company_name'],
]),
];
}
You can now return to the Block layout form, and click on Configure in the Copyright block. The new setting will be available in the block instance's configuration form.