I am learning how to create a custom module in Drupal 8
. I am stuck in creating the default configuration for a block of the module.
The name of my module is hello
. As required, I have created a file hello/config/install/hello.settings.yml
. Then as required I also created the defaultConfiguration()
method in my HelloBlock
class.
I tried deleting the module, reinstalling it and also tried clearing the cache. But still, after I install the module and place the block, it just says Hello !
instead of Hello, Batman!
Here is the required code -
hello/config/install/hello.settings.yml
hello:
name: 'Batman'
hello\src\Plugin\Block\HelloBlock.php
Here is the defaultConfigurtion() function -
public function defaultConfiguration() {
$default_config=\Drupal::config('hello.settings');
return array(
'name'=>$default_config->get('hello.name'),
);
}
Here is the entire HelloBlock class -
class HelloBlock extends BlockBase implements BlockPluginInterface {
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
$default_config=\Drupal::config('hello.settings');
return array(
'name'=>$default_config->get('hello.name'),
);
}
//Submit the form and save the form value into block configuration
public function blockSubmit($form, FormStateInterface $form_state) {
parent::blockSubmit($form,$form_state);
$values=$form_state->getValues();
$this->configuration['hello_block_name'] =
$values['hello_block_name'];
}
//Add the form
public function blockForm($form, FormStateInterface $form_state) {
$form = parent::blockForm($form,$form_state);
$config = $this->getConfiguration();
$form['hello_block_name'] = array(
'#type'=> 'textfield',
'#title'=> 'Who',
'#description'=>$this->t('Who do you want to say hello to?'),
'#default_value'=>isset($config['hello_block_name'])?
$config['hello_block_name'] : ' ',
);
return $form;
}
//Build the module i.e. Control the view of block
public function build() {
$config = $this->getConfiguration();
if (!empty($config['hello_block_name'])) {
$name = $config['hello_block_name'];
}
else {
$name = $this->t('to no one');
}
return array(
'#markup' => $this->t('Hello @name!', array (
'@name' => $name,
)),
);
}
}