开发者

In Grails how do I capture multiple selected items in g:select?

I have a Contact Domain class that can be associated with multiple Organizations, which are also domain classes. I want to use a multiple selection box to allow the user to select the organizations that are associated with the current contact. The selection box is populated with the available organizations. How do I assign the selected items to the organizations list in my Contact class?

 <g:select name="organizations.id"  
           multiple="multiple" 
           optionKey="id" 
           from="${com.ur.Organization.list()}" 
           value="${contact?.organizations}" />

The above is what I am currently trying, and while it does populate the selection with organizations it doesn't seem to put the selected items in my organizations field.

Thanks for any advice.

Edit: Incorporated comments from krsjunk a开发者_运维问答nd omarello.

Here's an abbreviated version of the domain classes.

class Contact{
    static searchable = true
    static mapping = {
        sort "lastName"
    }
    String firstName
    String lastName
    .  
    .
    .
    static belongsTo = [organizations:Organization, projects:Project]
}

class Organization {
    static searchable = true
    static mapping = {
        sort "name"
    }
    String name
    static hasMany = [contacts:Contact]
}


Well just change the name to

<g:select name="organizations"  multiple="multiple" 
          optionKey="id" 
          from="${com.ur.Organization.list()}" 
          value="${contact?.organizations}" />

Should work fine, just tried it.

Note my domain definitions look like this, (just in case you have something different

class Contact {

    static constraints = {
    }

    static hasMany = [organizations:Organization]

    String name
}


class Organization {

    static constraints = {
    }

    static hasMany = [contacts:Contact]
    static belongsTo = [Contact]

    String name
}


one problem is that value="contact?.organizations" should be value="${contact?.organizations}" — not sure if that is the whole problem or not. (also, the attribute multiple=".." is not necessary if value is a collection)

You may also need name="contact.organizations" to be name="contact.organizations.id" and another attribute optionKey="id"


In your newly edit domain example you don't have a one-to-many relationship between contact and organization. You have a one-to-many from organization to contact.

So

value="${contact?.organizations}"

will always be a single item, never a list.

Trying to select/assign multiple organization to a contact will never be valid.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜