0

I am working with a Spring MVC project and I can't figure out how to change the String representation of a Model in the Views.

I have a Customer model that has a ONE_TO_MANY relationship with a WorkOrder model. On the workorders/show.jspx the Customer is displayed as a String that is the first and last name, email address, and phone number concatenated.

How do I change this? I thought I could just change the toString method on the Customer, but that didn't work.

MattL
  • 1,132
  • 10
  • 23
  • I dont think you should use the toString but rather something like ${customer.firstName} ${customer.lastName} etc... but it of course depends on what the model and the view looks like. – Björn May 31 '12 at 14:19

2 Answers2

1

One solution would be to change/push-in show() to WorkOrderController to map a rendered-view-tag to what you would like to see.

@RequestMapping(value = "/{id}", produces = "text/html")
public String show(
    @PathVariable("id") Long id, 
    Model uiModel)
{
    final WorkOrder workOrder = WorkOrder.findWorkOrder(id);
    uiModel.addAttribute("workOrder", workOrder);
    uiModel.addAttribute("itemId", id);
    // Everything but this next line is just ripped out from the aspectJ/roo stuff.
    // Write a method that returns a formatted string for the customer name, 
    // and a customer accessor for WorkOrder.
    uiModel.addAttribute("customerDisplay", workOrder.getCustomer().getDisplayName());
    return "workorders/show";
}

Put/define a label in your i18n/application.properties file for customerDisplay.

Then in your show.jspx, you can access the mapping with something like... (The trick is similar for other views.)

<field:display field="customerDisplay" id="s_your_package_path_model_WorkOrder_customerDisplay" object="${workorder}" z="user-managed" />

I'm new to Roo, so I'd love to see a better answer.

jlb
  • 679
  • 1
  • 10
  • 21
1

We found a good solution. There are toString() methods for all the models in ApplicationConversionServiceFactoryBean_Roo_ConversionService.aj

You can just push the method for the Model you want into ApplicationConversionServiceFactoryBean.java and modify it. In my case I added this:

public Converter<Customer, String> getCustomerToStringConverter() {
    return new org.springframework.core.convert.converter.Converter<com.eg.egmedia.bizapp.model.Customer, java.lang.String>() {
        public String convert(Customer customer) {
            return new StringBuilder().append(customer.getId()).append(' ').append(customer.getFirstName()).append(' ').append(customer.getLastName()).toString();
        }
    };
}

Spring uses this for all the view pages so this will change the String representation of your model across your whole app!

MattL
  • 1,132
  • 10
  • 23