Adding and Removing Teams Within Sugar

From time to time you will need to change the teams on a records, via code, probably from a logic hook. This sounds easy but I had quite a lot of difficulty with it. I’ll give you what I learned

Firstly, Sugar have documented¬†here¬†very well, but there are aspects to it that just don’t work. Note that the code snippets below all come from the Sugar site, with a few modifications.

From their examples I found the following.

1. It is imperative that the primary team (team_id) be one of the teams to be included. If you are removing the primary team from the list of teams, make sure you allocate a new primary_team, and save the record, before you start adding and removing teams.

The code below shows setting a new primary team, and saving the record.

2. Use replace(), not add() and remove() as suggested in the Sugar article.

I had all sorts of problems using add(0 and remove(). When I turned to replace(), everything worked fine. I’m using Professional 6.5.14, so it may have been corrected in later editions.

The following is all you need, just replacing the array with all the teams you want included.

With the above you don’t need to worry about TeamSets at all.

Let me know if you have any comments or suggestions.