繁体   English   中英

Thymeleaf动态字段,Spring启动

[英]Thymeleaf dynamic fields, Spring boot

我想动态创建对象列表(部分)。 基本上,应该将数据输入到字段中,然后按下按钮以添加到列表中,并在最后与整个表单一起提交。 我尝试使用jquery创建HTML,但尚未提交。 无法仅针对已更新的列表提交表单,因为其余表单将被删除。 除非,否则我可以为此在模态中创建一个表格。 纯胸腺有什么办法吗? 对代码格式表示歉意。 希望我已经很好地解释了我的问题。

编辑:

我在实现目标方面取得了一些进展。 因此,现在的解释应该更简单。 在作业控制器中,我有一个Get Request jobView(),它创建三个新的空对象的列表,并与表单绑定。 我想要实现的是将这些对象动态添加到列表中,而不是固定数量。 假设有汽车维修工作,用户可以根据使用的零件数量动态添加零件。

工作控制器:

    @Controller
public class JobController {
  @Autowired
  JobRepository jobRepository;
  @Autowired
  PartRepository partRepository;

  @GetMapping("/job/new")
  public String jobView(Model model) {
    Job job = new Job();
    for (int i = 0; i < 3; i++) {
      job.addPart(new Part());
    }
    model.addAttribute("job", job);
    return "newJob";
  }

  @GetMapping("/job/manage")
  public String jobManageView(Model model) {
    //model.addAttribute("job", new Job());
    model.addAttribute("jobs", jobRepository.findAll());
    //System.out.println("hello" + Arrays.asList(new CarService().getAllCars().get(1)));
    return "manageJobs";
  }

  @PostMapping("/job/new/add")
  public String jobAdd(@ModelAttribute Job job, RedirectAttributes redirectAttributes) {
    try {
      System.out.println(job.getParts());
      partRepository.saveAll(job.getParts());
      jobRepository.save(job);
      redirectAttributes.addFlashAttribute("message", "Success. Record updated");
      redirectAttributes.addFlashAttribute("alertClass", "alert-success");
      return "redirect:/job/new";
    } catch (Exception e) {
      e.printStackTrace();
      redirectAttributes.addFlashAttribute("message", "Failed. Please check the data");
      redirectAttributes.addFlashAttribute("alertClass", "alert-danger");
      return "redirect:/job/new";
    }

  }

HTML:

                <form action="#" class="form-control form-control-sm" th:action="'new/add'" th:object="${job}"
                                  method="post">
                                <!-- Custom Form Start -->
                                <div class="row">
                                    <div class="col-sm-6">
                                        <div class="card">
                                            <div class="card-header bg-secondary text-white">
                                                <a data-toggle="collapse" href="#collapse-example" aria-expanded="true"
                                                   aria-controls="collapse-example" id="heading-example" class="d-block">
                                                    <i class="fa fa-chevron-down pull-right"></i>
                                                    Job Info
                                                </a>
                                            </div>
                                            <div id="collapse-example" class="collapse show"
                                                 aria-labelledby="heading-example">
                                                <div class="card-body">
                                                    <div class="form-group row">
                                                        <label for="description" class="col-2 col-form-label">Description</label>
                                                        <div class="col-10">
                                                        <textarea th:field="*{description}" class="form-control" type="text"
                                                                  id="description"></textarea>
                                                        </div>
                                                    </div>

                                                    <div class="form-group row">
                                                        <label for="dateInput" class="col-2 col-form-label">Date</label>
                                                        <div class="col-10">
                                                            <input th:field="*{date}" class="form-control" type="date"
                                                                   id="dateInput">
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-sm-6">
                                        <div class="card">
                                            <div class="card-header bg-secondary text-white">
                                                Labour
                                            </div>
                                            <div class="card-body">
                                                <div class="form-group row">
                                                    <label for="repairTime" class="col-2 col-form-label">Time</label>
                                                    <div class="col-10">
                                                        <input class="form-control" id="repairTime" th:field="*{repairTime}"
                                                               type="number"
                                                               value="">
                                                    </div>
                                                </div>
                                                <div class="form-group row">
                                                    <label for="rate" class="col-2 col-form-label">Rate</label>
                                                    <div class="col-10">
                                                        <input th:field="*{rate}" class="form-control" type="text" value=""
                                                               id="rate">
                                                    </div>
                                                </div>
                                                <div class="form-group row">
                                                    <label for="total" class="col-2 col-form-label">Total</label>
                                                    <div class="col-10">
                                                        <input class="form-control" id="total" th:field="*{total}" type="text"
                                                               value="">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-sm-6">
                                        <div class="card">
                                            <div class="card-header bg-secondary text-white">
                                                Car Info
                                            </div>
                                            <div class="card-body">
                                                <div class="form-group row">
                                                    <label for="reg" class="col-2 col-form-label">Reg</label>
                                                    <div class="col-10">
                                                        <input class="form-control" id="reg" th:field="*{car.reg}" type="text"
                                                               value="">
                                                    </div>
                                                </div>
                                                <div class="form-group row">
                                                    <label for="make" class="col-2 col-form-label">Make</label>
                                                    <div class="col-10">
                                                        <input class="form-control" id="make" th:field="*{car.make}" type="text"
                                                               value="">
                                                    </div>
                                                </div>
                                                <div class="form-group row">
                                                    <label for="model" class="col-2 col-form-label">Model</label>
                                                    <div class="col-10">
                                                        <input class="form-control" id="model" th:field="*{car.model}" type="text"
                                                               value="">
                                                    </div>
                                                </div>
                                                <div class="form-group row">
                                                    <label for="year" class="col-2 col-form-label">Year</label>
                                                    <div class="col-10">
                                                        <input class="form-control" id="year" th:field="*{car.year}" type="text"
                                                               value="">
                                                    </div>
                                                </div>
                                                <div class="form-group row">
                                                    <label for="mileage" class="col-2 col-form-label">Mileage</label>
                                                    <div class="col-10">
                                                        <input class="form-control" id="mileage" th:field="*{car.mileage}"
                                                               type="text"
                                                               value="">
                                                    </div>
                                                </div>
                                                <div class="form-group row">
                                                    <label for="color" class="col-2 col-form-label">Color</label>
                                                    <div class="col-10">
                                                        <input class="form-control" id="color" th:field="*{car.color}" type="text"
                                                               value="">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-sm-6">
                                        <div class="card">
                                            <div class="card-header bg-secondary text-white">
                                                Parts
                                                <input type="radio" class="radio-gr">
                                            </div>
                                            <div class="card-body">
                                                <div class="form-group row ">
                                                    <label for="partName" class="col-2 col-form-label">Name</label>
                                                    <div class="col-10">
                                                        <input class="form-control"
                                                               id="partName"
                                                               type="text"
                                                               value="">
                                                    </div>
                                                </div>

                                                <div class="form-group row">
                                                    <label for="quantity" class="col-2 col-form-label">Quantity</label>
                                                    <div class="col-10">
                                                        <input class="form-control" type="number" value="" id="quantity">
                                                    </div>
                                                </div>
                                                <div class="form-group row">
                                                    <label for="invoiceNumber" class="col-2 col-form-label">Invoice Number</label>
                                                    <div class="col-10">
                                                        <input class="form-control" type="text" value="" id="invoiceNumber">
                                                    </div>
                                                </div>
                                                <div class="form-group row">

                                                    <label for="price" class="col-2 col-form-label">Price</label>
                                                    <div class="col-10">
                                                        <input class="form-control" type="text" value="" id="price">
                                                    </div>
                                                </div>
                                                <div class="form-group row">
                                                    <label for="supplier" class="col-2 col-form-label">Supplier</label>
                                                    <div class="col-10">
                                                        <input class="form-control" type="text" value="" id="supplier">
                                                    </div>
                                                </div>
                                                <div class="form-group row">
                                                    <label for="brand" class="col-2 col-form-label">Brand</label>
                                                    <div class="col-10">
                                                        <input class="form-control" type="text" value="" id="brand">
                                                    </div>
                                                </div>

                                            </div>
                                            <div class="btn-group ">

                                                <button type="button" class="btn-warning" data-toggle="collapse"
                                                        data-target="#collapse1">
                                                    Parts list
                                                    <i class="nav-icon fa fa-arrow-circle-down"></i>
                                                </button>
                                                <button class="btn-success" th:onclick="'javascript:addToPartsList();'"
                                                        type="button">
                                                    Add to list
                                                    <i class="nav-icon fa fa-plus-circle"></i>
                                                </button>
                                            </div>
                                            <div id="collapse1" class="panel-collapse collapse">
                                                <p>hello</p>
                                                <div class="form-group row " id="partsListContainer">
                                                    <div class="card-body" th:each="part, itemStat :*{parts}">
                                                        <input class="form-control"
                                                               th:field="*{parts[__${itemStat.index}__].name}"
                                                               type="text" value=""/>
                                                        <input class="form-control"
                                                               th:field="*{parts[__${itemStat.index}__].quantity}"
                                                               type="text" value=""/>
                                                        <input class="form-control"
                                                               th:field="*{parts[__${itemStat.index}__].invoiceNumber}"
                                                               type="text" value=""/>
                                                        <input class="form-control"
                                                               th:field="*{parts[__${itemStat.index}__].price}"
                                                               type="text" value=""/>
                                                        <input class="form-control"
                                                               th:field="*{parts[__${itemStat.index}__].supplier}"
                                                               type="text" value=""/>
                                                        <input class="form-control"
                                                               th:field="*{parts[__${itemStat.index}__].brand}"
                                                               type="text" value=""/>
                                                    </div>
                                                </div>

                                            </div>

                                        </div>
                                    </div>
                                </div>

                                <div class="col-sm-6">
                                    <div class="card">
                                        <div class="card-header bg-secondary text-white">
                                            Customer
                                        </div>
                                        <div class="card-body">
                                            <div class="form-group row">
                                                <label for="customerName" class="col-2 col-form-label">Name</label>
                                                <div class="col-10">
                                                    <input class="form-control" id="customerName" th:field="*{customer.name}"
                                                           type="text"
                                                           value="">
                                                </div>
                                            </div>
                                            <div class="form-group row">
                                                <label for="customerSurname" class="col-2 col-form-label">Surname</label>
                                                <div class="col-10">
                                                    <input class="form-control" id="customerSurname" th:field="*{customer.surname}"
                                                           type="text"
                                                           value="">
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div>
                                    <button type="reset" value="Reset" class="btn btn-danger">Reset form
                                    </button>
                                    <button type="submit" value="Submit" class="btn btn-success">Add new job</button>
                                </div>
                            </form>

工作:

    @Entity
@Table(name = "job")
@SecondaryTables({
                         @SecondaryTable(name = "labour")
                 })
public class Job {
  @Id
  @Column
  @GeneratedValue(strategy = GenerationType.AUTO)
  private Integer id;

  @Column
  private String description;

  @Column
  private String date;

  @OneToMany
  @JoinColumn(name = "JOBID", referencedColumnName = "ID")
  private List<Part> parts;

  @ManyToOne(cascade = CascadeType.ALL)
  @JoinColumn(name = "CARID", referencedColumnName = "ID")
  private Car car;

  @ManyToOne(cascade = CascadeType.ALL)
  @JoinColumn(name = "CUSTOMERID", referencedColumnName = "ID")
  private Customer customer;

  @Column(name = "repairTime", table = "labour")
  private int repairTime;

  @Column(name = "rate", table = "labour")
  private double rate;

  @Column(name = "total", table = "labour")
  private double total;

  public Job() {
    this.parts = new ArrayList<>();
  }


  public Integer getId() {
    return id;
  }

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

  public String getDescription() {
    return description;
  }

  public void setDescription(String description) {
    this.description = description;
  }

  public String getDate() {
    return date;
  }

  public void setDate(String date) {
    this.date = date;
  }


  public int getRepairTime() {
    return repairTime;
  }

  public void setRepairTime(int repairTime) {
    this.repairTime = repairTime;
  }

  public double getRate() {
    return rate;
  }

  public void setRate(double rate) {
    this.rate = rate;
  }

  public double getTotal() {
    return total;
  }

  public void setTotal(double total) {
    this.total = total;
  }

  public Car getCar() {
    return car;
  }

  public void setCar(Car car) {
    this.car = car;
  }

  public Customer getCustomer() {
    return customer;
  }

  public void setCustomer(Customer customer) {
    this.customer = customer;
  }

  public List<Part> getParts() {
    return parts;
  }

  public void addPart(Part part) {
    this.parts.add(part);
  }

  public String getPartsName() {
    String name = "";
    for (Part p : parts
    ) {
      name += "|| Invoice: " + p.getInvoiceNumber() + ", " + "name: " + p.getName() + " ";
    }
    return name;
  }

  public void setParts(List<Part> parts) {
    this.parts = parts;
  }
}

问题解决了。 研究HTML之后,其绑定的输入字段将转换为<input class="form-control" value="" id="parts0.name" name="parts[0].name" type="text"> JQuery中的输入我必须遵循此模板。 最终代码如下所示:

   var index = 1;

function addToPartsList() {
    var name = $("#partName").val();
    var quantity = $("#quantity").val();
    var invoice = $("#invoiceNumber").val();
    var price = $("#price").val();
    var supplier = $("#supplier").val();
    var brand = $("#brand").val();

    $(
        '<div class="col-10" >' +
        ' <input class="form-control" id="parts' + index + '.name" name="parts[' + index + '].name" type="text" value="' + name + '"> ' +
        '<input class="form-control" id="parts' + index + '.quantity" name="parts[' + index + '].quantity" type="text" value="' + quantity + '"> ' +
        '<input class="form-control" id="parts' + index + '.invoiceNumber" name="parts[' + index + '].invoiceNumber" type="text" value="' + invoice + '"> ' +
        '<input class="form-control" id="parts' + index + '.price" name="parts[' + index + '].price" type="text" value="' + price + '"> ' +
        '<input class="form-control" id="parts' + index + '.supplier" name="parts[' + index + '].supplier" type="text" value="' + supplier + '"> ' +
        '<input class="form-control" id="parts' + index + '.brand" name="parts[' + index + '].brand" type="text"' +
        ' value="' + brand + '"> ' +
        '</div>'
    ).appendTo('#collapse1');
    index++;
}

列表已成功注册,并且存储库已保存。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM