I need to populate a dropdown list mapping from a entity (table) attribute for a form. Since the values are static (there's only 6 values repeated along the insert values), i thought that it might be a good idea get a list of those values and send to the Controller class and map into the view as Select button with Thymeleaf.
I know i could get the attribute 'Status' values directly from the entity, but i dont know the best way to do it
So, my question is:
Is it possible to populate a select dropdown button from a jpql query? Is there another better way to populate from unique entity attributes?
I tried to create a query like the next one, to get unique values from the attribute 'Status' which belongs to a entity named 'Orders', but this query generates a list without an associated id just the unique values (Also I thought about to create a query with a new temporary autoincrement id column, without success).
This is my entity:
@Data
@Entity
@Table(name="orders")
public class Orders implements Serializable {
@Id
private Integer orderNumber;
@Column
private String orderDate;
@Column
private String requiredDate;
@Column
private String shippedDate;
@Column
private String status;
// ...
}
@Repository("ordersDAO")
public interface OrdersDAO extends JpaRepository<Orders,Integer>{
@Query("SELECT DISTINCT o.status FROM orders o")
//
@Transactional(readOnly = true)
public List <Orders> getAllStatus();
From this point forward i can't resolve (neither the Controller nor form templates).
UPDATE
I'm trying this code, but it doesn't work. Let me know the errors to improve:
Service Implementation
public class OrdersServiceImpl implements OrdersService{
@Override
public List<Orders> getAllStatus() {
return ordersDAO.getAllStatus();
}
}
Controller
@Controller
@Slf4j
public class IndexController {
String url = "";
@Autowired
@Qualifier("ordersServiceImpl")
private OrdersService ordersService;
@GetMapping("/")
public String getStatusDropdown(Model model){
List<Orders> statusDropdown = ordersService.getAllStatus();
model.addAttribute("statusDropdown", statusDropdown);
return "forms";
}
HTML form
<div class="form-row align-items-center">
<div th:object="${statusDropdown}" class="col-2 my-1">
<label for="Estado" class="mr-sm-2">Estado</label>
<select class="custom-select mr-sm-2" id="Estado" form="ordersForm">
<option selected>Seleccione Estado</option>
<option th:each="status : ${statusDropdown}" th:text="${status}" th:value="${status}">Estado 1</option>
</select>
</div>
<div class="col align-self-end my-1">
<input class="btn btn-info" type="submit" value="Buscar" th:href="@{/getOrdersByStatus}">
</div>
</div>