2014-10-08 18 views
1

我使用wicket和hibernate開發一個網站。我只是想保存一些表格的一些數據。 我的目標是這樣的:Wicket:從表單中設置JodaDateTime

@Entity 
@Table(name = "PRODUCT") 
@Inheritance(strategy=InheritanceType.SINGLE_TABLE) 
@DiscriminatorColumn(name="DISCRIMINATOR",discriminatorType=DiscriminatorType.STRING) 
@DiscriminatorValue(value="product") 
public class Product implements Serializable { 

@Id 
@GeneratedValue 
@Column(name = "PRODUCT_ID") 
private int productID; 

@Column(name = "START_DATE") 
@Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime") 
private DateTime startDate; 

public DateTime getStartDate() { 
    return startDate; 
} 

public void setStartDate(DateTime startDate) { 
    this.startDate = startDate; 
} 
} 

我有一個形式,其中,這種形式裏面有幾個輸入字段。對於日期字段,我用:

DatePicker datePicker = new DatePicker(); 
DateConverter dateConverter = new PatternDateConverter ("dd.MM.yyyy", false); 

final DateTextField startDate = new DateTextField("startDate",dateConverter); 
startDate.add(datePicker); 

如果我提交表單我得到這個異常:

Last cause: Could not convert value: 08.10.14 to type: org.joda.time.DateTime. Could not find  compatible converter. 
WicketMessage: Method onFormSubmitted of interface  org.apache.wicket.markup.html.form.IFormSubmitListener targeted at [Form [Component id = form]] on  component [Form [Component id = form]] threw an exception 

我猜它,因爲檢票口使用了的startDate的制定者。但是我怎麼編輯這個?

+1

您的表單是否使用'CompoundPropertyModel'?如果爲true,那麼我認爲它試圖將'Date'轉換爲'DateTime',並且失敗。嘗試使用'DateTextField'自定義模型(例如'New PropertyModel (this,「customDate」)')來存儲'Date'對象的實際值,當表單提交時 - >將'customDate'轉換爲'DateTime '對象並設置爲'Product'。 – 2014-10-08 15:09:27

+0

當存儲'DateTextField'時,我使用'@Temporal(TemporalType.TIMESTAMP)'而不是'@Type',然後我使用'Date'對象'private Date startDate;'。您還可以將'TemporalType'設置爲'Date' – pikand 2014-10-09 07:43:05

+0

嘿,我想我意識到我完全不瞭解模型。 @Michael說,我在DateTextField中添加了日期模型。 – monti 2014-10-09 13:02:44

回答

1

如果您爲表單使用CompoundPropertyModel,那麼表單組件將搜索真實模型對象的相應字段,將值應用於(表單組件的wicket:id必須等於模型的字段的名稱,並且此字段的類型必須與表單組件的返回相同)。

但是,如果模型中沒有相應的字段,或者我們想要使用獨立的表單組件,那麼我們只需要爲這樣的組件使用另一個模型。

由於DateTextField在轉換後返回Date並且您的模型有DateTime字段,您的異常出現了。

那麼,你至少有兩種方法可以解決這個問題:

  1. 詳見我的評論的方式來使用自定義的模型這一領域,並在onSubmit方法轉換Date值,從表單組件中取出,以DateTime目的。
  2. 但是,我認爲使用自己的轉換器更好。您可以強制您的DateTextField爲您的模型返回DateTime對象。請查看herehere(請參閱src中的URL TextField)以更好地瞭解如何實現此操作。你可以實現你自己的轉換器依靠org.apache.wicket.datetime.DateConverter src。