製品バリアントの製品属性の値を手動で設定するには、以下にあるヘルパーメソッドを使用できます。
NopSolutions.NopCommerce.BusinessLogic.Products.ProductManager
NopSolutions.NopCommerce.BusinessLogic.Products.Attributes.ProductAttributeManager
NopSolutions.NopCommerce.BusinessLogic.Products.Attributes.ProductAttributeHelper
NopSolutions.NopCommerce.BusinessLogic.Orders.ShoppingCartManager
(これは、プロジェクトが通常のnopCommerceサンプルサイトに基づいていることを前提としています。)
ただし、プロセスはかなり簡単です。nopCommerceカタログの商品属性はTextBoxタイプであると思います。これにより、任意の文字列を属性の値として設定できます。
プロセスの概要
- 製品バリアントを取得します。これは、製品IDと、必要な製品のバリアント(複数ある場合)がすでにわかっていることを前提としています。
- バリアントの属性を取得します。
- ProductAttributeHelperを使用して、属性XML文字列を生成します
- これらの属性を使用して商品をカートに保存します。
サンプルコード
private bool SaveProductToBasket()
{
var product = GetTheProduct();
int productId = product.ProductId;
var variants = ProductManager.GetProductVariantsByProductId(productId);
int variantId = GetDesiredVariantId();
var variant = variants[variantId];
var attributes =
ProductAttributeManager.GetProductVariantAttributesByProductVariantId(variant.ProductVariantId);
string data = string.Empty;
data = SetVariantAttribute(data, attributes, "Attribute1", value1.ToString());
data = SetVariantAttribute(data, attributes, "Attribute2", value2.ToString());
data = SetVariantAttribute(data, attributes, "Attributee", value3.ToString());
var addToCartWarnings =
ShoppingCartManager.AddToCart(ShoppingCartTypeEnum.ShoppingCart, variant.ProductVariantId, data, decimal.Zero, 1);
if (addToCartWarnings.Count == 0)
{
return true;
}
// TODO: Bind warnings.
return false;
}
private string SetVariantAttribute(string data, ProductVariantAttributeCollection attributes, string attributeName, string value)
{
var attribute = (from a in attributes
where a.ProductAttribute.Name == attributeName
select a).First();
return ProductAttributeHelper.AddProductAttribute(data, attribute, value);
}