8.3 区块配置表单
配置表单允许在用户界面设置区块内显示的文本字符串。方法有:
- blockForm:向接收$form数组添加元素
- blockSubmit: 保存从表单接收的数据
- defaultConfiguration: 定义默认的配置值
- build: 输出一个渲染数组
在src\Plugin\Block下创建一个文件 HelloBlockConfigurable.php,内容如下:
<?php
/**
* @file
* Contains \Drupal\hello_world\Plugin\Block\HelloBlockConfigurable.
*/
namespace Drupal\hello_world\Plugin\Block;
use Drupal\Core\Block\Annotation\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Annotation\Translation;
use Drupal\Core\Form\FormStateInterface;
/**
* Provides a 'Example: configurable text string' block.
*
* Drupal\block\BlockBase gives us a very useful set of basic functionality for
* this configurable block. We can just fill in a few of the blanks with
* defaultConfiguration(), blockForm(), blockSubmit(), and build().
*
* @Block(
* id = "hello_configurable_block",
* admin_label = @Translation("Title of first block (example_configurable_text)"),
* category = @Translation("Hello")
* )
*/
class HelloBlockConfigurable extends BlockBase {
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'example_string' => $this->t('A default value. This block was created at %time', ['%time' => date('c')]),
];
}
/**
* {@inheritdoc}
*/
public function blockForm($form, FormStateInterface $form_state) {
$form['example_string_text'] = [
'#type' => 'textfield',
'#title' => $this->t('Block contents'),
'#size' => 60,
'#description' => $this->t('This text will appear in the example block.'),
'#default_value' => $this->configuration['example_string'],
];
return $form;
}
/**
* {@inheritdoc}
*/
public function blockSubmit($form, FormStateInterface $form_state) {
$this->configuration['example_string']
= $form_state->getValue('example_string_text');
}
/**
* {@inheritdoc}
*/
public function build() {
return [
'#type' => 'markup',
'#markup' => $this->configuration['example_string'],
];
}
}
访问admin/structure/block点击区域旁边的配置按钮来配置该表单。