2013-06-26 2 views
3

Java Playframework 2.1.1을 사용 중이고 다 - 대 - 다 관계 (학생과 코스 사이)가있는 객체를 유지하기위한 양식을 작성하려고합니다. 그래서 학생을 만드는 관점에서 다중 선택 요소를 사용하여 여러 과정을 선택합니다. 양식을 제출 한 후, 학생은 올바르게 삽입되지만 접합 가능한 "학생 과정"은 비어있게됩니다. 학생을 작성하는 형태 Student.javaPlayframework를 사용하는 ManyToMany-Object 유지하기

@Entity 
public class Student extends Model { 
    ... 
@ManyToMany(cascade = CascadeType.ALL) 
private List<Course> courses; 
... 
} 

AdminController.java

public class Admin extends Controller { 
final static Form<Student> studentForm = Form.form(Student.class); 

@Transactional 
public static Result newStudent(){ 
    List<Student> students= Student.find(); 
    return ok(createStudent.render(students,studentsForm)); 
} 

@Transactional 
public static Result submitStudent(){ 
    Form<Student> filledForm = studentForm.bindFromRequest(); 
    if(filledForm.hasErrors()) { 
     Logger.error("Submitted Form got errors"); 
     return badRequest(); 
    } else { 
     Student student= filledForm.get(); 
     Student.save(student); 
    } 
    List<Student> students= Student.find(); 
    return ok(createStudent.render(students,studentForm)); 
} 
... 
} 

Course.java

@Entity 
public class Course extends Model { 
... 

@ManyToMany(mappedBy = "courses", cascade=CascadeType.ALL) 
private List<Student> students; 

public static List<Course> find() { 
    Query query = JPA.em().createQuery("SELECT e FROM course e"); 
    return (List<Course>) query.getResultList(); 
} 
... 
} 

: 여기

은 일부 코드입니다 :

@(students:List[Student], studentForm: Form[Student]) 

@import helper._ 

@main("Administration - Create Student"){ 
<h1>Create Student</h1> 
<hr/> 
} 

<h2>New Student</h2> 
@helper.form(action = routes.Admin.submitStudent) { 
      ... 
    @helper.select(studentForm("courses"), 
    options(Course.options), 
    'multiple -> "multiple", 
    '_label -> "Course") 

    <input type="submit" class="btn btn-success"> 
} 

} 

도움을 주시면 감사하겠습니다.

+0

게시 된 값을 개체에 바인딩하여 문제가 발생하는 것 같습니다. 하나만 선택해도 생성 된 학생 개체에는 코스가 없습니다. –

답변

1

나는 이제 값을 객체에 직접 바인딩하여 문제를 해결했습니다.

Student student = filledForm.get(); 
List<Student> courses= new LinkedList<Course>(); 
for(Map.Entry<String, String> entry : filledForm.data().entrySet()){ 
    if(entry.getKey().contains("courses")){ 
     Course c = Course.find(Long.parseLong(entry.getValue())); 
     courses.add(c); 
    } 
} 
student.setCourses(courses); 

나는 여전히 filledForm.get() 함수를 사용하는 동안이 작업을 수행하는 더 우아한 방법을 찾고 있어요 : 여기

내 Admincontroller에서 코드입니다.

관련 문제