Exemple #1
0
        // Update tag field
        public void UpdateTagField(string userIput, string fieldName, Item tagRepository)
        {
            List <string> newInputData = userIput.Split('|').ToList();

            if (tagRepository.HasChildren)
            {
                Item        getTagRoot     = Sitecore.Configuration.Factory.GetDatabase("master").SelectSingleItem(TagRepository.Paths.FullPath);
                List <Item> getDescendants = getTagRoot.Axes.GetDescendants().Where(x => x.TemplateName == "Tag").ToList();

                // Get new tag list
                List <String> matchKey     = newInputData.Where(p => getDescendants.Any(p2 => p2.Name.ToLower() == ConvertName(p.Trim().ToLower()))).ToList();
                List <String> notMatchKey  = newInputData.Where(p => getDescendants.Any(p2 => p2.Name.ToLower() != ConvertName(p.Trim().ToLower()))).ToList();
                List <string> allTagItemId = new List <string>();
                notMatchKey.RemoveAll(r => matchKey.Any(r2 => r == r2));

                foreach (Item i in getDescendants)
                {
                    if (matchKey.Where(m => m.ToLower().ToString().Equals(i.Name.ToLower())).Any())
                    {
                        // Ignore other duplicated item having the same name
                        if (!allTagItemId.Where(a => CurrentDb.GetItem(a).Name.ToLower().Equals(i.Name.ToLower())).Any())
                        {
                            //Sitecore.Diagnostics.Log.Info("Match: " + i, this);
                            allTagItemId.Add(i.ID.ToString());
                        }
                    }
                }

                // Create new tag item
                foreach (string s in notMatchKey)
                {
                    if (!String.IsNullOrEmpty(s))
                    {
                        //Sitecore.Diagnostics.Log.Info("Not Match: " + s, this);
                        string       itemNameAndKey = ConvertName(s).ToLower();
                        TemplateItem tagTemplate    = CurrentDb.GetTemplate(TagTemplatePath.ID);
                        Item         newTag         = tagRepository.Add(itemNameAndKey.Trim(), tagTemplate);
                        allTagItemId.Add(newTag.ID.ToString());
                    }
                }

                // List of all assigned tags
                string outputList = allTagItemId.Aggregate((i, j) => i + "|" + j);
                using (new SecurityDisabler())
                {
                    CurrentPage.Editing.BeginEdit();
                    CurrentPage.Fields[fieldName].Value = outputList;
                    CurrentPage.Editing.EndEdit();
                    CurrentPage.Editing.AcceptChanges();
                }
            }
        }