From 3ec8908073eeeb72668c8d8a65c6f49b7dd775f5 Mon Sep 17 00:00:00 2001 From: MrEssCee <67432920+MrEssCee@users.noreply.github.com> Date: Fri, 4 Oct 2024 18:24:11 +0100 Subject: [PATCH 01/15] Create add-item article Original article for adding an item to a cart when using Umbraco Commerce --- 13/umbraco-commerce/how-to-guides/add-item | 182 +++++++++++++++++++++ 1 file changed, 182 insertions(+) create mode 100644 13/umbraco-commerce/how-to-guides/add-item diff --git a/13/umbraco-commerce/how-to-guides/add-item b/13/umbraco-commerce/how-to-guides/add-item new file mode 100644 index 00000000000..6daab872f7e --- /dev/null +++ b/13/umbraco-commerce/how-to-guides/add-item @@ -0,0 +1,182 @@ +--- +description: How-To Guide to add an item to your cart. +--- + +To add an item to the cart, you first need to setup Umbraco with a store and add the relevant properties (i.e. Price and Stock see https://docs.umbraco.com/umbraco-commerce/10.commerce.latest/key-concepts/umbraco-properties) to allow the store to interact with Umbraco. + +## Add a product to the Cart +You will need the Frontend to be setup to add allow an item to be added to the cart. This can be done by adding a button to the frontend that will call the Action to add the item to the cart. + +Create a new View, we will call it product.cshtml with the below code + +```csharp +@{ +var store = Model.Value("store", fallback: Fallback.ToAncestors); +var product = CommerceApi.Instance.GetProduct(store.Id, Model.Key.ToString(), "en-GB"); +var price = product.TryCalculatePrice(); +} +``` + +- You will need to access the store so you have access to the relevant properties for your product such as price. The store has a fallback property allowing you to traverse up the tree to find the store. +- We retrieve the product based on the store and a reference for the product (the 'productReference' in this instance is coming from the Model which is a single product). +- The Product is returned as a ProductSnapshot which is Umbraco Commerce obtaining the page ID and carrying out necessary processes to bring in the data which it can use for further processing. +- Finally we need to calculate the price which is then displayed without VAT (although can be also displayed with VAT) + +To display this we need to add some markup or at least amend it to include a button to add an item. In the same file add the below + +```csharp +@using (Html.BeginUmbracoForm("AddToCart", "CartSurface")) +{ + @Html.Hidden("productReference", Model.Key.ToString()) +

@Model.ProductTitle

+

@Model.ProductDescription

+ +

Our price excluding VAT @price.Result?.WithoutTax.ToString("C0")

+ + if (@Model.Stock == 0) + { +

Sorry, out of stock

+ } + else + { + + } + + @await Html.PartialAsync("...../Feedback.cshtml") +} +``` + +The hidden field is using the productReference to be passed across to the Controller. + +{% hint style="warning" %} + +ModelsBuilder is used to access the properties of the page. +If you are not using ModelsBuilder then you will need to use the following code to access the properties + + Model.Value("nameOfProperty") + +{% endhint %} + +## Adding the Controller + +Create a new Controller called CartSurfaceController.cs + +{% hint style="warning" %} + +The namespaces used in this Controller are important and need to be included. + + using Microsoft.AspNetCore.Mvc; + using Umbraco.Cms.Core.Cache; + using Umbraco.Cms.Core.Logging; + using Umbraco.Cms.Core.Models.PublishedContent; + using Umbraco.Cms.Core.Routing; + using Umbraco.Cms.Core.Services; + using Umbraco.Cms.Core.Web; + using Umbraco.Cms.Infrastructure.Persistence; + using Umbraco.Cms.Web.Website.Controllers; + using Umbraco.Commerce.Common.Validation; + using Umbraco.Commerce.Core.Api; + using Umbraco.Commerce.Core.Models; + using Umbraco.Commerce.Extensions; + using Umbraco.Extensions; + +{% endhint %} + +```csharp +public class CartSurfaceController : SurfaceController +{ + public CartSurfaceController(IUmbracoContextAccessor umbracoContextAccessor, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, IPublishedUrlProvider publishedUrlProvider, IUmbracoCommerceApi commerceApi) : base(umbracoContextAccessor, databaseFactory, services, appCaches, profilingLogger, publishedUrlProvider) + { + _commerceApi = commerceApi; + } +} +``` + +The equivalent code for having this as a Primary Constructor + +```csharp +public class CartSurfaceController(IUmbracoContextAccessor umbracoContextAccessor, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, IPublishedUrlProvider publishedUrlProvider) : SurfaceController(umbracoContextAccessor, databaseFactory, services, appCaches, profilingLogger, publishedUrlProvider) +{ +} +``` + + + +The CartDto is a class that is used to pass the productReference across to the Controller. This is a simple class that has a property for the productReference. + +```csharp +public class CartDto +{ + public string ProductReference { get; set; } +} +``` + +We now need to add the Action in order to add the item to the cart. This will be called when the button is clicked. + +```csharp + [HttpPost] + public IActionResult AddToBasket(CartDto cart) + { + commerceApi.Uow.Execute(uow => + { + var store = CurrentPage.Value("store", fallback: Fallback.ToAncestors); + + if (store == null) return; + + try + { + var order = commerceApi.GetOrCreateCurrentOrder(store.Id) + .AsWritable(uow) + .AddProduct(cart.ProductReference, 1); + + commerceApi.SaveOrder(order); + + uow.Complete(); + + TempData["SuccessFeedback"] = "Product added to cart"; + return RedirectToCurrentUmbracoPage(); + } + catch (ValidationException ve) + { + throw new ValidationException(ve.Errors); + } + catch (Exception ex) + { + logger.Error(ex, "An error occurred."); + } + }); + } + +``` + +- store variable is used to access the store to get the store ID. +- A try catch block is used to capture any errors that may occur when adding the item to the cart, including any validation errors. +- order is used to retrieve the current order if one exists or create a new order against the store found. In the Commerce Api everything is read-only for performance so we need to make it writable in order to add the product. +- AddProduct is called and the passed in productReference is passed across along with the quantity. +- SaveOrder is called to save the order. +- TempData is used to store a message to be displayed to the user if the product has been added to the cart. + +{% hint style="warning" %} +Umbraco Commerce uses the Unit of Work pattern in order to complete saviing the item (uow.Complete). When retrieving or saving data ideally you would want the entire transaction to be committed however if there is an error then nothing is changed on the database. +{% endhint %} + +Finally, we need to add the TempData to display a message to the user that the product has been added to the cart. + +## Add a partial view to display the message + +Create a new partial view called Feedback.cshtml + +```csharp +@Html.ValidationSummary(true, "", new { @class = "danger" }) + +@{ + var success = TempData["SuccessFeedback"]?.ToString(); + + if (!string.IsNullOrWhiteSpace(success)) + { +
@success
+ } +} +``` + +Run the application, click the button and the product will be added to the cart with a message displayed to the user. From 43c323a2e99e97ee2077dc740771a164acd0ef7c Mon Sep 17 00:00:00 2001 From: MrEssCee <67432920+MrEssCee@users.noreply.github.com> Date: Tue, 8 Oct 2024 07:06:30 +0100 Subject: [PATCH 02/15] Update 13/umbraco-commerce/how-to-guides/add-item Co-authored-by: Dinh Tran --- 13/umbraco-commerce/how-to-guides/add-item | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/13/umbraco-commerce/how-to-guides/add-item b/13/umbraco-commerce/how-to-guides/add-item index 6daab872f7e..b052d665f34 100644 --- a/13/umbraco-commerce/how-to-guides/add-item +++ b/13/umbraco-commerce/how-to-guides/add-item @@ -7,7 +7,9 @@ To add an item to the cart, you first need to setup Umbraco with a store and add ## Add a product to the Cart You will need the Frontend to be setup to add allow an item to be added to the cart. This can be done by adding a button to the frontend that will call the Action to add the item to the cart. -Create a new View, we will call it product.cshtml with the below code +Create a new Document Type with template, we will call it Product Page with these properties aliases: `productTitle`, `productDescription`, `price`, `stock`. + +The Product Page template can be implemented like the below code. ```csharp @{ From db7a256c379fe9bee5c209fd99e0c252d0f66a5e Mon Sep 17 00:00:00 2001 From: MrEssCee <67432920+MrEssCee@users.noreply.github.com> Date: Tue, 8 Oct 2024 07:06:40 +0100 Subject: [PATCH 03/15] Update 13/umbraco-commerce/how-to-guides/add-item Co-authored-by: Dinh Tran --- 13/umbraco-commerce/how-to-guides/add-item | 1 - 1 file changed, 1 deletion(-) diff --git a/13/umbraco-commerce/how-to-guides/add-item b/13/umbraco-commerce/how-to-guides/add-item index b052d665f34..5601eafe3b2 100644 --- a/13/umbraco-commerce/how-to-guides/add-item +++ b/13/umbraco-commerce/how-to-guides/add-item @@ -44,7 +44,6 @@ To display this we need to add some markup or at least amend it to include a but } - @await Html.PartialAsync("...../Feedback.cshtml") } ``` From 2ca53815376eef872a8399ca1f573110ba467327 Mon Sep 17 00:00:00 2001 From: MrEssCee <67432920+MrEssCee@users.noreply.github.com> Date: Tue, 8 Oct 2024 07:06:49 +0100 Subject: [PATCH 04/15] Update 13/umbraco-commerce/how-to-guides/add-item Co-authored-by: Dinh Tran --- 13/umbraco-commerce/how-to-guides/add-item | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/13/umbraco-commerce/how-to-guides/add-item b/13/umbraco-commerce/how-to-guides/add-item index 5601eafe3b2..c1554a438ad 100644 --- a/13/umbraco-commerce/how-to-guides/add-item +++ b/13/umbraco-commerce/how-to-guides/add-item @@ -35,7 +35,7 @@ To display this we need to add some markup or at least amend it to include a but

Our price excluding VAT @price.Result?.WithoutTax.ToString("C0")

- if (@Model.Stock == 0) + if (@Model.Value("stock") == 0) {

Sorry, out of stock

} From dbe586a33442d08a2478b74ae163c27fec2409b3 Mon Sep 17 00:00:00 2001 From: MrEssCee <67432920+MrEssCee@users.noreply.github.com> Date: Tue, 8 Oct 2024 07:07:02 +0100 Subject: [PATCH 05/15] Update 13/umbraco-commerce/how-to-guides/add-item Co-authored-by: Dinh Tran --- 13/umbraco-commerce/how-to-guides/add-item | 1 + 1 file changed, 1 insertion(+) diff --git a/13/umbraco-commerce/how-to-guides/add-item b/13/umbraco-commerce/how-to-guides/add-item index c1554a438ad..fbc56bff05f 100644 --- a/13/umbraco-commerce/how-to-guides/add-item +++ b/13/umbraco-commerce/how-to-guides/add-item @@ -12,6 +12,7 @@ Create a new Document Type with template, we will call it Product Page with thes The Product Page template can be implemented like the below code. ```csharp +@inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage @{ var store = Model.Value("store", fallback: Fallback.ToAncestors); var product = CommerceApi.Instance.GetProduct(store.Id, Model.Key.ToString(), "en-GB"); From f575d893a639cc9d2cf4f0cc5126717309d4d3c6 Mon Sep 17 00:00:00 2001 From: MrEssCee <67432920+MrEssCee@users.noreply.github.com> Date: Tue, 8 Oct 2024 07:07:43 +0100 Subject: [PATCH 06/15] Update 13/umbraco-commerce/how-to-guides/add-item Co-authored-by: Dinh Tran --- 13/umbraco-commerce/how-to-guides/add-item | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/13/umbraco-commerce/how-to-guides/add-item b/13/umbraco-commerce/how-to-guides/add-item index fbc56bff05f..dbb036f6913 100644 --- a/13/umbraco-commerce/how-to-guides/add-item +++ b/13/umbraco-commerce/how-to-guides/add-item @@ -31,7 +31,7 @@ To display this we need to add some markup or at least amend it to include a but @using (Html.BeginUmbracoForm("AddToCart", "CartSurface")) { @Html.Hidden("productReference", Model.Key.ToString()) -

@Model.ProductTitle

+

@Model.Value("productTitle")

@Model.ProductDescription

Our price excluding VAT @price.Result?.WithoutTax.ToString("C0")

From 71e4a923f8ebc5822759f0e50e7ba3617cdf424a Mon Sep 17 00:00:00 2001 From: MrEssCee <67432920+MrEssCee@users.noreply.github.com> Date: Tue, 8 Oct 2024 07:07:56 +0100 Subject: [PATCH 07/15] Update 13/umbraco-commerce/how-to-guides/add-item Co-authored-by: Dinh Tran --- 13/umbraco-commerce/how-to-guides/add-item | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/13/umbraco-commerce/how-to-guides/add-item b/13/umbraco-commerce/how-to-guides/add-item index dbb036f6913..4f22f8cbca6 100644 --- a/13/umbraco-commerce/how-to-guides/add-item +++ b/13/umbraco-commerce/how-to-guides/add-item @@ -32,7 +32,7 @@ To display this we need to add some markup or at least amend it to include a but { @Html.Hidden("productReference", Model.Key.ToString())

@Model.Value("productTitle")

-

@Model.ProductDescription

+

@Model.Value("productDescription")

Our price excluding VAT @price.Result?.WithoutTax.ToString("C0")

From a9deb428733604caa6df7e3b3fb8bcd7bfc1c097 Mon Sep 17 00:00:00 2001 From: MrEssCee <67432920+MrEssCee@users.noreply.github.com> Date: Tue, 8 Oct 2024 07:08:06 +0100 Subject: [PATCH 08/15] Update 13/umbraco-commerce/how-to-guides/add-item Co-authored-by: Dinh Tran --- 13/umbraco-commerce/how-to-guides/add-item | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/13/umbraco-commerce/how-to-guides/add-item b/13/umbraco-commerce/how-to-guides/add-item index 4f22f8cbca6..7c76e291e45 100644 --- a/13/umbraco-commerce/how-to-guides/add-item +++ b/13/umbraco-commerce/how-to-guides/add-item @@ -16,7 +16,7 @@ The Product Page template can be implemented like the below code. @{ var store = Model.Value("store", fallback: Fallback.ToAncestors); var product = CommerceApi.Instance.GetProduct(store.Id, Model.Key.ToString(), "en-GB"); -var price = product.TryCalculatePrice(); +var price = product.TryCalculatePrice().ResultOrThrow("Unable to calculate product price"); } ``` From c13ad58db908d49dfa23f4cf168bbd1d13a48ca8 Mon Sep 17 00:00:00 2001 From: MrEssCee <67432920+MrEssCee@users.noreply.github.com> Date: Tue, 8 Oct 2024 07:08:26 +0100 Subject: [PATCH 09/15] Update 13/umbraco-commerce/how-to-guides/add-item Co-authored-by: Dinh Tran --- 13/umbraco-commerce/how-to-guides/add-item | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/13/umbraco-commerce/how-to-guides/add-item b/13/umbraco-commerce/how-to-guides/add-item index 7c76e291e45..0f6430c5611 100644 --- a/13/umbraco-commerce/how-to-guides/add-item +++ b/13/umbraco-commerce/how-to-guides/add-item @@ -34,7 +34,7 @@ To display this we need to add some markup or at least amend it to include a but

@Model.Value("productTitle")

@Model.Value("productDescription")

-

Our price excluding VAT @price.Result?.WithoutTax.ToString("C0")

+

Our price excluding VAT @price.WithoutTax.ToString("C0")

if (@Model.Value("stock") == 0) { From aeca817ee74c7dcbf530540a587ccec7bb969329 Mon Sep 17 00:00:00 2001 From: MrEssCee <67432920+MrEssCee@users.noreply.github.com> Date: Tue, 8 Oct 2024 07:12:35 +0100 Subject: [PATCH 10/15] Update add-item Hint removed --- 13/umbraco-commerce/how-to-guides/add-item | 9 --------- 1 file changed, 9 deletions(-) diff --git a/13/umbraco-commerce/how-to-guides/add-item b/13/umbraco-commerce/how-to-guides/add-item index 0f6430c5611..90af33fe2a0 100644 --- a/13/umbraco-commerce/how-to-guides/add-item +++ b/13/umbraco-commerce/how-to-guides/add-item @@ -50,15 +50,6 @@ To display this we need to add some markup or at least amend it to include a but The hidden field is using the productReference to be passed across to the Controller. -{% hint style="warning" %} - -ModelsBuilder is used to access the properties of the page. -If you are not using ModelsBuilder then you will need to use the following code to access the properties - - Model.Value("nameOfProperty") - -{% endhint %} - ## Adding the Controller Create a new Controller called CartSurfaceController.cs From e20da066f616c478c044c62439d0ffb3888a9e4e Mon Sep 17 00:00:00 2001 From: sofietoft Date: Tue, 8 Oct 2024 10:00:29 +0200 Subject: [PATCH 11/15] Corrected grammar and added more context --- 13/umbraco-commerce/how-to-guides/add-item | 163 ++++++++++++--------- 1 file changed, 90 insertions(+), 73 deletions(-) diff --git a/13/umbraco-commerce/how-to-guides/add-item b/13/umbraco-commerce/how-to-guides/add-item index 90af33fe2a0..7f3ea762c60 100644 --- a/13/umbraco-commerce/how-to-guides/add-item +++ b/13/umbraco-commerce/how-to-guides/add-item @@ -2,14 +2,15 @@ description: How-To Guide to add an item to your cart. --- -To add an item to the cart, you first need to setup Umbraco with a store and add the relevant properties (i.e. Price and Stock see https://docs.umbraco.com/umbraco-commerce/10.commerce.latest/key-concepts/umbraco-properties) to allow the store to interact with Umbraco. +# Add item to Cart -## Add a product to the Cart -You will need the Frontend to be setup to add allow an item to be added to the cart. This can be done by adding a button to the frontend that will call the Action to add the item to the cart. +To add an item to the cart, you need to set up Umbraco with a store and add the relevant properties to allow the store to interact with Umbraco. Learn more by following the [Getting started with Umbraco Commerce: The Backoffice tutorial](../tutorials/getting-started-with-commerce). -Create a new Document Type with template, we will call it Product Page with these properties aliases: `productTitle`, `productDescription`, `price`, `stock`. +You will need the front end to be set up to allow an item to be added to the cart. This can be done by adding a button to the front end to call the Action to add the item to the cart. -The Product Page template can be implemented like the below code. +Create a new Document Type with the template. Call it **Product Page** with the following property aliases: `productTitle`, `productDescription`, `price`, `stock`. + +The Product Page template can be implemented as shown below. ```csharp @inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage @@ -20,12 +21,14 @@ var price = product.TryCalculatePrice().ResultOrThrow("Unable to calculate produ } ``` -- You will need to access the store so you have access to the relevant properties for your product such as price. The store has a fallback property allowing you to traverse up the tree to find the store. -- We retrieve the product based on the store and a reference for the product (the 'productReference' in this instance is coming from the Model which is a single product). -- The Product is returned as a ProductSnapshot which is Umbraco Commerce obtaining the page ID and carrying out necessary processes to bring in the data which it can use for further processing. -- Finally we need to calculate the price which is then displayed without VAT (although can be also displayed with VAT) +The code above does the following: + +- You need to access the store to access the relevant properties for your product, such as price. The store has a fallback property allowing you to traverse the tree to find the store. +- You retrieve the product based on the store and a reference for the product. The 'productReference' comes from the Model which is a single product. +- The Product is returned as a ProductSnapshot which is Umbraco Commerce obtaining the page ID and carrying out necessary processes to bring in the data for further processing. +- Finally, you need to calculate the price which is then displayed without VAT. This can also be displayed with VAT. -To display this we need to add some markup or at least amend it to include a button to add an item. In the same file add the below +To display this you need to add some markup or at least amend it to include a button to add an item. Add the following to the same file: ```csharp @using (Html.BeginUmbracoForm("AddToCart", "CartSurface")) @@ -48,54 +51,67 @@ To display this we need to add some markup or at least amend it to include a but } ``` -The hidden field is using the productReference to be passed across to the Controller. +The hidden field uses the `productReference` to be passed across to the Controller. ## Adding the Controller -Create a new Controller called CartSurfaceController.cs +For the button to work, you need to implement a controller. An example of this is shown below. + +Create a new Controller called `CartSurfaceController.cs`. {% hint style="warning" %} The namespaces used in this Controller are important and need to be included. - using Microsoft.AspNetCore.Mvc; - using Umbraco.Cms.Core.Cache; - using Umbraco.Cms.Core.Logging; - using Umbraco.Cms.Core.Models.PublishedContent; - using Umbraco.Cms.Core.Routing; - using Umbraco.Cms.Core.Services; - using Umbraco.Cms.Core.Web; - using Umbraco.Cms.Infrastructure.Persistence; - using Umbraco.Cms.Web.Website.Controllers; - using Umbraco.Commerce.Common.Validation; - using Umbraco.Commerce.Core.Api; - using Umbraco.Commerce.Core.Models; - using Umbraco.Commerce.Extensions; - using Umbraco.Extensions; +``` +using Microsoft.AspNetCore.Mvc; +using Umbraco.Cms.Core.Cache; +using Umbraco.Cms.Core.Logging; +using Umbraco.Cms.Core.Models.PublishedContent; +using Umbraco.Cms.Core.Routing; +using Umbraco.Cms.Core.Services; +using Umbraco.Cms.Core.Web; +using Umbraco.Cms.Infrastructure.Persistence; +using Umbraco.Cms.Web.Website.Controllers; +using Umbraco.Commerce.Common.Validation; +using Umbraco.Commerce.Core.Api; +using Umbraco.Commerce.Core.Models; +using Umbraco.Commerce.Extensions; +using Umbraco.Extensions; +``` {% endhint %} ```csharp public class CartSurfaceController : SurfaceController { - public CartSurfaceController(IUmbracoContextAccessor umbracoContextAccessor, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, IPublishedUrlProvider publishedUrlProvider, IUmbracoCommerceApi commerceApi) : base(umbracoContextAccessor, databaseFactory, services, appCaches, profilingLogger, publishedUrlProvider) + public CartSurfaceController(IUmbracoContextAccessor umbracoContextAccessor, + IUmbracoDatabaseFactory databaseFactory, + ServiceContext services, AppCaches appCaches, + IProfilingLogger profilingLogger, + IPublishedUrlProvider publishedUrlProvider, + IUmbracoCommerceApi commerceApi) + : base(umbracoContextAccessor, databaseFactory, services, appCaches, profilingLogger, publishedUrlProvider) { _commerceApi = commerceApi; } } ``` -The equivalent code for having this as a Primary Constructor +Below you can see the equivalent code for having this as a Primary Constructor: ```csharp -public class CartSurfaceController(IUmbracoContextAccessor umbracoContextAccessor, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, IPublishedUrlProvider publishedUrlProvider) : SurfaceController(umbracoContextAccessor, databaseFactory, services, appCaches, profilingLogger, publishedUrlProvider) +public class CartSurfaceController(IUmbracoContextAccessor umbracoContextAccessor, + IUmbracoDatabaseFactory databaseFactory, + ServiceContext services, AppCaches appCaches, + IProfilingLogger profilingLogger, + IPublishedUrlProvider publishedUrlProvider) + : SurfaceController(umbracoContextAccessor, databaseFactory, services, appCaches, profilingLogger, publishedUrlProvider) { } ``` - - -The CartDto is a class that is used to pass the productReference across to the Controller. This is a simple class that has a property for the productReference. +The CartDto class below is used to pass the `productReference` across to the Controller. This class has only one property for the `productReference`. ```csharp public class CartDto @@ -104,60 +120,61 @@ public class CartDto } ``` -We now need to add the Action in order to add the item to the cart. This will be called when the button is clicked. +We now need to add the Action to add the item to the cart. This action will be called when the button is clicked. ```csharp - [HttpPost] - public IActionResult AddToBasket(CartDto cart) +[HttpPost] +public IActionResult AddToBasket(CartDto cart) +{ + commerceApi.Uow.Execute(uow => { - commerceApi.Uow.Execute(uow => + var store = CurrentPage.Value("store", fallback: Fallback.ToAncestors); + + if (store == null) return; + + try { - var store = CurrentPage.Value("store", fallback: Fallback.ToAncestors); - - if (store == null) return; - - try - { - var order = commerceApi.GetOrCreateCurrentOrder(store.Id) - .AsWritable(uow) - .AddProduct(cart.ProductReference, 1); - - commerceApi.SaveOrder(order); - - uow.Complete(); - - TempData["SuccessFeedback"] = "Product added to cart"; - return RedirectToCurrentUmbracoPage(); - } - catch (ValidationException ve) - { - throw new ValidationException(ve.Errors); - } - catch (Exception ex) - { - logger.Error(ex, "An error occurred."); - } - }); - } + var order = commerceApi.GetOrCreateCurrentOrder(store.Id) + .AsWritable(uow) + .AddProduct(cart.ProductReference, 1); + + commerceApi.SaveOrder(order); + + uow.Complete(); + TempData["SuccessFeedback"] = "Product added to cart"; + return RedirectToCurrentUmbracoPage(); + } + catch (ValidationException ve) + { + throw new ValidationException(ve.Errors); + } + catch (Exception ex) + { + logger.Error(ex, "An error occurred."); + } + }); +} ``` -- store variable is used to access the store to get the store ID. -- A try catch block is used to capture any errors that may occur when adding the item to the cart, including any validation errors. -- order is used to retrieve the current order if one exists or create a new order against the store found. In the Commerce Api everything is read-only for performance so we need to make it writable in order to add the product. -- AddProduct is called and the passed in productReference is passed across along with the quantity. -- SaveOrder is called to save the order. -- TempData is used to store a message to be displayed to the user if the product has been added to the cart. +The code above does the following: + +- The `store` variable is used to access the store to get the store ID. +- A try-catch block captures any errors that may occur when adding the item to the cart, including any validation errors. +- `order` is used to retrieve the current order if one exists or create a new order against the store found. In the Commerce API, everything is read-only for performance so you need to make it writable to add the product. +- `AddProduct` is called and `productReference` is passed along with the quantity. +- `SaveOrder` is called to save the order. +- `TempData` stores a message to be displayed to the user if the product has been added to the cart. {% hint style="warning" %} -Umbraco Commerce uses the Unit of Work pattern in order to complete saviing the item (uow.Complete). When retrieving or saving data ideally you would want the entire transaction to be committed however if there is an error then nothing is changed on the database. +Umbraco Commerce uses the Unit of Work pattern to complete saving the item (`uow.Complete`). When retrieving or saving data ideally you would want the entire transaction to be committed. However, if there is an error nothing is changed on the database. {% endhint %} -Finally, we need to add the TempData to display a message to the user that the product has been added to the cart. +Finally, you need to add the `TempData` to tell the user that the product has been added to the cart. ## Add a partial view to display the message -Create a new partial view called Feedback.cshtml +Create a new partial view called `Feedback.cshtml`. ```csharp @Html.ValidationSummary(true, "", new { @class = "danger" }) @@ -172,4 +189,4 @@ Create a new partial view called Feedback.cshtml } ``` -Run the application, click the button and the product will be added to the cart with a message displayed to the user. +You can now run the application, click the button, and see the product added to the cart with a message displayed to the user. From 440a328a264155455b5d3cb06991325a31e58fb2 Mon Sep 17 00:00:00 2001 From: MrEssCee <67432920+MrEssCee@users.noreply.github.com> Date: Tue, 8 Oct 2024 10:18:35 +0100 Subject: [PATCH 12/15] Update and rename add-item to add-item.md Added property editors --- .../how-to-guides/{add-item => add-item.md} | 7 +++++++ 1 file changed, 7 insertions(+) rename 13/umbraco-commerce/how-to-guides/{add-item => add-item.md} (97%) diff --git a/13/umbraco-commerce/how-to-guides/add-item b/13/umbraco-commerce/how-to-guides/add-item.md similarity index 97% rename from 13/umbraco-commerce/how-to-guides/add-item rename to 13/umbraco-commerce/how-to-guides/add-item.md index 7f3ea762c60..3d672c48f44 100644 --- a/13/umbraco-commerce/how-to-guides/add-item +++ b/13/umbraco-commerce/how-to-guides/add-item.md @@ -10,6 +10,13 @@ You will need the front end to be set up to allow an item to be added to the car Create a new Document Type with the template. Call it **Product Page** with the following property aliases: `productTitle`, `productDescription`, `price`, `stock`. +The following property editors are recommeded to be used for the above: + +`productTitle`: TextString +`productDescription`: TextArea +`price`: Umbraco Commerce Price +`stock`: Umbraco Commerce Stock + The Product Page template can be implemented as shown below. ```csharp From ed383f469be14165397cace0cbf133a04bf2ccef Mon Sep 17 00:00:00 2001 From: sofietoft Date: Tue, 8 Oct 2024 12:51:44 +0200 Subject: [PATCH 13/15] Fixed long sentence --- 13/umbraco-commerce/how-to-guides/add-item.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/13/umbraco-commerce/how-to-guides/add-item.md b/13/umbraco-commerce/how-to-guides/add-item.md index 3d672c48f44..cd74de7d3c4 100644 --- a/13/umbraco-commerce/how-to-guides/add-item.md +++ b/13/umbraco-commerce/how-to-guides/add-item.md @@ -4,7 +4,7 @@ description: How-To Guide to add an item to your cart. # Add item to Cart -To add an item to the cart, you need to set up Umbraco with a store and add the relevant properties to allow the store to interact with Umbraco. Learn more by following the [Getting started with Umbraco Commerce: The Backoffice tutorial](../tutorials/getting-started-with-commerce). +To add an item to the cart, configure Umbraco with a store and add the necessary properties for interaction. Learn more by following the [Getting started with Umbraco Commerce: The Backoffice tutorial](../tutorials/getting-started-with-commerce). You will need the front end to be set up to allow an item to be added to the cart. This can be done by adding a button to the front end to call the Action to add the item to the cart. @@ -12,10 +12,10 @@ Create a new Document Type with the template. Call it **Product Page** with the The following property editors are recommeded to be used for the above: -`productTitle`: TextString -`productDescription`: TextArea -`price`: Umbraco Commerce Price -`stock`: Umbraco Commerce Stock +* `productTitle`: TextString +* `productDescription`: TextArea +* `price`: Umbraco Commerce Price +* `stock`: Umbraco Commerce Stock The Product Page template can be implemented as shown below. From 70bfb75972c5e641ff1a2eadf391f338e6898333 Mon Sep 17 00:00:00 2001 From: sofietoft Date: Tue, 8 Oct 2024 13:07:07 +0200 Subject: [PATCH 14/15] Add article to SUMMARY.md --- 13/umbraco-commerce/SUMMARY.md | 1 + 1 file changed, 1 insertion(+) diff --git a/13/umbraco-commerce/SUMMARY.md b/13/umbraco-commerce/SUMMARY.md index 53e12ad73f9..348f89e4add 100644 --- a/13/umbraco-commerce/SUMMARY.md +++ b/13/umbraco-commerce/SUMMARY.md @@ -35,6 +35,7 @@ * [Configure SQLite support](how-to-guides/configure-sqlite-support.md) * [Limit Order Line Quantity](how-to-guides/limit-orderline-quantity.md) * [Use an Alternative Database for Umbraco Commerce Tables](how-to-guides/use-an-alternative-database-for-umbraco-commerce-tables.md) +* [Add item to Cart](how-to-guides/add-item.md) ## Key Concepts From 97436f6164be082780ffc788f26f8751e2c05167 Mon Sep 17 00:00:00 2001 From: MrEssCee <67432920+MrEssCee@users.noreply.github.com> Date: Tue, 8 Oct 2024 12:25:50 +0100 Subject: [PATCH 15/15] Update SUMMARY.md Updated Summary --- 13/umbraco-commerce/SUMMARY.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/13/umbraco-commerce/SUMMARY.md b/13/umbraco-commerce/SUMMARY.md index 348f89e4add..d6c20f351cc 100644 --- a/13/umbraco-commerce/SUMMARY.md +++ b/13/umbraco-commerce/SUMMARY.md @@ -36,6 +36,8 @@ * [Limit Order Line Quantity](how-to-guides/limit-orderline-quantity.md) * [Use an Alternative Database for Umbraco Commerce Tables](how-to-guides/use-an-alternative-database-for-umbraco-commerce-tables.md) * [Add item to Cart](how-to-guides/add-item.md) +* [Update Cart](how-to-guides/update-cart.md) +* [Delete item in Cart](how-to-guides/delete-item.md) ## Key Concepts