处理block的配置表单

2019-02-19  本文已影响3人  liboxiang

官网: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'];
  }
}
上一篇下一篇

猜你喜欢

热点阅读