Populate dropdown from an entity using Spring-mvc and thymeleaf

Bram :

I'm working on an application in which I want to add a student to a meal using a dropdown in a form. My code looks as follows:

Meal.java

@Entity
public class Meal {

@Id
@GeneratedValue
  private Long id;

  @OneToOne
  private Student mealCook;

  private String mealName;

  private int mealPrice;

Student.java

@Entity
 public class Student {

@Id
@GeneratedValue
private Long id;

private String studentName;

MealController.java

@Controller
@RequestMapping("/m")
public class MealController {

private final MealRepository mealRepository;
private final StudentRepository studentRepository;

public MealController(MealRepository mealRepository, StudentRepository studentRepository){
    this.mealRepository = mealRepository;
    this.studentRepository = studentRepository;
}

@GetMapping
public ModelAndView list(){
    Iterable<Meal> meals = this.mealRepository.findAll();
    return new ModelAndView("meals/list" , "meals", meals);
}

@GetMapping("{id}")
public ModelAndView view(@PathVariable("id") Meal meal) {
    return new ModelAndView("meals/view", "meal", meal);
}

@GetMapping(params = "form")
public String createForm(@ModelAttribute Meal meal) {
    return "meals/form";
}

@PostMapping
public ModelAndView create(@Valid Meal meal,  BindingResult result,
                           RedirectAttributes redirect) {
    Iterable<Student> students = this.studentRepository.findAll();
    if (result.hasErrors()) {
        return new ModelAndView("meals/form", "formErrors", result.getAllErrors());
    }
    meal = this.mealRepository.save(meal);
    redirect.addFlashAttribute("globalMessage", "view.success");
    return new ModelAndView("redirect:/m/{meal.id}", "meal.id", meal.getId());
}

And lastly my view -> form.html

<form id="mealForm" th:action="@{/m/(form)}" th:object="${meal}" action="#" method="post">

    <div class="form-group">
        <label for="mealName">Meal Name</label>
        <input type="text" th:field="*{mealName}" th:class="${'form-control' + (#fields.hasErrors('mealName') ? ' is-invalid' : '')}">
    </div>

    <div class="form-group">
        <label for="mealCook">Meal Cook</label>
        <select th:field="*{mealCook}">
            <option th:each= ??
                    th:value= ??
                    th:text= ??</option>
        </select>
    </div>

    <button type="submit" class="btn btn-primary">Submit</button>
</form>

Now the goal is to add 1 student to a meal by selecting the studentName from a dropdown menu in a form.

But I'm stuggling on how to pass a list of students from the controller to the view and display it in a dropdown.

AmirBll :

You should add student list in controller wherever open the form:

    ModelAndView model = new ModelAndView("studentList");
    model.addObject(students) // get list from database or...
    // students =studentRepository.findAll() or use your exclusive query

And <option>:

<option th:each="item : ${studentList}"
        th:value=${item.id} // value you want...
        th:text=${item.name}>
</option>

and change entities:

Meal.java:

@Entity
    public class Meal {

@Id
@GeneratedValue
  private Long id;

  @OneToOne
  @JoinColumn(name = "meel_cook_id")
  private Student mealCook;

  private String mealName;

  private int mealPrice;

Student.java:

@Entity
 public class Student {

@Id
@GeneratedValue
private Long id;

private String studentName;

@OneToOne(mappedBy = "mealCook")
@JsonBackReference
private Meal meal;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=329353&siteId=1