Custom Collection of Items in Sitecore Multilist field datasource

I recently got a requirement to show upcoming News (News which date is greater then today’s date) into multilist field on Sitecore Item from News collections in content tree. So after looking into the requirement first thing came in my mind to create a custom Multilist field as we need to show dynamic collections of news on the bases  of current date (Today’s date). Or we need to provide custom datasource to multilist which should be driven by our custom code.

As much as I know about datasource is we can use fast query and query in that but I was not sure we can use custom code also in Datasource field. And I am sure many of us don’t know about the same.

I can see few of blog post about the same but I think because of keyword or meta data it is very difficult to find so I thought to write it again.

First I have created a class file and inherited that class with IDataSource interface (We need to provide reference of Sitecore.Buckets.dll for IDataSource).  And then I have implemented ListQuery method which is defined in IDataSource interface.

ListQuery method return type is Array of items so here we can do our custom code to get the array of items and return that collection as given in below script  –

In below code I am returning upcoming news items  –

public Item[] ListQuery(Item item)
        {
            item = Sitecore.Context.ContentDatabase.GetItem("/sitecore/content/Habitat/Home/Modules/Feature/News/News");
            return item.Axes.GetDescendants().Where(i=>i.IsDerived(Templates.NewsArticle.ID)).Where(i=>DateUtil.IsoDateToDateTime(i[Templates.NewsArticle.Fields.Date])>DateTime.Now).ToArray();
        }
        

And then I logged in to Sitecore and defined the Datasource in datasource field. Now in datasource field we need to define  code:NameSpace.ClassName, AssmeblyName as per given in below screenshot.

We will come with something new in next post…..

Advertisements
Posted in Sitecore, Sitecore Multilist, Sitecore Search | Tagged , , , | Leave a comment

Track search Keywords on Sitecore website

While working on Sitecore search we got a requirement where we need to store keyword s which is visitor will search in our website. First I thought to store them into Sitecore Database by creating items. But once I started looking into analytics feature I got that Sitecore analytics provides feature to store Site searches (Keywords). And also it provide more feature after storing them.

So I planned to use the analytics to store our site search keywords into analytics.

I created below function to store the keyword into sitecore analytics database  –


public bool IsActive => Tracker.Current != null && Tracker.Current.IsActive;

 public virtual void TrackSiteSearch(Item pageEventItem, string query)
        {
            Assert.ArgumentNotNull(pageEventItem, nameof(pageEventItem));
            Assert.IsNotNull(pageEventItem, $"Cannot find page event: {pageEventItem}");
            if (this.IsActive)
            {
                var pageEventData = new PageEventData("Search", [Search Event Item ID])
                {
                    ItemId = pageEventItem.ID.ToGuid(),
                    Data = query,
                    DataKey = query,
                    Text = query
                };
                var interaction = Tracker.Current.Session.Interaction;
                if (interaction != null)
                {
                    interaction.CurrentPage.Register(pageEventData);
                }
            }
        }

[Search Event Item ID] – It is the item id of the search event item created on /sitecore/system/Settings/Analytics/Page Events/Search location of Sitecore.

After creating this function you just need to call the function after getting the search results as below –

  if (!string.IsNullOrWhiteSpace(query) && results.Any())
     {
          TrackSiteSearch(ContextItem.Item, query.QueryText);
     }

This will store keyword into analytics database whenever visitor will perform search.

Where we can see the stored keywords in Sitecore analytics reports –

1. Open the ExperienceAnalytics dashboard from Launch pad as given in below screenshot

launch pad.png

2. Navigate to Behavior section and click on Internal search it will show complete report of searched keywords with all other analytics details as shown below.

 

launch pad2

 

In next post we will discuss how to show top searches keywords in site.

 

Posted in Sitecore, Sitecore Analytics | Tagged , | Leave a comment

Sitecore Search and filtering

This is not something you can’t find on internet but I am sure I’ll write some content or tips which is not easily available. I worked on search many times and every time I came across with different scenarios.

Here I am writing about my recent work with Sitecore search (Lucene & Solr). I have used filtering in our search with the help of predicate builder. It gives more capabilities to apply multiple filters with single line code. I would love to use predicate builder while working on search or filtering the results.

Here are some tips which can help you to get specific results as per your requirements  –

Sitecore Search allows you to use Linq to perform your search queries and uses the IQueryable<T> interface.

using (var context = ContentSearchManager.GetIndex(ContextItem).CreateSearchContext())
{

var queryable = context.GetQueryable<SearchResultItem>();

}

Here ContextItem is SitecoreIndexableItem item. you don’t need to specify the index name here. It will automatically pick the index as per current item and database of current item. And queryable is a collection of index results.

Till yet we haven’t applied any type of filtering it is just to get the indexed items from the indexes which is created by Solr or Lucene.

Now to apply filters define a predicate builder as given below –

      var predicate = PredicateBuilder.True<SearchResultItem>();

  1. Get items for specific template type  –
    predicate = predicate.And<SearchResultItem>(i => i.TemplateId == [Template ID]);
  2. Get items under specific node or Items from specific location in Sitecore –
    predicate = predicate.And<SearchResultItem>(i => i.Paths.Contains([Location Item ID]));
  3. Get items for context language only  –
    predicate = predicate.And<SearchResultItem>(item => item.Language == Context.Language.Name);
  4. Get items which contains specific Keyword –
    predicate = predicate.And<SearchResultItem>(i => i.Content.Contains(Keyword));

Now once you applied all the conditions or created all the predicates then you just need to pass it into linq  –

var results= queryable .Where(builder).Select(i => (Item)i.GetItem());

it will give you the list of filtered items as per your filtering conditions.

I hope this post will be helpful to start with search and filtering in next post we will discuss about Indexing custom fields and search on specific field values.

 

 

 

Posted in Sitecore, Sitecore Search | Tagged | Leave a comment

Increase Limit of items in Multi-list field of Sitecore

After A long time I am back to write something here for Sitecore Community. I didn’t stop sharing good things but I change the place for sometime and I was writing good blog posts http://www.nttdatasitecore.com/blog you can read it may be helpful.

Today I am writing about a small condition or setting which I recently came across, Increase the limit of items in Multilist field.

How about we came to address this point. We have created 200+ items under single node and on another item we created a Multilist field. Now we need to assign the datasource of this multilist field to show all the 200+ items which we have created earlier.

We started with basic approach to assign the datasource by Sitecore query. And here we came to know that only few items are showing in Multilist for selection not all. From here we started thinking what could be the reason for same and as we know if we are using Sitecore query so there is a limit setting defined in sitecore.config to control the no of items in query as given below.

<setting name=”Query.MaxItems” value=”100″ />

We increased the item limit from 100 to 1000 and after making this changes we are able to see all the items for selection in Mulitlist field.

Sometime a small setting can save your lots of time.

Happy Coding!!

 

 

 

Posted in Sitecore, Sitecore DMS | Leave a comment

Custom Field Type For Sitecore Web Form For Marketers

I have seen many questions about adding custom field in WFFM and adding session or querystring values in WFFM form field on form load.

I also got a same request to add querystring value in form field on load. WFFM module doesn’t provide any out of the box functionality to add session or querysting value in form field.

So finally I decided to create Custom Field in WFFM and add querystring value in that field. I started digging into Sitecore.Forms.Custom.dll and found code for SingleLineText field.

I created a custom field item with name CustomSingleLineText under /sitecore/system/Modules/Web Forms for Marketers/Settings/Field Types/Custom folder inside Sitecore and created a class in my class library project.

I extended code of SingleLineText field class from Sitecore.Forms.Custom.dll and added logic to show Session or Querystring value in text field on form load, see below code.

using Sitecore.Form.Core.Attributes;
using Sitecore.Form.Core.Visual;
using Sitecore.Form.Web.UI.Controls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Demo.Halper
{
     [Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))]
     public class CustomSingleLineText : RegexInputControl
     {
         private static readonly string baseCssClassName = "scfSingleLineTextBorder";
        [VisualCategory("Validation"), VisualProperty("Maximum Length:", 2000), DefaultValue(256)]
        public int MaxLength
        {
            get
            {
               return this.textbox.MaxLength;
            }
            set
            {
               this.textbox.MaxLength = value;
            }
         }
         [VisualCategory("Validation"), VisualProperty("Minimum Length:", 1000), DefaultValue(0)]
         public int MinLength
         {
            get;
            set;
         }
         [VisualFieldType(typeof(CssClassField)), VisualProperty("Css Class:", 600), DefaultValue("scfSingleLineTextBorder")]
         public new string CssClass
         {
            get
            {
                return base.CssClass;
            }
            set
            {
                base.CssClass = value;
            }
         }
         public CustomSingleLineText(HtmlTextWriterTag tag)
         : base(tag)
         {
             this.MaxLength = 256;
             this.MinLength = 0;
             this.CssClass = CustomSingleLineText.baseCssClassName;
          }
          public CustomSingleLineText()
          : this(HtmlTextWriterTag.Div)
          {
          }
          protected override void OnInit(EventArgs e)
          {
              this.textbox.CssClass = "scfSingleLineTextBox";
              this.help.CssClass = "scfSingleLineTextUsefulInfo";
              this.generalPanel.CssClass = "scfSingleLineGeneralPanel";
              this.title.CssClass = "scfSingleLineTextLabel";
              this.textbox.TextMode = TextBoxMode.SingleLine;
              this.Controls.AddAt(0, this.generalPanel);
              this.Controls.AddAt(0, this.title);
              this.generalPanel.Controls.AddAt(0, this.help);
              this.generalPanel.Controls.AddAt(0, this.textbox);
              // Please add your login for session or querysting value
              this.textbox.Text = "Add your session or querystring value";
          }
     }
}

After created class and added custom logic I have added values in Assembly and Class fields on CustomSingleLineText field item in Sitecore. To show Querysting value on form field I used custom field instead of default Single Line Text field.

Happy Coding 🙂

Posted in Sitecore, Sitecore web form for marketers | Tagged , , , , , , , , , , | 1 Comment

2014 in review

The WordPress.com stats helper monkeys prepared a 2014 annual report for this blog.

Here’s an excerpt:

A San Francisco cable car holds 60 people. This blog was viewed about 2,600 times in 2014. If it were a cable car, it would take about 43 trips to carry that many people.

Click here to see the complete report.

Posted in Uncategorized | Leave a comment

Install and configure Sitecore DMS

Here are some basic steps to install/configure DMS (with SQL server).

  1. Download DMS zip-archive for SQL Server from the CMS and DMS Downloads page.
  2. Unzip this file and we will see analytics database and few config files.
  3. We need to attach this analytics database to our SQL server.
  4. Now add analytics database’s connection in ConnectionString.config file as shown below.
    <add name=”analytics” connectionString=”user id={username};password={password};Data Source={server};Database={Database_Name}” />
  5. Copy all config files (Sitecore.Analytics.config, Sitecore.Analytics.ExlcudeRobots.config) to the /App_Config/Include/ folder. In case of Sitecore 7.2 also copy the Sitecore.Analytics.RobotDetection.config file to the/App_Config/Include/ folder.

These are the basic steps to configure DMS in Sitecore site. You can find more information here

In next blog I will show how we can view analytics reports.

Posted in Sitecore, Sitecore DMS | Tagged , , , , , , , , | Leave a comment