简体   繁体   中英

Render SelectTag() with options from an array of models

I have a User model and a App model in my application. App has a belongs_to relation with User model.

In the template apps/new.plush.html I need to render the list of users as a drop down selection. I have implemented forms.Selectable interface like below in the User model -

func (a *User) SelectLabel() string {
    return a.Name
}

func (a *User) SelectValue() interface{} {
    return a.ID
}

The New() action in apps.go looks like this -

func (v AppsResource) New(c buffalo.Context) error {
    tx, ok := c.Value("tx").(*pop.Connection)
    if !ok {
        return fmt.Errorf("no transaction found")
    }

    users := &models.Users{}
    if atErr := tx.All(users); atErr != nil {
        return c.Error(http.StatusNotFound, atErr)
    }

    c.Set("users", users)
    c.Set("app", &models.App{})

    return c.Render(http.StatusOK, r.HTML("/apps/new.plush.html"))
}

Now, how do I write the Select Tag to render the options from the users array?

Below is not working -

<%= f.SelectTag("UserID", {options: users})%>

I have found the solution from #buffalo slack channel. The issue is with -

func (a *User) SelectLabel() string {
    return a.Name
}

func (a *User) SelectValue() interface{} {
    return a.ID
}

These should not be pointer methods. The correct version is -

func (a User) SelectLabel() string {
    return a.Name
}

func (a User) SelectValue() interface{} {
    return a.ID
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM