我正在学习如何在Drupal 8
中创建自定义模块。我无法为模块的块创建默认配置。
我的模块名称为hello
。根据需要,我创建了一个文件hello/config/install/hello.settings.yml
。然后根据需要,我还在defaultConfiguration()
类中创建了HelloBlock
方法。
我尝试删除模块,重新安装它并尝试清除缓存。但是,在我安装模块并放置块后,它只是说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,
)),
);
}
}
答案 0 :(得分:1)
我认为他们没有尝试自己的教程,我对此有点挣扎,但如果你看一下弹出窗口的源代码,那么该字段的名称实际上是{{1}所以你应该在hello_block_name
:
defaultConfiguration()