Skip to content

Custom Data

Trevor Fayas edited this page Aug 4, 2021 · 2 revisions

Often you will need to set custom data with your products, which can help determine things like product configuration, personalization, etc. There are multiple ways to configure, we'll go through them here.

Cart Item Custom Data

When adding an item to the cart, the Generic Ecommerce is equipped to take a key-value dictionary along with the basic cart item data (quantity / sku guid). It automatically adds these key-values to the CartItem's CustomData within Kentico. You can set these key-value pairs statically or dynamically:

Through Add to Cart View Component

You can add custom data through the the "Add to Cart" View Component by passing a Dictionary<string, object> in the CustomFields property:

@*This is an example that will add a sku with a custom field of a color to the cart.  In order to just use as normal, remove the CustomerFields property from the AddToCartViewModel.*@ 

@await Component.InvokeAsync("Generic.Ecom.AddToCart", new AddToCartViewModel() { Quantity = 1, SKUGUID = Model.Page.SKUProduct.SKUGUID, CustomFields = new Dictionary<string, object>() { { "color", "red" } } } )

Updating Values Dynamically

You can use JavaScript to update, add or remove any data-attributes. An example of a "Quantity" box next to an add to cart would look like this:

<input type="number" class="form-control" id="qty-2" min="1" onchange="this.parentElement.querySelector('.add-to-cart').dataset.quantity = this.value" value="1">

Adding custom form fields is also as easy as adjusting the add to cart's dataset.customFieldFieldNameHere = "value";

<input type="text" class="form-control product-personalization-line1" maxlength="8" required="" id="line12" placeholder="Line 1">
document.body.addEventListener("change", (ev) => {
        if (ev.target.classList.contains("product-personalization-line1")) {
            // Find the add to cart button associated with the personalize line
            var productItem = ev.target.closest(".product-item");
            var addToCart = productItem.querySelector(".add-to-cart");
            if (addToCart) {
                // Adds the Line1 data attribute which will save to the CartItemCustomData
                addToCart.dataset.customFieldLine1 = ev.target.value;
            }
        }

    });

ICartService.AddToCart

Another option available is to implement your own ICartService and add logic in your AddToCart(AddToCartViewModel cartViewModel) method. The cartViewModel contains the CustomParameters Dictionary<string, object> property which you can add your own logic to.

Clone this wiki locally