2

I have a component with a metadata multiselect field as Location, for which options will load from a category. Users are allowed to select more then one option. I have below code which is working fine except giving the repeating value of options if selected more than one option.
for example. If user has selected two locations i.e. location1 & location2 from the location field.
IEnumerable<Keyword> fields = primarykeyfield.Values; , fields is returing count as 4, and value its displaying as location1,location2,location1,location2.

private static string GetLocation(Component Comp, Engine engine)
    {
        string Location = string.Empty;

        ItemFields componentMetaFields = new ItemFields(Comp.Metadata, Comp.MetadataSchema);

        if (Comp.Metadata != null)
        {
            foreach (XmlNode node in Comp.Metadata.ChildNodes)
            {
                if (node.Name.ToLower() == "location")
                {
                    KeywordField primarykeyfield = componentMetaFields["location"] as KeywordField;

                    if (primarykeyfield != null)
                    {
                        //Get the Keyword
                        IEnumerable<Keyword> fields = primarykeyfield.Values;
                        foreach (Keyword kt in fields)
                        {
                            if (Location == string.Empty)
                                Location = kt.Title.ToString();
                            else
                                Location = Location + "," + kt.Title.ToString();
                        }

                    }
                }

            }
        }

        return Location;
    }

IT will be great if anyone can point the mistake so that i can get the result as location1,location2, on selecting two values from Location field.

4

Without running the code, I think the problem is your initial for loop. If you look at the XML source of a Component with categories in the metadata (one of ours for example) :

<Metadata xmlns="uuid:f24b9067-dcb6-4ef1-8982-3dde4129fdab">
    <region>Singapore</region>
    <region>United Arab Emirates (Middle East)</region>
</Metadata>

If you then run foreach child node, you are effectively running your code twice. Short version: you don't need the loop.

  • Thank you for pointing this mistake. After removing that loop problem got resolved. – SDLBeginner Aug 2 '16 at 16:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.