grailsgsp

Grails gsp nested two selects


i've the following object

companies = [
{ id: 1, code: "cod1", employessList : [{id:1, name:"name1"}, {id:2, name:"name2"}, ...]},
{ id: 2, code: "cod2", employessList : [{id:4, name:"name1"}, {id:5, name:"name2"}, ...]},
{ id: 3, code: "cod3", employessList : [{id:11, name:"name1"}, {id:12, name:"name2"}, ...]},
...
]

i need put in gsp, two <g:select> one to choose the companies and an another to select the employess nested. And when i change the company the employees list update.

for instance,

<div> 
   <g:select id="companiesSelect" name="companies" from="${companies}" 
   class="form-control"                           optionKey="id" 
   optionValue="code" />
<div> 

<div> 
  <!-- Div with nested elements -->
</div>

Could someone help me with this?


Solution

  • You have 4 options here:

    1. Render both selects on the server side.

    Controller action:

    def somePage() {
      def companies = [...]
      def employees = params.companyId ? companies.findResult{ it.id == params.companyId ? it.employessList : null } : []
      [ companies:companies, employees:employees ]
    }
    

    GSP:

    <div> 
       <g:select id="companiesSelect" from="${companies}" onChange="refreshPage( this.value )" .../>
    <div> 
    
    <div> 
      <g:select id="employeesSelect" from="${employees}" .../>
    </div>
    

    where refreshPage( this.value ) is a JS-function to send the company id to controller action.

    1. Load the full list of companies+employees into the page as JSON, render that data as selects, and use the onChange-JS listener to refresh the 2nd select.

    2. Use Ajax call to load the data based on company id into employees select.

    The options 2 and 3 require a lot of JS, so I won't post it here.

    1. Use a modern JS framework like react to do the rendering, so that the server would be communicated over REST endpoint.