2013-07-22 35 views
1

我已經在Persistent中定義了一對多關係,但無法弄清楚如何創建可以將外鍵之一作爲輸入的表單。簡化我的使用情況是這樣的:捕獲表單中的持久關係

Person 
    name String 

Car 
    personId PersonId 
    name Text 
    type Text 

現在,當我嘗試生成租車形式,應該是什麼PERSONID字段類型?我想是這樣的,但得到一個錯誤:

entryForm :: Maybe Car -> Form Car 
entryForm car = renderDivs $ Car 
    <$> areq personIdField "Person" Nothing 
    <*> areq textField "Car Name" (carName <$> car) 
    <*> areq textField "Type" (carType <$> car) 

當我運行上面我得到的錯誤:Not in scope: `personIdField'.

我試圖intField和它說:

Couldn't match expected type `KeyBackend 
           persistent-1.2.1:Database.Persist.Sql.Types.SqlBackend Person' 
      with actual type `Text' 
Expected type: Field 
       m0 
       (KeyBackend 
        persistent-1.2.1:Database.Persist.Sql.Types.SqlBackend Person) 
    Actual type: Field m0 Text 
In the first argument of `areq', namely `intField' 
In the second argument of `(<$>)', namely 
    `areq intField "Person" Nothing 

我非常希望填充人名的下拉列表(如果沒有太多)或者有太多的時候有自由格式的文本字段(例如,自動完成)。關於如何將外鍵作爲用戶輸入的建議?

更新

我嘗試使用selectField如下,但不知道如果我正確地做這個。我仍然遇到錯誤。首先,我創建了一個WHERE語句得到PERSONID:

where 
    personId = do 
     person <- runDB $ selectFirst [] [Asc PersonName] 
     case person of 
      Just (Entity pId p) -> return pId 
      -- Nothing    -> ??? 

,然後我改變了我的第一個AREQ到

<$> areq (selectField [("First", personId)]) "Person Name" Nothing 

謝謝!

+1

你需要使用'selectField' – Ankur

+1

@Ankur請你詳細說明你的意思嗎?我嘗試使用selectField,但仍然得到類似的錯誤。但是,我不確定我是否正確使用它。另外,如果我只想從用戶那裏獲得自由格式的輸入,然後再將它映射回ID,這種結構將如何工作? – Ecognium

回答

3

我能弄清楚如何正確使用selectField。這是我落得這樣做:

where 
    people = do 
     entities <- runDB $ selectList [] [Asc PersonName] 
     optionsPairs $ map (\p -> (personName $ entityVal p, entityKey p)) entities 

表單字段成爲:

<$> areq (selectField people) "Person Name" Nothing 

我還沒有想通了免費的形式進入,只是還沒有,但這是一個好的開始。