【发布时间】:2017-05-31 08:45:36
【问题描述】:
我正在学习如何在Drupal 8 中创建自定义模块。我一直在为模块的一个块创建默认配置。
我的模块名称是hello。根据需要,我创建了一个文件hello/config/install/hello.settings.yml。然后根据需要,我还在我的HelloBlock 类中创建了defaultConfiguration() 方法。
我尝试删除模块,重新安装它并尝试清除缓存。但是,在我安装模块并放置块之后,它只是说 Hello ! 而不是 Hello, Batman!
这是所需的代码 -
hello/config/install/hello.settings.yml
hello:
name: 'Batman'
你好\src\Plugin\Block\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,
)),
);
}
}
【问题讨论】:
标签: php drupal drupal-modules drupal-8