Created
May 15, 2020 04:39
-
-
Save bomber-lomber/b4cb683620276f2b7f9f3bd5ca0e3577 to your computer and use it in GitHub Desktop.
CategoryFieldsRenderer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Dynamicweb.Ecommerce.Products; | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace Dynamicweb.Education.Ecommerce | |
{ | |
public class CategoryFieldsRenderer | |
{ | |
public string Render(IEnumerable<ProductInfo> products, string categoryId) | |
{ | |
var fields = GetCategoryFields(categoryId); | |
var result = "<table class=\"table\"><thead><tr>"; | |
foreach (var field in fields) | |
{ | |
result += $"<th>{field.Name}</th>"; | |
} | |
result += "</tr></thead>"; | |
result += "<tbody>"; | |
foreach(var productInfo in products) | |
{ | |
var product = Dynamicweb.Ecommerce.Services.Products.GetProductById(productInfo.ProductId, productInfo.VariantId, productInfo.LanguageId); | |
if (product == null) | |
{ | |
continue; | |
} | |
result += "<tr>"; | |
foreach (var field in fields) | |
{ | |
var propValue = Dynamicweb.Ecommerce.Services.Products.GetFieldValue(product, field); | |
result += $"<td>{(propValue.Succeeded && propValue.Data != null ? propValue.Data : string.Empty)}</td>"; | |
} | |
result += "</tr>"; | |
} | |
result += "</tbody></table>"; | |
return result; | |
} | |
private IEnumerable<ProductField> GetCategoryFields(string categoryId) | |
{ | |
var categoriesFieldsIdx = ProductField.GetCategoryFields().ToDictionary(f => f.SystemName); | |
var category = Dynamicweb.Ecommerce.Services.ProductCategories.GetCategoryById(categoryId); | |
if (category == null) | |
{ | |
throw new ArgumentException($"The category {categoryId} doesn't exist"); | |
} | |
var fields = category.Fields; | |
var result = new List<ProductField>(); | |
foreach(var field in fields) | |
{ | |
var sysName = $"ProductCategory|{field.Category.Id}|{field.Id}"; | |
ProductField prodField; | |
if (categoriesFieldsIdx.TryGetValue(sysName, out prodField)) | |
{ | |
result.Add(prodField); | |
} | |
} | |
return result; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Dynamicweb.Education.Ecommerce | |
{ | |
public class ProductInfo | |
{ | |
public string ProductId { get; set; } | |
public string LanguageId { get; set; } | |
public string VariantId { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment