一月 27, 2022 | 後端和Drupal
【D9 HardCode教學】如何建立一個Layout Builder的頁面並且將特定區塊加入到頁面中
How to create a layout builder page programmatically in Drupal 9?
在特殊的情況下,也許你想要寫程式自動建立一個Layout Builder的頁面,並且將特定區塊放置其中,那這篇文章將會是你想要找的文章,除了是我自己的筆記之外,也分享給需要這樣功能的人
動機
由於我們在製作從Drupal 7 要移轉到 Drupal 9的專案中,Migrate API會需要對應每一個Node原本的ID,但礙於網站同時也要進行開發(總不能先匯入完畢後,才開始開發吧,客人網頁可是一直在寫內容),因此,我們希望能夠讓移轉作業(Migrate process)時全部自動化,並且在匯入完畢所有Drupal 7 的文章後,系統再自動建立用Layout Builder製作的首頁,然後將特定的區塊放進去,因此,才會有希望能夠寫程式自動建立頁面,並且將對應的Layout與Block加入的這種需求。
作法
以下作法可以運用在非常多地方,但若你還不熟悉Drupal後端的模組開發,或是物件導向等概念,那並非這篇文章的目的,可以去參考我們其他相關的文章。
- 建立有Layout builder的文章
假設目前有一個Layout Builder的Content Type機器名稱是landing_page
$entity = \Drupal::entityTypeManager()->getStorage('node')->create([
'type' => 'landing_page',
'title' => "Test Page"
]);
$entity->save();
上述這樣的方式就可以建立一篇文章囉,接下來我們再開始建立對應的Layout與其中的內容。
- 建立Layout與其內容
我們通過建立一個Section,並且將兩個區塊加入到這個Section之中。
// 加入一個Column的Layout
$section = new Section('layout_onecol');
// 加入第一個特定區塊
$pluginConfiguration = [
'id' => "block_content:5a2b52ab-8d5f-4e39-9960-35ec6946dfb6",
'provider' => 'entity_block',
'label_display' => FALSE,
'view_mode' => 'default',
];
$component = new SectionComponent('5a2b52ab-8d5f-4e39-9960-35ec6946dfb6', 'content', $pluginConfiguration);
$section->appendComponent($component);
// 加入第二個特定區塊
$pluginConfiguration = [
'id' => "block_content:7eca8266-3b02-49b7-8e67-77eeb2357fc4",
'provider' => 'entity_block',
'label_display' => FALSE,
'view_mode' => 'default',
];
$component = new SectionComponent('7eca8266-3b02-49b7-8e67-77eeb2357fc4', 'content', $pluginConfiguration);
$section->appendComponent($component);
$sections[] = $section;
$entity->layout_builder__layout->setValue($sections);
$entity->save();
補充一下對應需要用到的Class
- Section:
Drupal\layout_builder\Section
- SectionComponent:
Drupal\layout_builder\SectionComponent
因此,通過上面的方法,就可以順利建立對應的Layout Builder頁面與對應的區塊囉。
結論
因為特殊的需求,所以才會需要找這個方法,而有了上述的方法,可以整合在任何地方,例如在某些條件下,想要自動產生Layout Builder頁面與特定區塊,都是很容易的事情囉,算是給我們自己筆記,也是分享給需要用到的人。