darrachequesne / spring-data-jpa-datatables

Spring Data JPA extension to work with the great jQuery plugin DataTables (https://datatables.net/)
Apache License 2.0
441 stars 174 forks source link

Display Enum value #110

Closed sebasira closed 4 years ago

sebasira commented 4 years ago

I have a problem and don't know how to solve it.

There's an Entity, let's call it Person with the following definition

public class Person{
    @JsonView(DataTablesOutput.View.class)
    private Long id;

    @JsonView(DataTablesOutput.View.class)
    private GenderType gender;

    @JsonView(DataTablesOutput.View.class)
    private String name;
}

The GenderType is an enum like:

public enum GenderType{
    MALE("boy"), FEMALE("girl");

    @JsonView(DataTablesOutput.View.class)
    public final String displayValue;

    GenderType(String displayValue) {
        this.displayValue = displayValue;
    }

    @Override
    public String toString() {
        return displayValue;
    }
}

And when rendering the DataTable I have:

var table = $('#mydatatable').DataTable({
    ajax: {
        .....
        ......
    },
        serverSide: true,
        columns: [
            {
                data: 'id'
            },
            {
                data: 'name'
            },
            {
                data: 'gender'
            },
       ]
});

And the problem I'm facing is that the GENDER Column displays MALE or FEMALE and I want it to be boy or girl. (It's a little bit complex than that, but the same principle). I mean what I want is to display the String value of the enum.

I've also tried with:

{
    data: 'gender.displayValue'
}

But it gives me this error:

DataTables warning: table id=mi-datatable - org.hibernate.jpa.criteria.BasicPathUsageException: Cannot join to attribute of basic type

and the DataTable is not rendered.

Thank you!

darrachequesne commented 4 years ago

Hi! I guess you have found a solution by now, but for future readers:

public enum GenderType{
    MALE("boy"), FEMALE("girl");

    public final String displayValue;

    GenderType(String displayValue) {
        this.displayValue = displayValue;
    }

    @Override
    @JsonValue
    public String toString() {
        return displayValue;
    }
}
const genderMap = {
  FEMALE: 'girl',
  MALE: 'boy'
}

$('#my-table').DataTable({
  columns: [
    {
      data: 'gender',
      render: (data) =>  genderMap[data] || '-'
    },
  ]
});
sebasira commented 4 years ago

Thanks! Yes I solve it by the second approach. But I like most the first one because I don't need to replicate the genderMap whenever the enum changes.

Thank you!