2

I have to populate a select box with all avaliable Disciplines that are stored in my DB.

So, in DisciplineController I created an action like this:

def getDisciplinesJson() {

def discList = Discipline.getAll()
return discList as JSON

}

Is that the right way to get disciplines as JSON, and how do I call this action and, using Javascript for example, populate a select box, something like this:

<select id=disc-select> </select>

This select box appears in other page, Student create, for example.

MariaH
  • 331
  • 1
  • 8
  • 21

3 Answers3

2

There are a lot of ways. For example using JQuery

<script>
  function loadDisciplines() {
    $.ajax({
      url: "${createLink(controller: 'DisciplineController', action: 'getDisciplinesJson')}",
      success: function (data) {
        //...
// Parse JSON, create select box etc..
      }
    });
  }
</script>

And change "return discList as JSON" to "render discList as JSON"

Also you can create template with code:

<select id=disc-select> 
<g:each in="${discList}" var="disc">
<option value="${disc?.id}">${disc?.name}</option>
</g:each>
</select>

And return from controller already rendered template:

render template:"pathToTemplate/thisTEmplate", model:[discList:discList]

Then in the loadDisciplines() success block you need to put only:

$('#disciplines-div').html(data);

where #disciplines-div is

<div id="disciplines-div"></div>
Evgeny Smirnov
  • 2,886
  • 1
  • 12
  • 22
1

If you don't mind altering select to data lists then even easier is dataList HTML5 supports data lists and you can find an example here: and show here:

<input type=text list=browsers>
<datalist id=browsers>
  <option value="Firefox">
  <option value="IE">
  <option value="Chrome">
  <option value="Opera">
  <option value="Safari">
</datalist>

If you wanted to see auto complete working with dataLists then check out boselecta. I have used it for auto completion and you can find that example here. There are some further complexity of parsing the json as data lists but it is all within that page..

Community
  • 1
  • 1
V H
  • 8,382
  • 2
  • 28
  • 48
0

I know your question is 'How to populate a select box with JSON from Grails Controller' but looking at your example. Why do you need to populate it with JSON?

In this case a <g:select> tag could be a simpler approach.

<g:select id="disc-select" from="${my.package.Discipline.list()}" name="myparam"/>

This is assuming that you´re using GSPs

Roberto Perez Alcolea
  • 1,408
  • 11
  • 11