Search code examples
sqlgrailsgsp

grails: show field of object in gsp


In my grails project I create instances of an object called Patient, that has got a field city.

class Patient {

 String name;
 String surname;
 String cf;
 String address;
 String cap;
 String city;
 String province;
 String country;
 String phone_1;
 String phone_2;
 String email;
 String vat;

}

When I create a Patient, I store city by its id, but I want that, in show() and list() methods, I see the name of the related city.

The Cities domain class is linked to a table in my db as follows

class Cities {

String cityName;
String capOfCity;
String provinceOfCity;

static constraints = {
}

static mapping = {
    table 's_cap'
    id column: 'idcap'
    cityName column: 'comune'
    capOfCity column: 'cap'
    provinceOfCity column: 'prov'
    version false
}  
}

I suppose that I must perform a query to db to get its name by id, but how can I do it in gsp?


Solution

  • With your current approach you can do

    def show(){
       // look up your patient object
       def patient = Patient.get(123)
       def patientCityObject = Cities.findByCityName(patient.city)
       [patientCityObject: patientCityObject ]
    }
    

    GSP:

    <p>${patientCityObject.cityName}</p>
    

    However,

    If you define the association between your domains then Grails will load your city when you are accessing it. To access you city object associated with Patient, you can define it as follow:

    class Patient {
     ...
     Cities city;
     ...
    
    }
    

    Then when you have the patient object, you can easily access its property city.

    def patient = Patient.get(123)
    patient.city.cityName
    

    This will give you the city object associated with your patient. Then you can pass that into your GSP and use it.

    To learn more about GORM and object relation you can read Object Relational Mapping