Drumal 8 Block API를 사용해 보십시오.

13387 단어 DrupalDrupal8

화면에 표시될 때까지 블록 정의를 모듈에 기술하려면


1. BlockBase의 학급을 계승하여 다음과 같은 장소에 배치한다.
module/custoom/{모듈 이름]/src/Plugin/Block/{블록 이름(클래스 이름)}.php

2. 정의@Block의 초대
이 초청은 매우 중요하다.이 기술이 없으면 화면 관리에서 선택할 수 없습니다.
/id/관리 키
・adminlabel... 관리 화면에서 블록을 구성하는 화면에 정보 표시
3. build ()의 내용 정의
디스플레이 정보를 정의합니다.캐시의 단위를 정의할 수도 있습니다.
실제 코드
KazunokoBlock.php

<?php

/**
 * @file
 * Contains \Drupal\kazunoko_block\Plugin\Block\KazunokoBlock.
 */

namespace Drupal\kazunoko_block\Plugin\Block;

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

/**
 * Provides a Kazunoko block.
 *
 *
 * @Block(
 *   id = "kazunoko_block",
 *   admin_label = @Translation("sample kazunoko block"),
 * )
 */
class KazunokoBlock extends BlockBase {

  /**
   * Builds and returns the renderable array for this block plugin.
   *
   * If a block should not be rendered because it has no content, then this
   * method must also ensure to return no content: it must then only return an
   * empty array, or an empty array with #cache set (with cacheability metadata
   * indicating the circumstances for it being empty).
   *
   * @return array
   *   A renderable array representing the content of the block.
   *
   * @see \Drupal\block\BlockViewBuilder
   */
  public function build() {
    return array(
      '#type' => 'markup',
      '#markup' =>'Drupal!!!!',
      '#cache' => array(
        'contexts' => array('user'),
      ),
    );
  }
}
4. 화면 관리보다 더 좋아하는 곳에 배치
Block명은 @Block에 기술된 admin입니다.label、
Category 이름이 모듈 이름인 것 같습니다.
(모듈 이름 = 모듈.info.yml의name에 설정된 문자열)

추가 후

※ 이해하기 어려워 블록 제목도 표시됩니다.

블록 창을 정의하고 사용하기 전에


블록 편집 화면에 독립된 창을 설정하여 등록 값을 표시할 때 사용합니다.

1. 다시 쓰기로 BlockForm() 및 BlockSubmit() 정의
BlockForm()에 표시되는 필드 정의
입력한 값을 BlockSubmit()에 저장하는 코드를 설명합니다.
KazunokoBlock.php(메모 부분)
  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);

    // Retrieve existing configuration for this block.
    $config = $this->getConfiguration();

    // Add a form field to the existing block configuration form.
    $form['text'] = array(
      '#type' => 'textfield',
      '#title' => t('text'),
      '#default_value' => $this->configuration['text'],
    );

    $form['checkbox'] = array(
      '#type' => 'checkbox',
      '#title' => t('checkbox'),
      '#default_value' => $this->configuration['checkbox'],
    );

    $form['radio'] = array(
      '#type' => 'radios',
      '#title' => t('radio'),
      '#options' => array(
        1 => t('yes'),
        0 => t('no')
      ),
      '#default_value' => $this->configuration['radio'],
    );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    // Save our custom settings when the form is submitted.
    $this->setConfigurationValue('text', $form_state->getValue('text'));
    $this->setConfigurationValue('checkbox', $form_state->getValue('checkbox'));
    $this->setConfigurationValue('radio', $form_state->getValue('radio'));
  }

일반적인 표를 만들 때의 느낌과 같다.
2.(추가)defaultConfiguration()은 재작성 형식으로 정의됨
defaultConfiguration () 을 다시 쓰면 기본값을 설정할 수 있습니다.
단지 aray 값에 답장할 뿐입니다.
  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return array(
      'text' => t('Drupal!'),
      'checkbox' => 1,
      'radio' => 0,
    );
  }
3. build ()에 등록된 변수를 가져와 표시
  public function build() {
    $checkbox = $this->configuration['text'] ? 'checked!' : '';
    $radio = $this->configuration['radio'] ? 'Yes' : 'No';
    return array(
      '#type' => 'markup',
      '#markup' => sprintf('text: %s, checkbox: %s, radio: %s', $this->configuration['text'], $checkbox, $radio),
      '#cache' => array(
        'contexts' => array('user'),
      ),
    );
  }
위 코드의 출력 결과

끝맺다


좀 복잡한 사이트라도
백엔드 책임자가 블록 정의에 따라 부품을 설치합니다.
전단 담당자가 이 부품에 대한 설정 & 레이아웃 조정,
이런 사이트가 완성되었습니다!이런 느낌이 들면 사이트가 너무 좋아요.
그게 다야.

좋은 웹페이지 즐겨찾기