Wicket - DropDownChoice from Enum to Primitive - wicket

Im having some problem with DropDownChoice.
I have an Enum with a list of school title like:
public enum StudyTitle {
NONE(null,null),ELEMENTARY("1","Elementary"),COLLEGE("2","College");
private String code;
private String description;
private StudyTitle(String code, String description){
setCode(code);
setDescription(description);
}
[setter and getter]
}
Then I have a Pojo with a String proprerty call "studyTitleCode" where I want to put the code (ex 1 for elementary, 2 for college etc...).
When I create a DropDownChoice Wicket doesn't allow me to have a proprerty Model of type String if the DropDownChoice is of type StudyTitle.
Ex.
[building the listOfStudyTitle as ArrayList of Enums]
DropDownChoice<String> studyLevel = new DropDownChoice<String>("id",new PropertyModel<String>(myPojo,"studyTitleCode"),listOfStudyTitle,new ChoiceRenderer<StudyTitle>("description","code"));
Is there a Method to allow Wicket to link one property of the Enum to the Property of Model?
Thanks

The choice options for an AbstractSingleSelectChoice must match the type of the value model. The only related config option for the DropDownChoice that I'm aware of is the IChoiceRenderer which allows you to set how the enum value is rendered (vs the default call toString()).
One option would be, instead of using the enum instance itself for your choices model, give the enum a String property that can be used:
public enum TestEnum {
ONE ("ONE"),
TWO ("TWO"),
THREE ("THREE");
private String value;
TestEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public static List<String> getStringValues()
{
List<String> stringValues = new ArrayList<String>();
for (TestEnum test : values()) {
stringValues.add(test.getValue());
}
return stringValues;
}
}
#Override
protected void onInitialize() {
super.onInitialize();
IModel<String> myStringValueModel = new Model<String>();
add(new DropDownChoice<String>("id", myStringValueModel, TestEnum.getStringValues()));
}

Related

Why does dart has got special keywords for get and set?

I am new to flutter, I was just wondering special keywords for getter and setter. Why has dart kept special keywords get and set for getter and setter respectively? Is there any particular reason, because like other languages it could have been done with simple functions also.
Example in dart we have get and set keywords.
class Person {
String _name;
String get name => _name;
set name (String val) => _name = val;
}
In java, we do the same using public methods.
// Java, No get, set keywords used
public class Person {
private String name; // private = restricted access
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
Why do we need separate get and set keywords in dart? Is that different from a normal getter and setter methods that we use in java, cop
We could simply use
class Person {
String _name;
String getName() => _name;
void setName(String val) => _name=val;
}
I know this is something like using variables directly instead of methods, Simply my question is Is there anything that we can't achieve in a simple getter and setter methods that we can do using get and set keywords?
This is basically for convenience and backward compatibility. Let's say you start off with a public field:
class Person {
final String name;
}
but then you decide name should rather be a calculated field based on first and last name:
class Person {
final String lastName;
final String firstName;
String get name => '$firstName $lastName';
}
in java it is a best practice to never, ever have a public class member variable, just because it doesn't have a way to transition to a method without changing the API. so you ALWAYS have to write getVariable() acessor methods, even if 99% of those only have return variable; as body.

How to use hidden field to store data model in wicket

I have a entity, name Product.It have two property is unit (byte) and unitName(String). unit property is mapped on database. Ex: 0:Kg ; 1:g;.... I want when input a valid unit, unit property is stored; unless, it save to unitName
Product
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "product_id")
private int productId;
#Column(name = "product_name")
private String productName;
#Column(name = "unit")
private Byte unit;
#Transient
private String unitName;
}
In unit text field, I use a UnitConvert
UnitConvert
public class UnitConverter implements IConverter<Byte> {
private static final long serialVersionUID = 4798262219257031818L;
public UnitConverter() {
}
#Override
public Byte convertToObject(String value, Locale locale) {
return Text.isEmpty(value) ? 0 : UtilCommon.getTaniCode(value);
}
#Override
public String convertToString(Byte value, Locale locale) {
return (value == null || value==0 ) ? "" : UtilCommon.getTaniName(value);
}
}
I only think about HiddenField to do that, but I don't know how to do that.
Someone know how to use or anything can help me. Thank you very much
So from what I understood you want to save the input of a Model to a different database property depending on certain checks before hand. You can do that in your Form.onSubmit() method.
A very simple implementation could look like this:
public ProductPanel(String id, final IModel<Object> productModel) {
super(id, productModel);
// we're putting the productModel into the constructor.
// Therefore it's guaranteed to be detached
// -> it's okay to have it with final modifier.
IModel<String> formModel = Model.of("");
Form<String> form = new Form<String>("form", formModel) {
#Override
protected void onSubmit() {
super.onSubmit();
String productName = getModelObject();
Object realProduct = productModel.getObject();
if (isAcceptableUnit(productName)) {
realProduct.setUnit(parseUnit(productName));
} else {
realProduct.setUnitName(productName);
}
layer.saveProduct();
}
};
add(form);
TextField<String> productName = new TextField<String>("textField", formModel);
form.add(productName);
}
private boolean isAcceptableUnit(String productName) {
// your logic to determine if it's okay to cast to byte here...
return true;
}
private byte parseUnit(String productName) {
// your logic to parse the String to byte here...
return 0;
}
Some additional comments since I'm uncertain if the code snippets you provided are just for simplicity or actually code pieces:
You should try to avoid declaring your db object Serializable. Should you use normal Model objects to save your DTOs wicket will actually serialize them and you won't be able to do anything with them (well with hibernate at least).
Database object should use LoadableDetachableModel and save the primary key to load the entity in the load() method of it.
This would enable you now to work directly on those objects by using CompoundPropertyModel etc (which has it's pros and cons which I will not explain in detail here).
Still in your case I would add an Model<String> to the form and let the server decide how the input should be handled and mapped to the actual domain object.

Disadvantages of interface objected programming

class Person{
private String name;
private int age;
private String gender;
//......
}
class Student extends Person{
private String id;
private String schoolBelongTo;
//......
}
public void showInfoOf(Person person){
System.out.println(person.getName());
//......
}
When using function "showInfoOf" ,if an object of Peron is used as the param,OK.However,if it is the type Student,I cannot get access to the field id and schoolBelongTo.
So I am confused ,how to ?
Actually, I want to know is this one of its(Interface oriented programming's or Supper class oriented programming's) disadvantages???
Two possible solutions:
You can programatically check the type in showInfoOf (Person), and use a cast to access & print the desired fields; or,
You can define a method on Person which will print/provide the desired info -- and either replace showPersonInfo() with that entirely, or call it into it. This is the more OO way.
Example:
abstract class Person {
private String name;
private int age;
private String gender;
public void printInfo() {
System.out.println( name);
}
}
class Student extends Person{
private String id;
private String schoolBelongTo;
#Override
public void printInfo() {
super.printInfo();
System.out.println( id);
System.out.println( schoolBelongTo);
}
}
public void showInfoOf (Person person){
person.printInfo();
}
In this example, all functionality has moved to Person.printInfo() and there is no real functionality remaining in showInfoOf (Person).
However in the real-world, you'd probably want move versatility in a Person.provideInfo() function -- perhaps returning a LinkedHashMap of fields & values (since unlabelled values on their own, are not great design).
The showInfoOf (Person) function could then handle formatting & printing the values to the specific requirement, leaving the Person.provideInfo() function general & multi-purpose.
in showInfoOf() you would have to check that person is of type Student, then cast it as a Student to get id or schoolBelongsTo

How to store a complex type with only one value in Entity Framework?

I'm using EF Code First and have an entity which has a Telephone property of type PhoneNumber. The PhoneNumber class has some validation and convenience methods, but essentially holds a string with a correct phone number.
I want to persist this to the database as a simple string. How would I go about this?
Do I need to register some sort of type converter, or do I really need to expose a public property on my PhoneNumber class which is used as complex type (I'd rather not have a public property like this, since I would like PhoneNumber to be immutable).
This is my PhoneNumber class:
public class PhoneNumber {
private string _number;
public PhoneNumber(string number) {
if (!IsValid(number)) {
throw new ArgumentException("Invalid Dutch phone number.");
}
_number = number;
}
private static string Sanitize(string number) {
return number.Trim()
.Replace("-", String.Empty)
.Replace(" ", String.Empty);
}
public bool IsValid() {
return IsValid(this);
}
public static bool IsValid(string number) {
if (number == null) {
return false;
}
var cleanNumber = Sanitize(number);
return Regex.IsMatch(cleanNumber, #"^06\d{8}$");
}
public static implicit operator PhoneNumber(string number) {
return new PhoneNumber(number);
}
public static implicit operator string(PhoneNumber number) {
return number.ToString();
}
}
You will have to add this to your code:
public string Number
{
get { return _number; }
private set { _number = value; }
}
private PhoneNumber() {}
and map your class as complex type:
modelBuilder.ComplexType<PhoneNumber>();

what is use of creating property in separate class for each entilty?

I am learning some good code practice that's why i was going through some code, some thing i could not understand in it. It has made property in a separate class for each entity like in userClass it has property
#region public properties
private int uid;
public int userId
{
get { return uid; }
set { uid = value; }
}
private string uName;
public string userName
{
get { return uName; }
set { uName = value; }
}
private string pwd;
public string password
{
get { return pwd; }
// set { pwd = value; }
}
private string uAddress;
public string userAddress
{
get { return uAddress; }
set { uAddress = value; }
}
private string fName;
public string firstName
{
get { return fName; }
set { fName = value; }
}
private string lName;
public string lastName
{
get { return lName; }
set { lName = value; }
}
private string uPhone;
public string userPhone
{
get { return uPhone; }
set { uPhone = value; }
}
private string uMobile;
public string userMobile
{
get { return uMobile; }
set { uMobile = value; }
}
private int secretQuestion;
public int securityQuestion
{
get { return secretQuestion; }
set { secretQuestion = value; }
}
private string userAnswer;
public string answer
{
get { return userAnswer; }
set { userAnswer = value; }
}
#endregion
and from the business logic class it uses the property instead of using directly any entity's attribute name, but i am confuse whats there need to make a property like this?
other then this it has got enums for database column name which has a clear reason behind this that if in near future we have to change the database table's fields name then we don't have to change through out the whole business logic class and we can make changes to enum directly, But what is there use of creating property like this please elaborate me on this
Are you really asking why it uses properties instead of having public fields?
Fields are an implementation detail - they're how data is stored, which shouldn't be something the outside world cares about, at least for 99% of types. Properties are part of the contract that a type has in terms of its API - the implementation is up to the type. In other words, it's a matter of encapsulation. Properties can be expressed in interfaces, as abstract methods etc, precisely because they keep the contract and the implementation separate.
Additionally, properties make databinding, debugging and various other things simpler. I have an article about why properties matter, which you may find useful.
Having said all of this, those properties are implemented in a tedious way - and they don't obey .NET naming conventions. I would have written them as:
public int UserId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
// etc
Properties can be defined on Interfaces, but member fields cannot. So if you needed to refactor this class to a class that implements an interface, you can put the properties on the interface (and then have other classes that implement them as well.)
Some similar questions:
Public Fields versus Automatic Properties
Property vs public field.
In additional to above: Actually you can easily decide public field or property by yourself. It is quite easier to understand that:
(1) Name is a property of class Person
(2) Speed is a property of class Plane
(3) Empty is a public field of class String. If you say String has a property named Empty, it's really weird. And String has a property Length is easy to understand.