Search code examples
spring-mvcthymeleaf

Selecting the option passed from the controller


I'm having trouble with the selection of the right value in a 'select' when the options are String. I can't find the solution in the forums.

I pass 'kind' in the controller and I can see that the values are fine but only the Integer fields are selected properly in the 'select'. The ones with String always show the first value and not the one pass in 'kind'.

I added the code I thought it could help Can anyone help?

My HTML code. The form contains many 'select' but I left two, the first one works but the second one always show the first option:

 <form  role="form" th:action="@{/kind/update}"  th:object="${kind}" method="post">
    <div class="form-group col-md-4">
        <label for="replicates">No. of Replicates</label>
        <select id="replicates" class="form-control" style="width: 70%;" th:field="${kind.replicates}">
            <option th:each="rep: ${replicatesnumber}" th:value="${rep}" th:text="${rep}"> </option>
       </select>
   </div>
   <div class="form-group col-md-3">
       <label for="substrate">Substrate</label>
       <select id="substrate" class="form-control" th:field="${kind.substrate}">
           <option th:each="substrate: ${substrates}" th:value="${substrate}" th:text="${substrate}"> </option>
       </select>
   </div>
   <div class="box-footer">
    <button type="submit" class="btn btn-primary">Save</button>
    <a class="btn btn-primary" th:href="@{/division/edit/}+${kind.division.id}" role="button">Cancel</a>                                     
    </div>
</form>     

The controller look like this:

@Controller
@RequestMapping("/kind")
public class KindController {

    @Autowired 
    private KindService kindService;

    @ModelAttribute("replicatesnumber")
    public int[] getReplicates() {
        int[] reps = new int[3];
        reps[0] = 2;
        reps[1] = 4;
        reps[2] = 8;
        return reps;
    }

    @ModelAttribute("substrates")
    public List<String> getSubstrates() {
        return Arrays.asList("BP", "PP", "TP", "OGM", "Sand");
    } 

   @GetMapping(value= "/edit/{kindId}")
   public String viewDivision(@PathVariable Integer kindId, Model model){
       Kind kind= kindService.findById(kindId);
       model.addAttribute("kind",kind);
       return  "kind_edit";
   }      

and the entity:

@Entity
@Table(name = "kind", schema = "ostscourses")
public class Kind implements java.io.Serializable {

private Integer id;
private Division division;
private String name;
private Integer germinationDays;
private Integer firstCount;
private Integer replicates;
private Boolean dark;
private Integer chill;
private String temperature;
private String substrate;
private Integer noSeeds;
private List<Sample> samples;

public Kind() {
}

public Kind(Integer id, Division division) {
    this.id = id;
    this.division = division;
}

public Kind(Integer id, Division division, String name, Integer germinationDays, Integer firstCount, Integer replicates, Boolean dark, Integer chill, String temperature, String substrate, Integer noSeeds, List<Sample> samples) {
    this.id = id;
    this.division = division;
    this.name = name;
    this.germinationDays = germinationDays;
    this.firstCount = firstCount;
    this.replicates = replicates;
    this.dark = dark;
    this.chill = chill;
    this.temperature = temperature;
    this.substrate = substrate;
    this.noSeeds = noSeeds;
    this.samples = samples;
}

@Id
@Column(name = "id", unique = true, nullable = false)
public Integer getId() {
    return this.id;
}

public void setId(Integer id) {
    this.id = id;
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "division_id", nullable = false)
@JsonIgnore
public Division getDivision() {
    return this.division;
}

public void setDivision(Division division) {
    this.division = division;
}

@Column(name = "name", length = 25)
public String getName() {
    return this.name;
}

public void setName(String name) {
    this.name = name;
}

@Column(name = "germination_days")
public Integer getGerminationDays() {
    return this.germinationDays;
}

public void setGerminationDays(Integer germinationDays) {
    this.germinationDays = germinationDays;
}

@Column(name = "first_count")
public Integer getFirstCount() {
    return this.firstCount;
}

public void setFirstCount(Integer firstCount) {
    this.firstCount = firstCount;
}

@Column(name = "replicates")
public Integer getReplicates() {
    return this.replicates;
}

public void setReplicates(Integer replicates) {
    this.replicates = replicates;
}

@Column(name = "dark")
public Boolean getDark() {
    return this.dark;
}

public void setDark(Boolean dark) {
    this.dark = dark;
}

@Column(name = "chill")
public Integer getChill() {
    return this.chill;
}

public void setChill(Integer chill) {
    this.chill = chill;
}

@Column(name = "temperature", length = 10)
public String getTemperature() {
    return this.temperature;
}

public void setTemperature(String temperature) {
    this.temperature = temperature;
}

@Column(name = "substrate", length = 5)
public String getSubstrate() {
    return this.substrate;
}

public void setSubstrate(String substrate) {
    this.substrate = substrate;
}

@Column(name = "no_seeds")
public Integer getNoSeeds() {
    return this.noSeeds;
}

public void setNoSeeds(Integer noSeeds) {
    this.noSeeds = noSeeds;
}

@OneToMany(fetch = FetchType.LAZY, mappedBy = "kind")
@JsonIgnore
public List<Sample> getSamples() {
    return this.samples;
}

public void setSamples(List<Sample> samples) {
    this.samples = samples;
}

@Override
public int hashCode() {
    int hash = 3;
    hash = 47 * hash + Objects.hashCode(this.id);
    return hash;
}

@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final Kind other = (Kind) obj;
    if (!Objects.equals(this.id, other.id)) {
        return false;
    }
    return true;
}

@Override
public String toString() {
    return "Kind{" + "id=" + id + ", name=" + name + ", germinationDays=" + germinationDays + ", firstCount=" + firstCount + ", replicates=" + replicates + ", dark=" + dark + ", chill=" + chill + ", temperature=" + temperature + ", substrate=" + substrate + ", noSeeds=" + noSeeds + '}';
}

}


Solution

  • Well, I just found a solution creating enum with the values I need in the select

    public enum SubstrateType{
        BP,
        PP,
        TP,
        OGM,
        Sand;
    }    
    

    In my controller:

    @ModelAttribute("substrates")
    public SubstrateType[] getSubstrates() {
        return SubstrateType.values();
    }    
    

    I know it should work without enum as I have seen this before. Anyway I think is a good practice having enum.