Hi
I am using the new index for a product list (product catalog module). I would like to sort products according to the order set by the editor in the backend. I am using this code that should put the sorting order for products inside a product group into the index. But I can't make it work! The field "[product group id]_sorting" is not visible in the index when I look at it using LukeNet, and sorting on the field from the frontend does not have any effect. I have added the field as a parameter to the index but with no effect. What am I missing?
using Dynamicweb.Diagnostics.Tasks;
using Dynamicweb.eCommerce.Indexing;
using Dynamicweb.eCommerce.Products;
using Dynamicweb.Indexing;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
namespace NellemannSortingBuildExtender
{
public class SortingBuildExtender : IIndexBuilderExtender<ProductIndexBuilder>
{
private IList<string> _groupIdList = null;
private ProductGroupRelationCollection _relations = null;
public void ExtendDocument(IndexDocument doc)
{
// Verify group id list
if (_groupIdList == null)
LoadGroupIdList();
// Verify produt-group relations
if (_relations == null)
LoadRelations();
// Find product id from index document
string productId = doc["ProductID"].ToString();
// Find all relevant relations
var productRelations = _relations.Where(rel => rel.ProductID.Equals(productId, StringComparison.InvariantCultureIgnoreCase));
// Iterate through all groups ids
foreach (var groupId in _groupIdList)
{
// Find the associated relation for the group id
var relation = productRelations.FirstOrDefault(rel => rel.GroupID.Equals(groupId, StringComparison.InvariantCultureIgnoreCase));
// Fallback value if relation does not exist: sorting products to the bottom
int sorting = int.MaxValue;
if (relation != null)
{
// Relation exists: using sorting value from relation
sorting = relation.Sorting;
}
// Adding sorting field to index document
doc.Add(groupId + "_sorting", sorting);
}
}
private void LoadGroupIdList()
{
_groupIdList = new List<string>();
var connectionString = TaskManager.Context["Database.ConnectionString"].ToString();
using (var connection = new SqlConnection(connectionString))
{
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = "SELECT DISTINCT GroupID FROM EcomGroups";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var groupId = reader.GetString(0);
if (!string.IsNullOrEmpty(groupId))
_groupIdList.Add(groupId);
}
}
}
}
}
private void LoadRelations()
{
_relations = new ProductGroupRelationCollection();
var connectionString = TaskManager.Context["Database.ConnectionString"].ToString();
using (var connection = new SqlConnection(connectionString))
{
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = "SELECT * FROM EcomGroupProductRelation";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var relation = new ProductGroupRelation(reader);
_relations.Add(relation);
}
}
}
}
}
}
}