Play-Scala開發技巧 - 帶索引遍曆Form(arrayProperty)

來源:互聯網
上載者:User

標籤:

    Play提供了Form、Field等表單類型,協助開發人員節省了很多表單處理方面的負擔,但是有些功能目前不是很靈活,正如本文即將討論的@helper.repeat函數,該函數目前無法讓開發人員直接存取元素索引,本文介紹兩種方法,可以臨時解決這個問題。

    假設我們的form定義如下:

val userForm = Form[User](    mapping(      "_id" -> text,      "name" -> nonEmptyText,      "emails" -> list(nonEmptyText)    )(User.apply)(User.unapply))

其中emails屬性是List類型。

1. Field中如何存放List類型?

List類型在Field中是被打散存放的,所以無法直接從Field中取出該List執行個體,例如對於:

user.emails = List("[email protected]", "[email protected]", "[email protected]")

直接調用userForm("emails").value返回None,正確的訪問方式是:

userForm("emails")("[0]").valueuserForm("emails")("[1]").valueuserForm("emails")("[2]").value

或者

userForm("emails[0]").valueuserForm("emails[1]").valueuserForm("emails[2]").value

OK,背景知識介紹完畢,下面進入正題。

2. 使用Filed.indexes擷取索引資訊

    對於存放List屬性的Field執行個體,其indexes屬性將會返回其索引列表,類型為List[Int],代碼如下:

@for(i <- userForm("emails").indexes){     @userForm("emails")("[" + i + "]").value}
3. 利用Field.name擷取索引資訊
@helper.repeat(userForm("emails"), min=0 ){ field =>    @field.name}

輸出資訊為:

emails[0]emails[1]emails[2]

第2鐘方式不夠靈活,需要手工從字串中解析出索引,建議使用第1種方式。

歡迎光臨我們的小站:

奇智智能客服機平台:http://www.smartnlp.cn

Play-Scala開發技巧 - 帶索引遍曆Form(arrayProperty)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.