drupal

drupal8 学习笔记 - 创建block

2019-06-21  本文已影响0人  AnnaJIAN

Drupal 8 中的块 API 变了,现在块既是插件(plugins)也是实体(entities)。

#Anna@bogon~/Sites/vagrant-np7/drupal8/sites/all/modules/examples/block_example (master) ☀️✨$ ls
block_example.info.yml  src
#drupal8/sites/all/modules/examples/block_example/src/Plugin/Block/ExampleConfigurableTextBlock.php
<?php

/** 
 * @file 
 * Contains \Drupal\block_example\Plugin\Block\ExampleConfigurableTextBlock. 
 */

namespace Drupal\block_example\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 = "example_configurable_text",
 *   admin_label = @Translation("Title of first block (example_configurable_text)"),
 *   category = @Translation("Example")
 * )
 */
class ExampleConfigurableTextBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'block_example_string' => $this->t('AAAAAA default value. This block was created at %time', ['%time' => date('c')]),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $form['block_example_string_text'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Block contentsA'),
      '#size' => 60,
      '#description' => $this->t('This text will appear in the example block.'),
      '#default_value' => $this->configuration['block_example_string'],
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    $this->configuration['block_example_string']
      = $form_state->getValue('block_example_string_text');
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    return [
      '#type' => 'markup',
      '#markup' => $this->configuration['block_example_string'],
    ];
  }

}

注意blockForm,blockSubmit,build这些方法。
build是呈现block列表,markup获取block_example_string 里面的内容显示,blocksubmit获取block_example_string_text内容提交到block_example_string,blockform是各种表单元素,defaultConfigure指默认数据。
admin_label是block的默认title,category选block的时候可以看见。

写完激活,添加到region中,在页面中就可以显示。

上一篇 下一篇

猜你喜欢

热点阅读