【问题标题】:Drupal 8: Custom Module Block default configuration not workingDrupal 8:自定义模块块默认配置不起作用
【发布时间】: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


    【解决方案1】:

    我认为他们没有尝试他们自己的教程,我对此有点挣扎,但是如果您查看弹出窗口的源代码,该字段的名称实际上是 hello_block_name 所以你应该有这个在你的defaultConfiguration():

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

    【讨论】:

      猜你喜欢
      • 2015-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-03
      • 2020-05-06
      • 2015-02-21
      • 1970-01-01
      • 2013-09-10
      相关资源
      最近更新 更多