2012-08-09 1 views
3

그래서 내가 개발중인 시스템과 관련하여 다음과 비슷한 작업을하려고합니다.재생! 별도의 몽고 컬렉션에서 항목을 선택하는 양식

User라는 모델이 있고 _id (ObjectId), username , 암호를 입력 한 다음 새 약속을 만들려고하면 양식이 환자를 찾습니다 (드롭 다운에서 환자 이름을 표시하지만 실제로 환자의 ObjectId를 가져옵니다) 및 약속 시간.

이제 모든 곳을 살펴 보았습니다. 이제 내가 달성하려고하는 해결책에 가까운 곳에서 아무 것도 찾을 수 없습니다. Application.scala에서

, 나는이 :

val appointmentForm= Form(
    tuple(
    "patient" -> nonEmptyText, // ObjectId 
    "startTime" -> nonEmptyText)) 

나는 매우 환자를 반영하기 위해 내 시야를 작동하는 방법을 잘 모르겠습니다. 난 당신이 이런 식으로 뭔가를 알고 :

@select(appointmentForm("patient"), options(..) 

사람이 내가 몽고 ObjectId가 데리러이 예를 들어 환자를 조회 할 수있는 방법에 관해서는 나에게 어떤 아이디어를 제공 할 수 있습니다.

경로 :

내가 BTW 사용하고있는 ORM 여기

+2

[salat github issue queue] (https://github.com/leon/)에 게시 할 수 있습니다. play-salat/issues) .. 작성자가 상당히 적극적으로 반응하는 것처럼 보입니다. – Stennie

답변

1

https://github.com/leon/play-salat 내가 그것을 얼마나 예입니다

GET  /test  controllers.Test.show 
POST  /test  controllers.Test.submit 

보기 :

@(f: Form[(ObjectId, String)], users: Seq[(ObjectId, String)]) 
@import helper._ 

@form(action = routes.Test.submit) { 
    @select(f("patient"), options = users.map(user => (user._1.toString, user._2))) 
    @inputText(f("startTime")) 
    <input type="submit" value="Submit!"> 
} 

컨트롤러 :

package controllers 

import org.bson.types.ObjectId 
import play.api.data.format.Formatter 
import play.api.mvc._ 
import play.api.data.Forms._ 
import play.api.data._ 
import play.api.data.FormError 
import play.api.Logger 

object Test extends Controller { 

    /** 
    * Converts an ObjectId to a String and vice versa 
    */ 
    implicit object ObjectIdFormatter extends Formatter[ObjectId] { 
    def bind(key: String, data: Map[String, String]) = { 
     val error = FormError(key, "error.required.ObjectId", Nil) 
     val s = Seq(error) 
     val k = data.get(key) 
     k.toRight(s).right.flatMap { 
     case str: String if (str.length() > 0) => Right(new ObjectId(str)) 
     case _ => Left(s) 
     } 
    } 
    def unbind(key: String, value: ObjectId) = Map(key -> value.toStringMongod()) 

    val objectId: Mapping[ObjectId] = of[ObjectId] 
    } 

    // import to get objectId into scope 
    import ObjectIdFormatter._ 

    // define user tuples consisting of username and ObjectId for the dropdown. In real lif the list is probably fetched from the db 
    def users: Seq[(ObjectId, String)] = 
    Seq((new ObjectId("4f456bf744aed129d04db1bd"), "dieter"), (new ObjectId("4faa410b44aec5a0a980599f"), "eva")) 

    val appointmentForm= Form(
    tuple(
     "patient" -> objectId, // use the ObjectIdFormatter 
     "startTime" -> nonEmptyText)) 


    def show = Action { 
    Ok(views.html.test(appointmentForm, users)) 
    } 

    def submit = Action { implicit request => 
    appointmentForm.bindFromRequest.fold(
     formWithErrors => { 
     Logger.warn("errors: " + formWithErrors.errors) 
     BadRequest(views.html.test(formWithErrors, users)) 
     }, 
     formContent => { 
     Logger.info("formContent: " + formContent) 
     Ok(views.html.test(appointmentForm, users)) 
     }) 
    } 
} 
0

Fyi, 나는 마침내 maxmc가이 멋진 의견을 본 후 문제를 해결할 수있었습니다. 내 문제는 근본적인 스칼라 문제였습니다. 나는 List가 Seq의 구현임을 깨닫지 못했다. 그래서이 예에서, 몽고를 사용하여, 당신이해야 할 것은 코드에있는 것은 다음

CONTROLLER

def newAppointment= Action { 
    val pList = Patient.findAll.toList 
    Ok(views.html.admin.newuser(appointmentForm, pList)) 
} 

보기 :

@(appointmentForm: Form[(String, String, String)], pList : List[Patient]) 

... ... ...

@select(
     appointmentForm("patient"), 
     pList.map{ p => 
      p.id.toString -> (p.patientName) 
     }, 
     '_default -> "--- Select a Patient ---", 
     '_label -> "Patient" 
    ) 

Modeler.findAll 함수는 Iterator [Type]을 반환합니다. 우리는 그것을 원하지 않는다. 우리는 뷰 안에서 트래버스 할 수있는 목록을 검색해야합니다. 그래서 당신이 찾은 것입니다. 거기에서 @select는 pList를 매핑하고 데이터베이스의 각 항목에 대해 ID를 환자 이름과 연관시킵니다. @Select 태그의 Seq에 Seq (String, String)가 필요하므로 문자열임을 유의하십시오.