(快速參考)

19 Scaffolding

版本 6.2.0

19 Scaffolding

Scaffolding 讓您能為網域類別產生一些基本的 CRUD 介面,包括

  • 必要的 檢視

  • 建立/讀取/更新/刪除 (CRUD) 作業的控制器動作

應用程式表達對 scaffolding 外掛程式相依性的方式是將下列內容包含在 build.gradle 中。

dependencies {
        // ...
        implementation "org.grails.plugins:scaffolding"
        // ...
    }

動態 Scaffolding

入門 scaffolding 最簡單的方式是透過將控制器中的 scaffold 屬性設定為特定網域類別來啟用它

class BookController {
    static scaffold = Book  // Or any other domain class such as "Author", "Publisher"
}

在設定好這個之後,當您啟動應用程式時,動作和檢視會在執行階段自動產生。下列動作會由執行階段 scaffolding 機制預設動態實作

  • index

  • show

  • edit

  • delete

  • create

  • save

  • update

也會產生一個 CRUD 介面。若要存取這個介面,請在瀏覽器中開啟 https://127.0.0.1:8080/book

注意:定義 scaffold 屬性的舊式替代方法

class BookController {
    static scaffold = true
}

不再支援 Grails 3.0 以上的版本。

如果您偏好將網域模型保留在 Java 中,並使用 Hibernate 進行對應,您仍可以使用腳手架,只要匯入網域類別,並將其名稱設定為 scaffold 引數即可。

您可以將新的動作新增到腳手架控制器,例如

class BookController {

    static scaffold = Book

    def changeAuthor() {
        def b = Book.get(params.id)
        b.author = Author.get(params["author.id"])
        b.save()

        // redirect to a scaffolded action
        redirect(action:show)
     }
}

您也可以覆寫腳手架動作

class BookController {

    static scaffold = Book

    // overrides scaffolded action to return both authors and books
    def index() {
        [bookInstanceList: Book.list(),
         bookInstanceTotal: Book.count(),
         authorInstanceList: Author.list()]
    }

    def show() {
        def book = Book.get(params.id)
        log.error("{}", book)
        [bookInstance : book]
    }
}

所有這些動作都稱為「動態腳手架」,其中 CRUD 介面會在執行階段動態產生。

預設情況下,腳手架檢視中的文字區域大小會在 CSS 中定義,因此新增「rows」和「cols」屬性不會產生任何效果。

此外,標準腳手架檢視會預期集合的模型變數格式為 <propertyName>InstanceList,而單一實例的格式為 <propertyName>Instance。您可能會想使用「books」和「book」等屬性,但這些屬性無法使用。

靜態腳手架

Grails 讓您可以從命令列產生控制器和用於建立上述介面的檢視。若要產生控制器,請輸入

grails generate-controller Book

或產生檢視

grails generate-views Book

或產生所有內容

grails generate-all Book

如果您在套件中有一個網域類別,或從 Hibernate 對應類別 產生,請記得包含完整限定的套件名稱

grails generate-all com.bookstore.Book

自訂產生的檢視

檢視會根據 驗證限制 進行調整。例如,您只要重新排列產生器中的限制,就能變更欄位在檢視中顯示的順序

def constraints = {
    title()
    releaseDate()
}

如果您使用 inList 限制,您也可以讓產生器產生清單,而不是文字輸入

def constraints = {
    title()
    category(inList: ["Fiction", "Non-fiction", "Biography"])
    releaseDate()
}

或者,如果您在數字上使用 range 限制

def constraints = {
    age(range:18..65)
}

使用限制來限制大小也會影響 d 檢視中可以輸入的字元數。

def constraints = {
    name(size:0..30)
}

欄位外掛程式

Grails 腳手架範本會使用 欄位外掛程式。產生腳手架檢視後,您可以使用外掛程式提供的 Taglib 自訂表單和表格(有關詳細資訊,請參閱 欄位外掛程式文件)。

<%-- Generate an HTML table from bookInstanceList, showing only 'title' and 'category' columns --%>
<f:table collection="bookInstanceList" properties="['title', 'category']"/>

自訂腳手架範本

Grails 用來產生控制器和檢視的範本,可以使用 install-templates 指令安裝範本來進行自訂。