Skip to content

Commit e20da06

Browse files
authored
Corrected grammar and added more context
1 parent aeca817 commit e20da06

File tree

1 file changed

+90
-73
lines changed
  • 13/umbraco-commerce/how-to-guides

1 file changed

+90
-73
lines changed

13/umbraco-commerce/how-to-guides/add-item

Lines changed: 90 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,15 @@
22
description: How-To Guide to add an item to your cart.
33
---
44

5-
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.
5+
# Add item to Cart
66

7-
## Add a product to the Cart
8-
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.
7+
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).
98

10-
Create a new Document Type with template, we will call it Product Page with these properties aliases: `productTitle`, `productDescription`, `price`, `stock`.
9+
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.
1110

12-
The Product Page template can be implemented like the below code.
11+
Create a new Document Type with the template. Call it **Product Page** with the following property aliases: `productTitle`, `productDescription`, `price`, `stock`.
12+
13+
The Product Page template can be implemented as shown below.
1314

1415
```csharp
1516
@inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage<ProductPage>
@@ -20,12 +21,14 @@ var price = product.TryCalculatePrice().ResultOrThrow("Unable to calculate produ
2021
}
2122
```
2223

23-
- 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.
24-
- 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).
25-
- 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.
26-
- Finally we need to calculate the price which is then displayed without VAT (although can be also displayed with VAT)
24+
The code above does the following:
25+
26+
- 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.
27+
- 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.
28+
- 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.
29+
- Finally, you need to calculate the price which is then displayed without VAT. This can also be displayed with VAT.
2730

28-
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
31+
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:
2932

3033
```csharp
3134
@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
4851
}
4952
```
5053

51-
The hidden field is using the productReference to be passed across to the Controller.
54+
The hidden field uses the `productReference` to be passed across to the Controller.
5255

5356
## Adding the Controller
5457

55-
Create a new Controller called CartSurfaceController.cs
58+
For the button to work, you need to implement a controller. An example of this is shown below.
59+
60+
Create a new Controller called `CartSurfaceController.cs`.
5661

5762
{% hint style="warning" %}
5863

5964
The namespaces used in this Controller are important and need to be included.
6065

61-
using Microsoft.AspNetCore.Mvc;
62-
using Umbraco.Cms.Core.Cache;
63-
using Umbraco.Cms.Core.Logging;
64-
using Umbraco.Cms.Core.Models.PublishedContent;
65-
using Umbraco.Cms.Core.Routing;
66-
using Umbraco.Cms.Core.Services;
67-
using Umbraco.Cms.Core.Web;
68-
using Umbraco.Cms.Infrastructure.Persistence;
69-
using Umbraco.Cms.Web.Website.Controllers;
70-
using Umbraco.Commerce.Common.Validation;
71-
using Umbraco.Commerce.Core.Api;
72-
using Umbraco.Commerce.Core.Models;
73-
using Umbraco.Commerce.Extensions;
74-
using Umbraco.Extensions;
66+
```
67+
using Microsoft.AspNetCore.Mvc;
68+
using Umbraco.Cms.Core.Cache;
69+
using Umbraco.Cms.Core.Logging;
70+
using Umbraco.Cms.Core.Models.PublishedContent;
71+
using Umbraco.Cms.Core.Routing;
72+
using Umbraco.Cms.Core.Services;
73+
using Umbraco.Cms.Core.Web;
74+
using Umbraco.Cms.Infrastructure.Persistence;
75+
using Umbraco.Cms.Web.Website.Controllers;
76+
using Umbraco.Commerce.Common.Validation;
77+
using Umbraco.Commerce.Core.Api;
78+
using Umbraco.Commerce.Core.Models;
79+
using Umbraco.Commerce.Extensions;
80+
using Umbraco.Extensions;
81+
```
7582

7683
{% endhint %}
7784

7885
```csharp
7986
public class CartSurfaceController : SurfaceController
8087
{
81-
public CartSurfaceController(IUmbracoContextAccessor umbracoContextAccessor, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, IPublishedUrlProvider publishedUrlProvider, IUmbracoCommerceApi commerceApi) : base(umbracoContextAccessor, databaseFactory, services, appCaches, profilingLogger, publishedUrlProvider)
88+
public CartSurfaceController(IUmbracoContextAccessor umbracoContextAccessor,
89+
IUmbracoDatabaseFactory databaseFactory,
90+
ServiceContext services, AppCaches appCaches,
91+
IProfilingLogger profilingLogger,
92+
IPublishedUrlProvider publishedUrlProvider,
93+
IUmbracoCommerceApi commerceApi)
94+
: base(umbracoContextAccessor, databaseFactory, services, appCaches, profilingLogger, publishedUrlProvider)
8295
{
8396
_commerceApi = commerceApi;
8497
}
8598
}
8699
```
87100

88-
The equivalent code for having this as a Primary Constructor
101+
Below you can see the equivalent code for having this as a Primary Constructor:
89102

90103
```csharp
91-
public class CartSurfaceController(IUmbracoContextAccessor umbracoContextAccessor, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, IPublishedUrlProvider publishedUrlProvider) : SurfaceController(umbracoContextAccessor, databaseFactory, services, appCaches, profilingLogger, publishedUrlProvider)
104+
public class CartSurfaceController(IUmbracoContextAccessor umbracoContextAccessor,
105+
IUmbracoDatabaseFactory databaseFactory,
106+
ServiceContext services, AppCaches appCaches,
107+
IProfilingLogger profilingLogger,
108+
IPublishedUrlProvider publishedUrlProvider)
109+
: SurfaceController(umbracoContextAccessor, databaseFactory, services, appCaches, profilingLogger, publishedUrlProvider)
92110
{
93111
}
94112
```
95113

96-
97-
98-
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.
114+
The CartDto class below is used to pass the `productReference` across to the Controller. This class has only one property for the `productReference`.
99115

100116
```csharp
101117
public class CartDto
@@ -104,60 +120,61 @@ public class CartDto
104120
}
105121
```
106122

107-
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.
123+
We now need to add the Action to add the item to the cart. This action will be called when the button is clicked.
108124

109125
```csharp
110-
[HttpPost]
111-
public IActionResult AddToBasket(CartDto cart)
126+
[HttpPost]
127+
public IActionResult AddToBasket(CartDto cart)
128+
{
129+
commerceApi.Uow.Execute(uow =>
112130
{
113-
commerceApi.Uow.Execute(uow =>
131+
var store = CurrentPage.Value<StoreReadOnly>("store", fallback: Fallback.ToAncestors);
132+
133+
if (store == null) return;
134+
135+
try
114136
{
115-
var store = CurrentPage.Value<StoreReadOnly>("store", fallback: Fallback.ToAncestors);
116-
117-
if (store == null) return;
118-
119-
try
120-
{
121-
var order = commerceApi.GetOrCreateCurrentOrder(store.Id)
122-
.AsWritable(uow)
123-
.AddProduct(cart.ProductReference, 1);
124-
125-
commerceApi.SaveOrder(order);
126-
127-
uow.Complete();
128-
129-
TempData["SuccessFeedback"] = "Product added to cart";
130-
return RedirectToCurrentUmbracoPage();
131-
}
132-
catch (ValidationException ve)
133-
{
134-
throw new ValidationException(ve.Errors);
135-
}
136-
catch (Exception ex)
137-
{
138-
logger.Error(ex, "An error occurred.");
139-
}
140-
});
141-
}
137+
var order = commerceApi.GetOrCreateCurrentOrder(store.Id)
138+
.AsWritable(uow)
139+
.AddProduct(cart.ProductReference, 1);
140+
141+
commerceApi.SaveOrder(order);
142+
143+
uow.Complete();
142144

145+
TempData["SuccessFeedback"] = "Product added to cart";
146+
return RedirectToCurrentUmbracoPage();
147+
}
148+
catch (ValidationException ve)
149+
{
150+
throw new ValidationException(ve.Errors);
151+
}
152+
catch (Exception ex)
153+
{
154+
logger.Error(ex, "An error occurred.");
155+
}
156+
});
157+
}
143158
```
144159

145-
- store variable is used to access the store to get the store ID.
146-
- A try catch block is used to capture any errors that may occur when adding the item to the cart, including any validation errors.
147-
- 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.
148-
- AddProduct is called and the passed in productReference is passed across along with the quantity.
149-
- SaveOrder is called to save the order.
150-
- TempData is used to store a message to be displayed to the user if the product has been added to the cart.
160+
The code above does the following:
161+
162+
- The `store` variable is used to access the store to get the store ID.
163+
- A try-catch block captures any errors that may occur when adding the item to the cart, including any validation errors.
164+
- `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.
165+
- `AddProduct` is called and `productReference` is passed along with the quantity.
166+
- `SaveOrder` is called to save the order.
167+
- `TempData` stores a message to be displayed to the user if the product has been added to the cart.
151168

152169
{% hint style="warning" %}
153-
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.
170+
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.
154171
{% endhint %}
155172

156-
Finally, we need to add the TempData to display a message to the user that the product has been added to the cart.
173+
Finally, you need to add the `TempData` to tell the user that the product has been added to the cart.
157174

158175
## Add a partial view to display the message
159176

160-
Create a new partial view called Feedback.cshtml
177+
Create a new partial view called `Feedback.cshtml`.
161178

162179
```csharp
163180
@Html.ValidationSummary(true, "", new { @class = "danger" })
@@ -172,4 +189,4 @@ Create a new partial view called Feedback.cshtml
172189
}
173190
```
174191

175-
Run the application, click the button and the product will be added to the cart with a message displayed to the user.
192+
You can now run the application, click the button, and see the product added to the cart with a message displayed to the user.

0 commit comments

Comments
 (0)