Skip to content

Commit fa9c8d8

Browse files
Create update-cart
Tutorial for Umbraco 13 Commerce to update cart
1 parent 2986dc5 commit fa9c8d8

File tree

1 file changed

+203
-0
lines changed

1 file changed

+203
-0
lines changed
Lines changed: 203 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,203 @@
1+
---
2+
description: How-To update your cart.
3+
---
4+
5+
Once an item has been added to the cart you would most likely need the functionality to update the cart.
6+
7+
## Update shopping cart
8+
You will need a new page for the user to navigate to giving a summary of what's already in the cart and the ability to update each item.
9+
10+
Create a new View, we will call it `cart.cshtml` with the below code
11+
12+
```csharp
13+
@inherits UmbracoViewPage
14+
@{
15+
var store = Model.Value<StoreReadOnly>("store", fallback: Fallback.ToAncestors);
16+
var currentOrder = CommerceApi.Instance.GetCurrentOrder(store!.Id);
17+
if (currentOrder == null) return;
18+
}
19+
```
20+
21+
- You will need to access the store in order to have access to the relevant data for the current cart/order. The store has a `fallback` property allowing you to traverse up the tree to find the store.
22+
- `currentOrder` is used to get the current order for the store. If the current order is null then theres nothing to display.
23+
24+
To display the basic layout when an order does exist, we need to add some markup or at least amend it to include the desired functionality. In the same file add the below
25+
26+
```csharp
27+
@using (Html.BeginUmbracoForm("UpdateCart", "CartSurface"))
28+
{
29+
@foreach (var item in currentOrder.OrderLines.Select((ol, i) => new
30+
{
31+
OrderLine = ol,
32+
Index = i
33+
}))
34+
{
35+
<p>
36+
@Html.Hidden($"orderLines[{item.Index}].Id", item.OrderLine.Id)
37+
@item.OrderLine.Name @Html.Hidden($"orderLines[{item.Index}].Quantity", (int)item.OrderLine.Quantity, new { @type = "number" })
38+
@Html.Hidden($"orderLines[{item.Index}].ProductReference", item.OrderLine.ProductReference)
39+
<a href="@Url.SurfaceAction("RemoveFromBasket", "BasketSurface", new { OrderLineId = item.OrderLine.Id })">Remove</a>
40+
</p>
41+
42+
}
43+
44+
<button type="submit">Update Cart</button>
45+
46+
var success = TempData["SuccessMessage"]?.ToString();
47+
48+
if (!string.IsNullOrWhiteSpace(success))
49+
{
50+
<div class="success">@success</div>
51+
}
52+
}
53+
```
54+
55+
We first loop through each item in the `cart/order` and display the name of the product and the quantity. We also add a hidden input for the order id, quantity and product reference. This is so we can update the cart with the new quantity.
56+
57+
```csharp
58+
@Html.Hidden($"orderLines[{item.Index}].OrderId", item.OrderLine.Id)
59+
```
60+
61+
This is setting the Id of the order line (or the item in the current cart/order).
62+
63+
```csharp
64+
@item.OrderLine.Name @Html.Hidden($"orderLines[{item.Index}].Quantity", (int)item.OrderLine.Quantity, new { @type = "number" })
65+
```
66+
67+
As well as setting the name of the product, this is setting the quantity of the product in the cart/order. Finally the quantity is set to a number input type.
68+
69+
70+
```csharp
71+
@Html.Hidden($"orderLines[{item.Index}].ProductReference", item.OrderLine.ProductReference)
72+
```
73+
74+
This is setting the product reference of the product in the cart/order so there is a way to distinguish between products. This is hidden as it is not needed to be displayed to the user.
75+
76+
77+
{% hint style="warning" %}
78+
79+
The `remove` button is added here but is not covered in this guide. This will be covered in a separate guide.
80+
81+
{% endhint %}
82+
83+
Finally a button is added to submit the form to update the cart. This will call the `UpdateCart` action in the `CartSurfaceController` which will then show a success message to the user.
84+
85+
## Adding the Controller
86+
87+
Create a new Controller called `CartSurfaceController.cs`
88+
89+
{% hint style="warning" %}
90+
91+
The namespaces used in this Controller are important and need to be included.
92+
93+
using Microsoft.AspNetCore.Mvc;
94+
using Umbraco.Cms.Core.Cache;
95+
using Umbraco.Cms.Core.Logging;
96+
using Umbraco.Cms.Core.Models.PublishedContent;
97+
using Umbraco.Cms.Core.Routing;
98+
using Umbraco.Cms.Core.Services;
99+
using Umbraco.Cms.Core.Web;
100+
using Umbraco.Cms.Infrastructure.Persistence;
101+
using Umbraco.Cms.Web.Website.Controllers;
102+
using Umbraco.Commerce.Common.Validation;
103+
using Umbraco.Commerce.Core.Api;
104+
using Umbraco.Commerce.Core.Models;
105+
using Umbraco.Commerce.Extensions;
106+
using Umbraco.Extensions;
107+
108+
{% endhint %}
109+
110+
```csharp
111+
public class CartSurfaceController : SurfaceController
112+
{
113+
public CartSurfaceController(IUmbracoContextAccessor umbracoContextAccessor, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, IPublishedUrlProvider publishedUrlProvider, IUmbracoCommerceApi commerceApi) : base(umbracoContextAccessor, databaseFactory, services, appCaches, profilingLogger, publishedUrlProvider)
114+
{
115+
_commerceApi = commerceApi;
116+
}
117+
}
118+
```
119+
120+
The equivalent code for having this as a Primary Constructor
121+
122+
```csharp
123+
public class CartSurfaceController(IUmbracoContextAccessor umbracoContextAccessor, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, IPublishedUrlProvider publishedUrlProvider, IUmbracoCommerceApi commerceApi) : SurfaceController(umbracoContextAccessor, databaseFactory, services, appCaches, profilingLogger, publishedUrlProvider)
124+
{
125+
}
126+
```
127+
128+
129+
130+
The `CartDto` is a class that is used to pass data to the Controller. This is a simple class that has a property for the `productReference` and an array of `OrderLineQuantityDto[]`.
131+
132+
```csharp
133+
public class CartDto
134+
{
135+
public string ProductReference { get; set; }
136+
public OrderLineQuantityDto[] OrderLines { get; set; }
137+
}
138+
139+
public class OrderLineQuantityDto
140+
{
141+
public Guid Id { get; set; }
142+
public decimal Quantity { get; set; }
143+
}
144+
```
145+
146+
{% hint style="warning" %}
147+
`ProductReference` is not used here but a simple example of how you could pass the product reference to the controller for other similar related tasks.
148+
{% endhint %}
149+
150+
We now need to add the `Action` in order to update the items in the cart. This will be called when the button is clicked.
151+
152+
```csharp
153+
[HttpPost]
154+
public IActionResult UpdateCart(CartDto cart)
155+
{
156+
try
157+
{
158+
_commerceApi.Uow.Execute(uow =>
159+
{
160+
var store = CurrentPage?.Value<StoreReadOnly>("store", fallback: Fallback.ToAncestors);
161+
162+
if (store == null) return;
163+
164+
var order = _commerceApi.GetCurrentOrder(store.Id)
165+
.AsWritable(uow);
166+
167+
foreach (var orderLine in cart.OrderLines)
168+
{
169+
order.WithOrderLine(orderLine.Id)
170+
.SetQuantity(orderLine.Quantity);
171+
}
172+
173+
_commerceApi.SaveOrder(order);
174+
175+
uow.Complete();
176+
});
177+
}
178+
catch (ValidationException)
179+
{
180+
ModelState.AddModelError(string.Empty, "Failed to update cart");
181+
182+
return CurrentUmbracoPage();
183+
}
184+
185+
TempData["SuccessMessage"] = "Cart updated";
186+
187+
return RedirectToCurrentUmbracoPage();
188+
}
189+
```
190+
191+
- A `try catch` block is used to capture any validation errors that may occur when updating items in the cart.
192+
- `store` variable is used to access the store to retrieve the store ID.
193+
- `order` is used to retrieve the current order. In the Commerce Api everything is read-only for performance so we need to make it writable in order to add the product.
194+
- We loop through all the `orderLines(items)` in the cart and set the new quantity amount which was set in the View and passed into the CartDto model.
195+
- `SaveOrder` is called to save the order.
196+
- If there are any validation errors, they are added to ModelState error and the user is redirected back to the current page.
197+
- `TempData` is used to store a message to be displayed to the user if the product has been succesfully updated.
198+
199+
{% hint style="warning" %}
200+
Umbraco Commerce uses the Unit of Work pattern in order 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 then nothing is changed on the database.
201+
{% endhint %}
202+
203+
If you have followed the 'Add item to cart' article then run the application, add an item to your cart and navigate to your cart.cshtml page. Enter a new quantity click the Update Cart button and the item(s) in your cart would confirm the values have been updated with a success message.

0 commit comments

Comments
 (0)