Skip to content

Commit 40307d1

Browse files
authored
Merge pull request #6523 from MrEssCee/patch-5
Create update-cart
2 parents cad4886 + cd19775 commit 40307d1

File tree

1 file changed

+218
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)