drieu
drieu

Reputation: 367

grails select box Cannot cast String to List

I have the following in a select box

<div class="form-group">
<label for="machinename">Portails</label>
<select name='portalsChoice' multiple class="form-control">
    <g:each in="${portals}" var="portal">
        <option>${portal.name}</option>
    </g:each>
</select>
</div>

Then, in a controller, I get all parameter like this :

def mymethod() {
List<String> portalsChoice = params.portalsChoice
...
}

If I select 2 elements, it works well. I I select only 1 element, I have the following error : Cannot cast object 'my string' with class 'java.lang.String' to class 'java.util.List'

What is the best way to avoid this error ?

Thanks in advance,

Upvotes: 0

Views: 364

Answers (2)

D&#243;nal
D&#243;nal

Reputation: 187379

Replace this

def mymethod() {
    List<String> portalsChoice = params.portalsChoice
}

with

def mymethod() {
    List<String> portalsChoice = params.list('portalsChoice')
}

The portalsChoice list will contain the selected elements, regardless of how many were selected.

Upvotes: 1

Madhu Bose
Madhu Bose

Reputation: 371

You can provide a check in your controller:

List<String> portalsChoice = []
if(params.portalsChoice instanceof String){
   //force it to be a list 
   portalsChoice = params.list('portalsChoice')
}else{
//for multiple 
  portalsChoice = params.portalsChoice 
}

not so tricky but helps resolve your issue.

Upvotes: 0

Related Questions