Search code examples
javagroovygrails

How to get a record from a different controller


I am trying to grab a record from one controller and pass it into another controller. On the main page, I use the CaseRecordController.groovy to populate information by ID like this:

def show() {
    def caseRecordInstance

    try {
        def id = Long.parseLong(params.id)
        caseRecordInstance = CaseRecord.findById(id)
    }...
}

And then it goes to the next page, BaseLineController.groovy which uses the same kind of code to get the page's information:

def show() {
    def baselineInstance
    def caseRecordInstance

    if(params.id) baselineInstance = Baseline.findById(Long.parseLong(params.id))

    try {
        def id = Long.parseLong(params.id)
        caseRecordInstance = CaseRecord.findById(id)
    }...
}

...which works for getting that controllers ID ( which is different because it uses a different controller ). But I want to grab the ID from the previous controller, the CaseRecordController, to get that information.


Solution

  • You have 2 options here:

    1. Put the id into the session and grab it from anywhere else at any time.
    2. Use the flash-scope to do the same, but only once.

    This is how it can look like:

    def showA() {
       session.caseRecordId = params.id
       // or
       flash.caseRecordId = params.id
    }
    
    def showB() {
       println session.caseRecordId
       // or
       println flash.caseRecordId // only once
    }