logo

Palette - Make it Colorful🎨

Palette - Visual Page Builder, no design degree required.

Live Demo Download Palette

滚动
04/10/2025, by Ivan

现在假设我们希望为站点构建者添加一个功能,使其可以为每个自定义区块实例输入部分配置。请始终记住,在 Drupal 8 中,所有站点构建配置都可以从开发站点导出并导入到生产站点(称为 配置管理)。作为模块开发者,您还可以为表单提供默认配置,以便在站点构建者创建新区块时自动填充。

在上一页已有的 HelloBlock 类中,添加这些 “use” 语句,它们应当紧随现有的 use 语句之后:

use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;

更新类声明,加入新的 “实现 BlockPluginInterface”:

class HelloBlock extends BlockBase implements BlockPluginInterface {

然后将以下方法添加到类中。类似的完整文件在这里,但请注意表单名称和配置名称与本教程不完全一致。

此代码仅添加表单,表单处理和保存结果将在接下来的页面中介绍。

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);

    $config = $this->getConfiguration();

    $form['hello_block_name'] = [
      '#type' => 'textfield',
      '#title' => $this->t('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;
  }

在此示例中,表单首先通过以下代码调用其父类来定义:$form = parent::blockForm($form, $form_state);。然后我们在表单中添加了一个新字段。这个过程称为 多态,它是使用 面向对象编程 (OOP) 方法的重要优势之一。

接下来,我们必须告诉 Drupal 将表单中的值保存到该区块的配置中。示例如下:

  /**
   * {@inheritdoc}
   */
  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'];
  }

要查看该表单,请转到之前添加的区块实例:管理 -> 结构 -> 区块布局,然后点击(Hello World)区块的“配置”。

要为同一表单添加多个提交按钮:

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);

    $config = $this->getConfiguration();

    $form['hello_block_name'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Who'),
      '#description' => $this->t('Who do you want to say hello to?'),
      '#default_value' => isset($config['hello_block_name']) ? $config['hello_block_name'] : '',
    ];

    $form['actions']['custom_submit'] = [
      '#type' => 'submit',
      '#name' => 'custom_submit',
      '#value' => $this->t('Custom Submit'),
      '#submit' => [[$this, 'custom_submit_form']],
    ];    

    return $form;
  }

新的自定义提交操作:

  /**
   * Custom submit actions.
   */
  public function custom_submit_form($form, FormStateInterface $form_state) {
    $values = $form_state->getValues();
    // 执行所需的操作。
  }