Search code examples
grailsgsp

Set select value in gsp


Controller:

     def abbrev = [:]
        abbrev.put(1,"I")
        abbrev.put(2,"II")
        abbrev.put(3,"III")
        abbrev.put(4,"IV")
        List<Expando> abbreviations = abbrev.collect{
          abbreviation -> Expando.newInstance(key:abbreviation.key,value:abbreviation.value)
        }

            def row = [:]
            def programRows = [ ]

    somelist.each {
              item -> row = [key1:value1, key2,value2 ]
                programRows << row
            }

[abbreviations:abbreviations, programRows:programRows ]

I iterate through programRows so i get a map ( programRow ). the map value1 is equivalent to a key in abbreviations ( List of Expandos ) so i want to set the select value based on this: i commented the option value so you can understand what value i want to assign.

View gsp:

    <g:each in="${programRows}" var="programRow">
   <g:select name="abbrevs" from="${abbreviations}" optionValue="//programRow.get('key1')//" optionKey="key" class="vfuCourseAbbreviations"/>

How can i do this??


Solution

  • I'd put your code so:

    def someAction(){
      def abbreviations = [ 'I', 'II', 'III', 'IV' ]
      def programRows = somelist.collect {
        [ key1:value1, key2:value2 ] // as "value1" you have to pass the index in "abbreviations"
      }
      [ abbreviations:abbreviations, programRows:programRows ]
    }
    

    the GSP:

    <g:each in="${programRows}" var="programRow">     
      <select name="abbrevs">
        <g:each in="${abbreviations}" var="abbr" status="i">
          <option value="${i}" ${i == programRow.key1 ? 'selected' : ''}>${abbr}</option>
        </g:each>
      </select>     
    </g:each>