Search code examples
listformsgrailsselectedindex

Grails g:select setting selectedIndex


How do you set the selectedIndex on a <g:select> tag with a value from the list? I have a page that allows you to add a record. the page then goes to a view containing a g:select and i want the g:select to default to that item i just inserted into the database.

I tried passing the new object in the flash but i can't figure out how to get it's index in the list being used to generate the g:select data.


Solution

  • Supposing you store a Book object in flash.book at the controller level, your second page could look like this :

    <html>
        <head>
            <g:javascript library="prototype" />
            <g:javascript>
                  function showLast(selectedId) {
                      if (selectedId) {
                        $$('#books option[value=' + selectedId + "]")[0].selected = true;
                      } else {
                        $('books').selectedIndex = 0;
                      }
                  };
    
                  Event.observe(window, 'load', init, false);
    
                  function init() {
                      showLast(${flash?.book?.id});
                  }
                </g:javascript>
        </head>
        <body>
            <g:select id="books" name="id"
                      from="${Book.list()}"
                      value="title"
                      optionValue="title"
                      optionKey="id"
             />
        </body>
    </html>