For this example we use SugarCRM, where MultiSelect fields are supplied as a JSON string, i.e. [{"value1","value2"}
First, I check to make sure my origin value ('reg') and existing value in Sugar ('existing') are not empty, as either case is easy to resolve.
if (string.IsNullOrEmpty(reg))
{
//Starfish.LogMessage("reg is empty");
result = existing;
}
else if (string.IsNullOrEmpty(existing))
{
//Starfish.LogMessage("existing is empty");
result = "[\""+reg+"\"]";
}
Next, I check to see if the origin value is already selected in the existing Sugar value.
else if (existing.Contains(reg))
{
//Starfish.LogMessage("existing already contains reg");
result = existing;
}
Now that all of the easy cases are out of the way, I deal with the case where I need to add the origin value to the existing Sugar value. In order for the data to be consistent for reporting, after adding the value, I convert the JSON string to an array, sort it, then convert it back to JSON format.
else
{
//Starfish.LogMessage("Need to add reg to existing value");
existing = existing.Replace(System.Environment.NewLine, "");
existing = existing.Replace(" ","");
string combined = existing.Replace("]","")+",\""+reg+"\"";
combined = combined.Replace("[","");
string[] combinedArray = combined.Split(',');
Array.Sort(combinedArray);
for (int j = 0; j <= combinedArray.GetUpperBound(0); j++)
{
//Starfish.LogMessage(combinedArray[j]+" ");
result = result + combinedArray[j] + ",";
}
result = result.TrimEnd(',');
result = "["+result+"]";
}