1

I tried to multiple select with select2 i used laravel and my data on userRoles is returned data on User model with relation roles, and allRoles is just all in Role model code on view

<select class="form-control" name="roles[]" id="roles"  multiple>
            <option v-for="role in allRoles"
                    :value="role.id"
                    >
                @{{ role.name }}
            </option>
 </select>

how to set selected options using userRoles array?

1 Answer 1

1

Add a computed hashMap (object) to search for selected roles:

computed: {
    selectedRoleMap() {
        var map = {};
        this.userRoles.forEach(role => {
            map[role] = 1;
        });
        return map;
    }
}

Then add :selected="selectedRoleMap.hasOwnProperty(role.id)" to options.

Working fiddle here: https://jsfiddle.net/df7j8xhz/

Alternatively, you can add a hasRole method to loop through userRoles to see if an id is in userRoles, but build a hashMap and search in it has a better performance than looping the array allRoles.length times.

Sign up to request clarification or add additional context in comments.

3 Comments

@Rai Why do you need that array? Your problem is making some of the optionss selected right?
@Rai Let us continue this discussion in chat.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.