处理block的配置表单

官网:https://www.drupal.org/docs/8/creating-custom-modules/add-a-form-to-the-block-configuration

代码:

<?php

namespace Drupal\first_form\Plugin\Block;

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

/**
 * Provides a 'Hello' Block.
 *
 * @Block(
 *   id = "first_form_block",
 *   admin_label = @Translation("first form block"),
 *   category = @Translation("First Form World"),
 * )
 */
class FirstFormBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
     
    $config = $this->getConfiguration();
  
    if (isset($config['first_form_block_setting']) && !empty($config['first_form_block_setting'])) {
      $name = $config['first_form_block_setting'];
    }
    else {
      $name = $this->t('to no one');
    }
  
    return array(
      '#markup' => $this->t('Hello @name!', array('@name' => $name)),
    );
  }

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

    $config = $this->getConfiguration();

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

    return $form;
  }
  
  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    parent::blockSubmit($form, $form_state);
    $values = $form_state->getValues();
    $this->configuration['first_form_block_setting'] = $values['first_form_block_setting'];
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 回首页 第一部分 Drupal简介 Drupal overview A tour of Drupal fundam...
    王乂阅读 2,077评论 0 9
  • 这两天破例入职了两位女同事,之前早就说女同事已超额了,不会再招,现在这样一弄,意味着外宿人员有可能没有床位,那到底...
    思言悟语阅读 364评论 0 0
  • 1. 二表婶是被人贩子卖到胡家庄的女人,给我姑奶奶做了儿媳妇。 二表叔小时候放炮炸聋了半边耳朵,加上家里实在穷,多...
    花花小茶馆阅读 2,069评论 6 35