1
我正在学习如何在Drupal 8
中创建自定义模块。我被困在创建模块块的默认配置。Drupal 8:自定义模块块默认配置不起作用
我的模块的名称是hello
。根据需要,我创建了一个文件hello/config/install/hello.settings.yml
。然后根据需要,我还在我的HelloBlock
类中创建了defaultConfiguration()
方法。
我尝试删除模块,重新安装它,并试图清除缓存。不过,我仍然安装模块并放置块之后,它只是说的Hello !
代替Hello, Batman!
下面是所需的代码 -
你好/配置/安装/ hello.settings.yml
hello:
name: 'Batman'
你好\ SRC \插件\块\ HelloBlock.php
这里是defaultConfigurtion()函数 -
public function defaultConfiguration() {
$default_config=\Drupal::config('hello.settings');
return array(
'name'=>$default_config->get('hello.name'),
);
}
这里是整个HelloBlock类 -
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,
)),
);
}
}