0

Подскажите, как передать объект в форме spring. Я использую Thymeleaf.

<tbody>
            <tr style="font-size: 13px">
                <td th:text="${record.getId()}"></td>
                <form action="#" th:action="@{/update}" th:object="${record}" method="post">
                    <input type="hidden" th:field="*{id}" th:value="${record.getId()}" />
                    <td>
                        <input type="text" th:field="*{date_recording}" th:value="${record.getDate_recording()}" />
                    </td>
                    <td>
                        <input type="text" th:field="*{sum}" th:value="${record.getSum()}" />
                    </td>

                    <td>
                        <input type="text" th:field="*{purpose_of_payment}" th:value="${record.getPurpose_of_payment()}" />
                    </td>
                    <td>
                        <select th:field="*{article}">
                            <option th:each="article : ${articles}" th:value="${article.getName()}" th:name="article" th:text="${article.getName()}"></option>
                        </select>
                    </td>
                    <td>
                        <input type="text" th:field="*{source_type}" th:value="${record.getSource_type()}" />
                    </td>
                    <td>
                        <input type="text" th:field="*{payer}" th:value="${record.getPayer()}" />
                    </td>
                    <td>
                        <input type="text" th:field="*{recipient}" th:value="${record.getRecipient()}" />
                    </td>
                    <td th:if="${record.getId() != 0}"><input type="submit" value="Обновить"/></td>
                    <td th:if="${record.getId() == 0}"><input type="submit" value="Создать"/></td>
                </form>
            </tr>
        </tbody>

Поле article - это список объектов. Пользователь должен выбрать один и отправить форму. Но когда я делаю это текущим способом, то мне спринг пишет ошибку:

Field error in object 'record' on field 'article': rejected value [Выручка]; codes [typeMismatch.record.article,typeMismatch.article,typeMismatch.com.example.models.Article,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [record.article,article]; arguments []; default message [article]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.example.models.Article' for property 'article'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Integer] for value 'Выручка'; nested exception is java.lang.NumberFormatException: For input string: "Выручка"]]

Тип string нельзя преобразовать к Article. Если я форме я указываю th:value="${article}" (как бы, сам объект), то пишет ту же самую ошибку:

Field error in object 'record' on field 'article': rejected value [com.example.models.Article@c53773f]; codes [typeMismatch.record.article,typeMismatch.article,typeMismatch.com.example.models.Article,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [record.article,article]; arguments []; default message [article]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.example.models.Article' for property 'article'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.lang.Integer] for value 'com.example.models.Article@c53773f'; nested exception is java.lang.NumberFormatException: For input string: "com.example.models.Article@c53773f"]]

Record:

@Entity
@Table(name = "records")
public class Record {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

@ManyToOne
private Article article;

private double sum;
private String source_type;
private String purpose_of_payment;
private String dateRecording;
private String payer;
private String recipient;

public Record() {
    this.payer = "";
    this.recipient = "";
    this.sum = 0d;
    this.source_type = null;
    this.article = null;
    this.purpose_of_payment = null;
    this.dateRecording = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
}

public Record(String payer, String recipient, double sum, String source_type, Article article, String purpose_of_payment, String date_recording) {
    this.payer = payer;
    this.recipient = recipient;
    this.sum = sum;
    this.source_type = source_type;
    this.article = article;
    this.purpose_of_payment = purpose_of_payment;
    this.dateRecording = date_recording;
}

-- getters and setters --

1 ответ 1

0

Хм, я, оказывается, дебил. Достаточно передать в форме id. Spring дальше сам всё сделает.

<option th:each="article : ${articles}" th:value="${article.getId()}" th:name="article" th:text="${article.getName()}"></option>

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.