3.1 配置表单和管理

龷龶龲龱龭龩龧龣龡龭龟龭龩龧龛龙(CM)龭龑

Drupal 8 齷 Drupal 7 齴齰龩龧齯齫龟齧齣齠齟齜齘齔齐齏齎齊齰齆齄龛龙龑

本课内容

  • 齃鼿 CM鼾龩龧龛龙鼻龑
  • 鼸鼴 examples/configform_example 鼙鼕龑
  • 齃鼿龩龧龣龡龑
  • 鼑鼏鼍鼋龩龧龣龡龑
  • 鼇鼋 *.settings.yml 黽龲龱黹齔 CM 黸鼙鼕黵黳龩龧龑

配置管理

Drupal 8 龩龧龛龙鼾CM鼻 龩龧 API 黥黤黽黸鼙鼕黵黳龩龧齣黢黡黠點齐齏黝黙黖龧龑黓黏黍黉黈黇黃黂黀麾麻麹麸麶齣黢麳麲麱麮麫麨麤麣麡麠麝麹麙麕麑麍齰龩龧龑黓麋麊麉 Drupal 8 黝黙麈點 Drupal 7 Features 鼙鼕齰麃麂龑

Drupal 8 黸鹾鹺鹶鼴鹴鹱鼾鹯鹬鹨鹤麤鹠鹟龟鹝鹙鼻齰龩龧鹗黈黡黠點鹖鹒麤鹏鹎齰齔鹊鹈鹄龑黓麠鹀黏黍鹠鹨龩龧鹾鹺齰鹴鹱龑

黹齔 Configuration inspector 鼙鼕黽鸽黏黍鸹 Drupal 龛龙鹈鹄鸶鸴鸲鸯鸮齏龩龧黽鸬鸩鸧鸹鸥鸢齆齄鸠鸲鸯 YAML 鸥鸢龑

鼙鼕鹨鹤麲黏黍黡鸙 {module}/config/install 鸎鸊鸠齰 YAML 鸥鸢黽麫麨龩龧鸇麫齰鼍鸄黽黹齔鸁龷鷾鷻鷹鸢鷶鷳齏鹴鹱鷱鷰鹤鷬龑

鷫麈齐齏鷨鷥龩龧齰鷡鷝鸥齆齄黽黹鷙麫麨鷳鷘鷖黂黀鷓鷨鷑鷎黽黓齏黏黍鷊鷉 schema 鸥鸢鷅鷁龑

被 CM 替代的 Drupal 7 函数

CM 鶿鶾點 Drupal 鶺鹟黹齔齰鶷齏齧齣龑黝黙鶳鶲鶯黓鶫齧齣鶧鶣鶟鶝 CM 齆齄黽齄齐鶙龙龩龧齣黢龑

配置表单

鵻鵷鼇鼋 PageExampleForm 鵴鵱鵭點 FormBase 黽FormBase 鶯 FormInterface 鼾黡黠點齐齏龣龡齰鸴鵨鼻 齰齐齏黉龡鷅鷁龑

Drupal 8 黡黠點鵤齐齏黝黙黇 ConfigFormBase 黽黓齏黇齰鵢鵡鵝鶙鶯鵛鵘點鵕龩龧齆齄齰鸙鵓龑

使用 ConfigFormBase 创建模块

鷁鸹鵻鵷拷鵎鵋鵈齰 page_example,创建一个新模块 configform_example

鵻鵷鵅黹 PageExampleForm 黇麂鵁黵黳齔鹊黡黠齰 email 龑黸點鷅鷁黓齏鸽鴾鸧鸹 ConfigFormExampleConfigForm.php 鴺鼾黖鴶 configform_example/src/Form/鼻齷 FormBase 鶿鴵鸄 ConfigFormBase

use Drupal\Core\Form\ConfigFormBase;
 
class ConfigFormExampleConfigForm extends ConfigFormBase {

黓齏黇鴱鵡齐齏鴯鴫齰鴨鴥 getEditableConfigNames鼾ConfigFormBase 齰鴤麍鴨鴥鼻黽鵻鵷鷁鸹鼇鼋龑

/**
* {@inheritdoc}.
*/
public function getEditableConfigNames() {
  return ['configform_example.settings'];
}

使用 YAML 配置

Drupal 8 齴黹齔龩龧 API 黏黍齷鹯鹬鹗鴠麳鼙鼕黡黠齰龩龧齯齫黵黳鸹 YAML 鸥鸢鸠龑鴞鼙鼕鶧鴛鴙鵴黽YAML 鸠齰齯齫鴗齊鴖鶧鹏鹒齣黢鴒黽鹏鹒齰鸎齰鶯黸點鵛鵘鴐麂龑

齐鴏齣黢鴒鶧鵛鹗鸽黏黍鴍鷑鷎齰鹏鹎黸 YAML 鸥鸢黽鴌鵇鴊鴉龑

鴞黸鼙鼕黡黠龩龧鵴黽黏黍鷊鷉齐齏鴈麫齰 YAML 鸥鸢黸龩龧鸇麫鴅鴁鳿鼾YAML 鸥鸢鳾龧鸹 config/install 鸎鸊鸠鼻龑

鵻鵷黹齔黍鷝鶾鳼黸 email 鳹鳵鸇龧鴅鴁鳿龑

configform_example.settings.yml 鳱

email_address: form@examples.com

嵌套字段

鹬鳬鴾鵡黽鸽黏黍黹齔鳨鳦麱麮鸇麫麙麕鶫齰龩龧龑

address:
  line_1: 123 fake st
  city: Boston
  state: MA
  zip: 55555

黓鳙鳕鳓齣鼸齰鳨鳦鳑鼍鳏麈 YAML 鳌黇黃龑鷳齣鳋鳉鷝黹齔黀鼾.鼻鳅鳃黓齏鳨鳦鳿龑

鹯鹬龷鹯齴鴗黹齔 address.line_1 鳅鳃 line_1 齰鳿龑

注意: 模块只有被安装时才会被导入到数据库,所以如果模块已经被安装了你必须卸载重新安装。

表单方法

鷁鸹 buildForm() 鴨鴥鳁鲿麍黓麠黽鶾鳼鲾鲼鲺鸠鷑鲹鳱

龟 FormBase 鹾鹺黽 ConfigFormBase 鷅鷁點 buildForm 鴨鴥黽鲵龣龡齣鼸鸠鲲鷨點齐齏黡鸙鲮鲪龑

鳏黍鸹鵻鵷鲲鷨鵇鲧鲣鵋鵈黏黍黹齔鲡黇鷅鷁齰鸠鷑龑

public function buildForm(array $form, FormStateInterface $form_state) {
  $form = parent::buildForm($form, $form_state);
  $config = $this->config('configform_example.settings');
  $form['email'] = [
    '#type' => 'email',
    '#title' => $this->t('Your .com email address.'),
    '#default_value' => $config->get('email_address')
  ];
  return $form;
}

评论 (写第一个评论)