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鹮鹪龛鹦鹢鹞龏龸龴鹜鹛鹗龸龴鹓龲龮齻

本书共79小节:

评论 (写第一个评论)