2017-05-31 143 views
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, 
    )), 
); 
} 
} 

回答

1

我認爲他們沒有嘗試自己的教程中,我掙扎了一下這個問題,但如果你看看源代碼彈出窗口,字段的名稱實際上是hello_block_name,所以你應該有這個在您的defaultConfiguration()

public function defaultConfiguration() { 
    $default_config=\Drupal::config('hello.settings'); 
    return array(
    'hello_block_name'=>$default_config->get('hello.name'), 
); 
}