• No results found

7 The Shopping Cart Module

N/A
N/A
Protected

Academic year: 2021

Share "7 The Shopping Cart Module"

Copied!
32
0
0

Loading.... (view fulltext now)

Full text

(1)

In the preceding chapters you’ve learned how to set up the Dynamicweb Product Catalog module, which is a core part of any Dynamicweb eCommerce site. If your site’s goal is to present a read-only product catalog, this is all you need to get started.

However, for the majority of eCommerce web sites, you want to enable your customers actually to order (and pay for) your products. Dynamicweb eCommerce 8 comes with the Shopping Cart module, which is designed specifically to handle the ordering process. In this chapter, you’ll get a good look at this module and its capabilities. In particular, this chapter looks at the following topics:

● An overview of the Shopping Cart Module and its capabilities

● Ways to define your own Order Steps to change the user’s flow through the ordering process

● How to create and configure validation rules to enforce validity of the user’s data ● How to configure shipping providers

● The different options you have available to send out order notification e-mails ● How to enable Step Validation to prevent users from messing with their orders. Closely related to the Shopping Cart module are Payment methods, the eCommerce Orders list in the backend, and the Customer Center module. These are discussed in Chapters 8, 10 and 11 respectively.

7.1 Introducing the Shopping Cart Module

The Shopping Cart module is the main entry point for the ordering process. By adding it to a paragraph on a page in the frontend, a customer can:

● Add selected products to the cart

● Complete the checkout process by entering customer details (name, address data, and so on), select payment and shipping providers, and view an order confirmation. ● Receive an order confirmation by e-mail.

In addition, the module can interact with the configured payment gateway to exchange details about the order and the payment the user makes. The result of the transaction made at the payment gateway then becomes available to the order in the backend.

(2)

Page 2 of 32

Dynamicweb also ships with the cart’s predecessor, simply referred to as the Shopping Cart module in the list of modules. To distinguish between the old and the new module, the newer version is called Shopping Cart v2. The new version offers a lot more functionality, including the ability to freely define your own steps of the checkout process. I won’t discuss the earlier version of the cart module in this book, but you can learn more about it in the Dynamicweb documentation portal at:

http://manual.dynamicweb-cms.com/Dynamicweb-eCommerce/Modules/Shopping-Cart.aspx

Wherever in the book you see a reference to the Shopping Cart module, I am referring to the newer, v2 module.

The next sections focus on what a cart is, and how to add the Shopping Cart module to a page and configuring its basic settings. Later sections dig deeper into the more advanced options, such as order steps and validation rules.

7.1.1 Understanding the Cart

The Shopping Cart, or Cart, is the central entity that keeps track of a customer and the products that the customer is ordering. Under the hood, the Cart is really an Order (both from an API as well as from a database point of view) but has some special flags set that mark it as a cart rather than an order. The Cart is stored in ASP.NET Session state as well as in the database and keeps track of customer and order information, including (but not limited to) the following:

● Customer data (such as name, address, contact information)

● Order lines (the products the user has added to the cart, both normal products as well as BOM (Bill of Material) products)

● Discount data (sales discounts that are applicable to the order) ● Information about the selected shipping and payment providers

● Details of the transaction between the eCommerce web site and the payment provider

Since the cart is always readily available, it’s easy to make updates to it (by adding products to it using links for example) and to display its contents (as a quick summary on each page, or with a lot more detail on the pages that deal with the checkout process for example). I’ll show you how to add products to the cart after I’ve discussed how to add the cart module to the page and configure it. Later in this chapter you see how to output the contents of the cart on pages in your site.

7.1.2 Configuring the Shopping Cart Module

When you add the Shopping Cart module to a paragraph, there are a number of items you can configure. In Figure 7-1 you see the module’s configuration page:

(3)

Page 3 of 32

(4)

Page 4 of 32

This screen enables you to configure the following options: Configuration option Description

Shop Here you can choose the shop where your orders go to. If you don’t choose a shop here, the orders go to the shop marked as the Default shop in the management center. For clarity, you should always explicitly select a shop here.

Steps Here you can configure existing, and add new steps to the order process. Order steps are discussed later in this chapter.

Notification e-mails This option enables you to configure e-mail notifications that can be sent to customers and site administrators. E-mail notifications are discussed later in this chapter.

Field validation Here you configure the validation rules that are applied to the order. You can force the user to agree to the terms and conditions and assign one or more custom validation groups. Order validation rules are discussed later in this chapter.

Newsletter The newsletter configuration option will only show when the Newsletter v3 module is installed. This option enables you to select one or more Newsletter categories the user can be assigned to when completing an order. To add a new category, click the Add button and select the Newsletter category from the list. Users can choose if they want to sign up for the newsletters or not through a checkbox in the order process, but they can’t choose which newsletters to subscribe to. If you need to implement this, you should create a separate page or order step that lets users choose from different newsletter categories using the Newsletter module.

Empty cart This option controls what users see when they visit the Cart page while their cart is empty. You have three options:

Redirect to an internal page – When you select this option, you can choose another Dynamicweb page that the user is redirected to instead of the Cart page. For example, you could redirect the user to a promotional page, or to a specialized search page that helps them choose from your products.

Show template – With this option you can select a custom

template that is shown instead of the cart. Inside this template you can add any HTML you see fit, such as some content that

explains that the cart is empty and helps them find products. ● Take no special action – If you select this option, Dynamicweb

takes no special action and simply renders the first step of the order process. Inside the template for this step you can test the Ecom:Order.IsEmpty tag and display a message when the cart is empty, as shown in the following example:

<!--@If Defined(Ecom:Order.IsEmpty)--> Your cart is empty.

<!--@EndIf(Ecom:Order.IsEmpty)-->

When re-entering the cart

Determines whether the user is taken to the first step of the checkout process or to the last step they visited when they request the cart page again after having visited another page.

(5)

Page 5 of 32 Country for shipping

method

Country for payment method

Enables you to choose which country is used to determine the available shipping and payment methods and their fees. The third option uses the delivery country if it has been set explicitly, and falls back to the

customer country (e.g. the billing address).

Unavailable products If you set this option to Remove, products are removed from the cart if they have become unavailable since they were added to the cart. This can happen when you deactivate products or they run out of stock. The products are removed from the cart without a notification to the user, which may cause some confusion for them.

If you look closely at Figure 7-1, you may have noticed the absence of options to choose templates, which are so common for many other Dynamicweb modules. The reason for this is that the templates are configurable for each step under the Steps heading, which you’ll learn more about in a bit.

In the next walkthrough you’ll see how to add the Shopping Cart module to a page, configure its settings and then use it at the frontend. Later walkthroughs in this chapter then build on this example by changing the behavior of the cart, such as defining your own order steps and custom validation rules.

Walkthrough – Using the Shopping Cart Module

1. Log in to your Dynamicweb site and, using the Navigation Pane, create a new page called Cart. Add a paragraph to the page, call it Cart as well, and then insert the Shopping Cart v2 module. You should see the screen shown in Figure 7-1. Remember: The module is called Shopping Cart v2 (eCom) on the module list when you add the module to a paragraph. As explained earlier, in the remainder of this chapter, I’ll simply refer to it as the Shopping Cart module.

2. Leave all settings at their default and save the paragraph.

3. Go into the Management Center and expand the path eCommerce | Orders | Payment. Delete any existing Payment methods that are defined. Then create a new payment method called Buy on account with its Cart type set to None. Make sure you make the payment method available in all countries by checking off all checkboxes on the

Country fees tab. Refer to the section 2.3 Configuring a Payment Method if you need more information on creating a payment method. You can also refer to the next chapter, where payment methods are discussed in more detail. Save the payment method. 5. Open the site in your browser by clicking Open website on the main toolbar and browse

to one of the pages with the Product Catalog module on it that you created earlier. Add one or more products to the cart and then request the Cart page you created in step 1 of this walkthrough. You should see an overview of the products you ordered.

6. Click Next to proceed to the user data step. On that screen, leave all fields empty and click the Create order button. Notice how the page refreshes and shows you an error message that tells you to tick the checkbox for the terms and conditions. The reason you get this error message is that the associated option in the Shopping Cart module is checked by default.

(6)

Page 6 of 32

7. Place a checkmark in the Terms and Conditions checkbox and click Create order again. You should now receive a confirmation telling you that your order was created successfully.

You can now see the order in the backend. To view it, log back in to Dynamicweb and click the eCommerce button. Your order should be listed in the orders screen.

The steps you followed in the preceding walkthrough have a few flaws. Firstly, you may not want to follow the path of showing the cart, showing the user details and then showing the order confirmation. You may want to display an intermediate page where users can select a different payment method, or shipping provider, for example. Secondly, you need a way to force the user to enter some required details, such as a name, address and a valid e-mail address. I’ll address the first concern in the next section, while the second issue is addressed in detail in a later section called “Validation User Input”.

7.1.3 Working with Order Steps

As you saw in the preceding section, the Shopping Cart module lets you define one or more steps as part of the checkout process. You can think of steps as being a virtual breakdown of the information that the user needs to supply during the checkout process. Each step then collects part of the information that is needed to complete the checkout, such as the user’s details, the preferred payment method and so on. You need to implement at least the Checkout step, but all other steps are optional. The concept of steps gives you great flexibility in terms of the way you collect the user data. You could have all the data on a single page (using the required Checkout step), or you could spread it over multiple pages, where each page collects specific information, such as address details, gift wrapping options and so on. You will see more of customizing steps later.

By default, the steps are set up as follows:

Figure 7-2

This is a common setup, which will handle most of the cases. As you saw in the previous walkthrough, these order steps first present an overview of the cart. If you then click next, the user is asked for its details, such as name and addresses. In addition, this step enables the user to select a payment method and shipping provider, if available. The checkout step then behaves differently based on the selected payment method. With the “No pay” method you configured in Chapter 2, this step is visually skipped and takes the user directly to the receipt page. Under the hood the step still fires code to mark the order as paid in the database and execute optional extensibility code. But if you’ve chosen an external payment method, the user is typically redirected away from the main

(7)

Page 7 of 32

shop web site to the payment gateway’s website, where they can enter their payment details such as a bank account or credit card data. When the payment succeeds, the user is taken to the final step – Receipt – where an overview of the order is shown. If the payment doesn’t succeed, or the payment is cancelled, the user is taken back to a specific page on the site. You typically configure the URL for this page in your payment gateway’s administrative interface. Refer to their documentation for more details. 7.1.3.1 Configuring Order Steps

Most of the steps enable you to configure a template. For example, if you click the first icon (labeled Edit) next to the Show Cart step you’ll see the following popup:

Figure 7-3

The Name you enter here is used to identify the step in the list of steps.

The Template selector works just as any other Dynamicweb template selector. You can choose a different one from the drop-down list, click the Edit icon to edit the template’s underlying HTML and click the Translate icon to translate keys found in the template. In addition to changing the name and templates for the steps, you can also reorder them. To do this, just drag a step and drop it in the desired location. While you’re technically free to drag them in any order you see fit, you need to consider the steps’ order carefully. There’s not much point in showing the receipt before you’ve completed the payment.

You can also add new steps by clicking the Add step link. You’ll see how to make use of this in the next walkthrough.

Walkthrough – Adding Order Steps

If you’ve configured a number of payment methods (for example to let the user choose between credit card, bank account or PayPal), you may not want to display the various available methods on the user details page, as it might create clutter. In this scenario, you can add an additional step between Information and Checkout that enables the user to choose a payment method. In this walkthrough you’ll see how to add that additional step to the steps list and configure it appropriately.

1. Start by creating a copy of the file

/Templates/eCom7/CartV2/Step/Information.html and call the file

Options.html. You can do this using the Windows File Explorer or the Dynamicweb File Manager.

(8)

Page 8 of 32

2. Open up the new file you just created (again, you can do this using Dynamicweb’s File Manager or Visual Studio) and remove the <fieldset> elements for the billing (<fieldset id="billing">) and shipping address (<fieldset

id="delivery">), the newsletter (<fieldset id="newsletter">) and the terms and conditions (<fieldset id="conditions">). You should end up with a template file that contains a <form> element, which in turn contains the payment and shipping options (<fieldset id="paymentanddelivery">) and a number of buttons at the bottom to navigate from step to step. Locate and remove the four calls to the

updateCart JavaScript method on the radio buttons. You can remove the entire

onclick handler (onclick="updateCart();"). Save the template.

3. Open up Information.html and remove the <fieldset> for the payment and delivery options (<fieldset id="paymentanddelivery">). Save the template. 4. Next, open the Cart page you created earlier in the backend of Dynamicweb. Open the

paragraph with the Shopping Cart module on it and then open its configuration screen. 5. Below the list of steps click Add step. In the dialog that follows, enter Options as the

step name and choose Options.html as the template:

Figure 7-4

Click OK to apply the changes.

6. Drag the new order step from its location at the end of list, and drop it between the Information and Checkout steps:

Figure 7-5

7. Click Save and close to apply the changes.

8. Open up the frontend of your website in your browser, add a few products to your cart and proceed to the checkout by clicking the Cart menu item. On the cart overview page

(9)

Page 9 of 32

click Next. Notice how this page still asks you for your personal details but no longer lets you choose a payment method or shipping provider. Enter your details, agree to the terms and conditions and click Create order. Now you should see a screen that lets you select the payment method and shipping provider. Pick the Buy on account payment method from the list and click Create order again. Now the order is processed and marked as complete and you’ll see the receipt page appear.

Defining your own steps is pretty easy and gives you a great deal of flexibility in determining the path the user takes through your checkout procedure. You may have noticed that in the preceding exercise you ended up with a button called Create order in both the Information as well as in the Options step. This may not be exactly what you want. It may make more sense to change the button on the Information page to something like Select payment and delivery options. Fortunately, this is easily accomplished with Dynamicweb template tags, as you’ll see next.

7.1.3.2 Template Tags for the Shopping Cart

Since the Shopping Cart is a rich module, it should come as no surprise that it has a lot of template tags. In fact, it has way too many to list in this book. In this section I’ll describe just a few important ones that most of your eCommerce sites will need. If you want the full list of all available template tags, use DwTemplateTags or check out the documentation portal for the Shopping Cart module at http://templates.dynamicweb-cms.com/eCommerce/Dynamicweb-eCommerce-template-tags/Shopping-Cart-V2.aspx. If you open up the Information.html template again and look at the code, you’ll see a number of obvious tags, such as those starting with Ecom:Order.Customer, which contain the customer’s details. However, the Shopping Cart module has a lot more tags. For example, you have access to the selected payment method

(Ecom:Order.PaymentMethod) and shipping method

(Ecom:Order.ShippingMethod). You display the items in the cart (including any sales discounts) using the OrderLines loop. Inside the OrderLines loop you can then access information about the product (using tags that start with Ecom:Product), the order line (using tags that start with Ecom:Order:OrderLine) and a lot more. You will see an example of customizing the OrderLines loop in Chapter 9 where you use some code to display discounts in the cart differently from standard products.

Another useful tag is the MissingProducts loop which gives you a list of products that are no longer available in the cart. This loop contains items that were previously added to the cart but are now no longer available, for example because you’ve disabled the product in the backend or because they are no longer in stock. Another loop, called

ValidationErrors, is discussed in the next section.

In the template file Options.html you’ll also find a number of loops and inner tags to display and select the configured payment gateways and shipping providers.

At the bottom of the template file you’ll see two tags used for navigation. By default, the tags look like this:

<input type="submit" name="<!--@CartV2.PreviousStepButtonName-->" id="<!--@CartV2.PreviousStepButtonName-->" value="

<!--@Translate(back, "Back")-->" class="submitter" />

<input type="submit" name="<!--@CartV2.CurrentStepButtonName-->" id="<!--@CartV2.CurrentStepButtonName-->" value="

(10)

Page 10 of 32 <!--@Translate(update, "Update")-->" class="submitter" />

<input type="submit" name="<!--@CartV2.NextStepButtonName-->" id="<!--@CartV2.NextStepButtonName-->" value="

<!--@Translate(createorder, "Create Order")-->" class="submitter" />

In the Bikez demo, the text on the buttons is translated automatically using the

Translate tag. You learn more about this tag in Chapter 14.

This code renders a Previous, Current and Next button at the end of each step. For the first step in the list you should remove the Previous button, while you shouldn’t use any of these buttons in the final Receipt page. Notice how the template tags don’t define the actual button, but merely the action that should be carried out. This makes it easy to change the text for the buttons. For example, in Information.html you could change the Next button as follows:

<input type="submit" name="<!--@CartV2.NextStepButtonName-->" id="<!--@CartV2.NextStepButtonName-->"

value="Select payment and delivery options" class="submitter" />

This changes the button’s text in the Information step only.

In this section you learned about the Shopping Cart steps and how to add and customize them. Obviously, you also need a way to add products to the cart. Dynamicweb

supports a number of different ways to do this as you’ll see next.

7.2 Managing the Cart

In general, there are two main ways to add a product to the cart: using a direct link, and by submitting a form. The actual code you need to write varies slightly with the type of product you’re adding. Each of the different scenarios is discussed in this section. When adding (or otherwise modifying) products to the cart, you can make use of a special query string parameter called cartcmd. This parameter supports a number of different options, with the 6 most important ones listed in the following table:

Query String Value Description

Add Adds the requested product to the cart.

emptycart Empties the cart. If you want to show a specific page afterwards, you can create a link to that page with emptycart as the command, E.g.:

<a href="Default.aspx?ID=123&cartcmd=emptycart">

Dynamicweb will empty the cart and then show the requested page. addmulti Enables you to add multiple products at the same time.

IncOrderLine Increases the quantity of an item in the cart.

DecOrderLine Decreases the quantity of an item in the cart. When the quantity reaches zero, the item is removed from the cart.

DelOrderLine Removes an item from the cart.

(11)

Page 11 of 32

7.2.1 Adding Products from the List and Details Pages

From these pages you can create an Add to Cart link using code similar to this:

<a href ="/Default.aspx?id=<!--@Ecom:Product:Page.ID-->&amp;ProductID=<!--@Ecom:Product.ID-->&amp;cartcmd=add">Add to basket</a>

Here, the trigger for Dynamicweb is the inclusion of the cartcmd query string parameter set to add. You can also specify an initial quantity by adding a Quantity parameter like this:

<a href

="/Default.aspx?id=<!--@Ecom:Product:Page.ID-->&amp;ProductID=<!--@Ecom:Product.ID-->&amp;cartcmd=add&quantity=4">Add four products to the basket</a>

Besides a direct link you can also add a product to the cart using an HTML <form />

element. You need to set up a form that submits at least the selected product ID and a cart command. In addition, you can also set an initial quantity. The following example lets the user select a quantity before the item is added to the cart:

<form method="post">

<input type="hidden" name="CartCmd" value="add" />

<input type="hidden" name="ProductID" value="<!--@Ecom:Product.ID-->" /> <select name="quantity"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select>

<input id="Submit1" type="submit" value="Add to cart" /> </form>

Each of the three form fields (the two hidden fields and the drop-down list) map directly to the query string fields you saw earlier. When a user chooses a quantity from the list and clicks the button, the form is submitted to the server. Dynamicweb then recognizes the CartCmd field and adds the requested product (by looking at the ProductID field) with the requested quantity. If you leave out the quantity field, a single product is added to the cart. You can use the CartCmd field inside any post form as long as the form also contains information on the products you want to add.

Rather than manually setting up the CartCmd and product ID fields, you can also use the tags Ecom:Product.Form and Ecom:Product.Form.Clean. The first one renders a complete <form /> element, while the second one renders just the hidden fields needed to add products, variants and units to the cart. For example, the Clean

variant of this tag could render something like this:

<input type="hidden" name="ProductURL" id="ProductURL" value="" /> <input type="hidden" name="CartCmd" id="CartCmd" value="add" />

<input type="hidden" name="ProductID" id="ProductID" value="PROD15" /> <input type="hidden" name="VariantID" id="VariantID" value="" /> <input type="hidden" name="UnitID" id="UnitID" value="" />

You can use these <form /> techniques in product lists as well as in product details pages. You will see what the VariantID and UnitID fields are used for later.

(12)

Page 12 of 32

Using a form to add products to the cart can be useful if you want to provide the user with a richer interface to add a product. This makes it easier to add other form fields such as a drop-down list or a text box. And then you can also use JavaScript to do validation and submit the form if you wish.

Another common reason to use a form is when you need to add multiple products at once as you’ll see next.

7.2.2 Adding multiple products

To make it easier for your users to add a number of products to the cart at the same time, you can set up a form similar to the previous one, but with a slight twist. Instead of setting up the hidden ProductID field yourself or using the Product.Form tags, you use the Ecom:Product.Form.Multi.HiddenFields tag inside the Products loop. The following example loops over all the products and outputs hidden fields to register the products that need to be ordered. In addition, it renders a single text box that enables the user to enter a quantity for each product. You can of course hide this text box (so a single product is added), replace it with a hidden field (so you can control the initial quantity) or replace it with another control such as a drop-down list as you saw earlier.

<form name="multiForm" id="multiForm" method="post">

<input type="hidden" name="CartCmd" id="CartCmd" value="addMulti" /> <!--@LoopStart(Products)-->

<!--@Ecom:Product.Form.Multi.HiddenFields-->

<!--@Ecom:Product.Name--> Quantity: <input type="text"

name="Quantity<!--@Ecom:Product.LoopCounter-->" value="1" /><br /> <!--@LoopEnd(Products)-->

<input id="Submit1" type="submit" value="submit" /> </form>

The single Submit button near the end of the form and outside the Products loop adds all the products from the loop to the cart. This code outputs the following HTML:

<input type="hidden" name="ProductLoopCounter1" id="ProductLoopCounter1" value="1" /> <input type="hidden" name="ProductID1" id="ProductID1" value="PROD2" />

<input type="hidden" name="VariantID1" id="VariantID1" value="" /> <input type="hidden" name="UnitID1" id="UnitID1" value="" />

Product Name 1 Quantity: <input type="text" name="Quantity1" value="1" /><br /> <input type="hidden" name="ProductLoopCounter2" id="ProductLoopCounter2" value="2" /> <input type="hidden" name="ProductID2" id="ProductID2" value="PROD3" />

<input type="hidden" name="VariantID2" id="VariantID2" value="" /> <input type="hidden" name="UnitID2" id="UnitID2" value="" />

Product Name 2 Quantity: <input type="text" name="Quantity2" value="1" /><br />

7.2.3 Adding Variants

Adding variants is similar to adding standard products, except that you also need to pass in the ID of the variant. For links, you simply add the ID of the variant to the VariantID

query string parameter. For form based solutions, you can set up a hidden field called

VariantID, or rely on the Product.Form or

Product.Form.Multi.HiddenFields tags.

The following example shows how to add create links to add the available variants to the cart in a product’s details page:

(13)

Page 13 of 32 <!--@LoopStart(Products)--> <!--@LoopStart(VariantCombinations)--> <!--@If(Ecom:VariantCombination.Product.Active==True)--> <!--@Ecom:VariantCombination.Product.Name--> <!--@Ecom:VariantCombination.VariantText--> <a href="/Default.aspx?id=<!--@Global:Page.ID-->&amp;productid= <!--@Ecom:VariantCombination.Product.ID-->&amp;cartcmd=add&VariantUD= <!--@Ecom:VariantCombination.VariantID-->"> Add to basket</a><br /> <!--@EndIf--> <!--@LoopEnd(VariantCombinations)--> <!--@LoopEnd(Products)-->

Likewise, the following code can be used to add a variant to the cart using a form:

<!--@LoopStart(Products)-->

<!--@LoopStart(VariantCombinations)-->

<form name="multiForm" id="multiForm" method="post">

<input type="hidden" name="CartCmd" id="CartCmd" value="add" /> <input type="hidden" name="ProductID" id="ProductID"

value="<!--@Ecom:VariantCombination.Product.ID-->" /> <input type="hidden" name="VariantID" id="VariantID"

value="<!--@Ecom:VariantCombination.VariantID-->" /> <input id="Submit1" type="submit" value="Add

<!--@Ecom:VariantCombination.Product.Name--> <!--@Ecom:VariantCombination.VariantText-->" />

</form>

<!--@LoopEnd(VariantCombinations)--> <!--@LoopEnd(Products)-->

Note: In the code above you can also replace the CartCmd, ProductID, and VariantID hidden elements with the <!--@Ecom:Product.Form.Clean> template tag to get them rendered automatically.

You can use this code in product lists and details pages.

7.2.4 Adding BOM Products

When using BOM products, several products are added to the cart. So adding a BOM product that consists of a bike, a helmet, lights and glasses, will add 4 items to the cart. The products added are those configured on the product in the backend on the Parts Lists tab. To display the added products as sub items to the campaign product, use the

BOMItems loop as discussed in chapter 4.

Figure 7-6

If one of the items of the BOM product is a configurator where the user can choose from a list of different configuration options, a change to the product template is needed.

(14)

Page 14 of 32

In the product.html template, you find code like this to show a configurator in the frontend: <div id="includingproducts"> <!--@LoopStart(BOMProducts)--> <!--@HeaderStart--> <h2>Including products</h2> <ul> <!--@HeaderEnd--> <li class="listitem<!--@BOMProducts.LoopMod2-->"> <a href="<!--@Ecom:Product.Link.Clean.PID-->"><!--@Ecom:Product.Name--> </a> </li> <!--@FooterStart--> </ul> <!--@FooterEnd--> <!--@LoopEnd(BOMProducts)--> </div>

This code will display a configurator to the user where the wanted option of lights can be chosen:

Now the product consists of 4 other products from the catalog in total – and one of the options can now be configured. The user can add any of the lights from the list to this product.

Adding a configurator to the cart requires that the add to cart form is a post as discussed earlier in this chapter – the direct link method is not useable in this scenario.

7.2.5 Changing the Quantity of Items in the Cart

Once an item is in the cart, a customer should be able to change the quantity or to remove the product from the cart. You have a few options available to do this. The simplest solution is to make use of three *Link tags inside the OrderLines loop on a cart page, like this:

<!--@If Defined(Ecom:Order:OrderLine.IsProduct)-->

<a href="<!--@Ecom:Order:OrderLine.IncrementLink-->"> + </a> <a href="<!--@Ecom:Order:OrderLine.DecrementLink-->"> - </a> <a href="<!--@Ecom:Order:OrderLine.DeleteLink-->">Delete</a> <!--@EndIf(Ecom:Order:OrderLine.IsProduct)-->

This renders the following code in the browser:

<a href="Default.aspx?CartCmd=IncOrderLine&key=OL572"> + </a> <a href="Default.aspx?CartCmd=DecOrderLine&key=OL572"> - </a> <a href="Default.aspx?CartCmd=DelOrderLine&key=OL572">Delete</a>

(15)

Page 15 of 32

The first link increases the quantity of the selected item in the cart by one. The second link decreases the quantity and the final link removes the product from the cart

completely.

Notice how each link uses the CartCmd query string along with a reference to the order line that is being modified. Also note that I am checking if a product or a discount is being rendered. Obviously, it doesn’t make sense to offer increment and decrement links for discounts, and with this code they light up on products only.

If for some reason you need more control over the link you can build it up yourself using the available cart commands and the Ecom:Order:OrderLine.ID tag, like this:

<a href="Default.aspx?CartCmd=IncOrderLine&key=<!--@Ecom:Order:OrderLine.ID-->"> + </a>

To let the user enter a quantity for a product directly rather than using the Increment and Decrement links, you can add a text field or a drop-down list to the order line. You also need to add a button to submit the changes to the server. Here’s an example

implementation:

<!--@LoopStart(OrderLines)--> ...

<!--@If Defined(Ecom:Order:OrderLine.IsProduct)-->

<input type="text" name="<!--@Ecom:Order:OrderLine.Quantity.Input.Name-->"

value="<!--@Ecom:Order:OrderLine.Quantity-->" />

<!--@EndIf(Ecom:Order:OrderLine.IsProduct)--> ...

<!--@LoopEnd(OrderLines)-->

This code renders a text box with an ID for each order line. The tag

Ecom:Order:OrderLine.Quantity.Input.Name returns something like

QuantityOrderLineOLNN where NN is the ID of the order line. When posting back to the cart, this ID is used to identify which quantity applies to which order line. You can let the user save the changes by moving to the next step, or with a custom Update button which can be as simple as this:

<input type="submit" value="Update" />

If you don’t want to create your own text box, you can also use the tag

Ecom:Order:OrderLine.Quantity.Input.Box which renders the complete text box for you.

7.2.6 Removing Items from the Cart

Finally, you may have the need to remove items from the cart. To do this, you have two options. Firstly, you can clear the entire cart by linking to any page you want to display after the cart has been emptied and adding emptycart as the cart command. For example, the following link:

http://ecommerce8.local.dynamicweb.dk/en-US/Products?cartcmd=emptycart

empties the cart and then sends the user to the Products page.

Secondly, you can remove individual items from the cart by building up a link with a cart command of DelOrderLine and the ID of the order line. For example:

(16)

Page 16 of 32

<a href="Default.aspx?CartCmd=DelOrderLine&key=

<!--@Ecom:Order:OrderLine.ID-->">Delete</a>

If you have no need to control the actual URL, you can also use the DeleteLink

shortcut like this:

<a href="<!--@Ecom:Order:OrderLine.DeleteLink-->">Delete</a>

7.2.7 Redirecting the user after adding something to the cart.

If you know the ID of the page you want to redirect to in advance, redirecting the user is fairly easy: just add a hidden field called Redirect to the form, like in this example that shows a modified example of the code you saw earlier to add a product with a user defined quantity to the cart:

<form method="post">

<input type="hidden" name="CartCmd" value="add" />

<input type="hidden" name="ProductID" value="<!--@Ecom:Product.ID-->" />

<input type="hidden" name="Redirect" value="/Default.aspx?ID=8" />

<select name="quantity"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select>

<input id="Submit1" type="submit" value="Add to cart" /> </form>

This takes the user to the page with an ID of 8 whenever an item is added to the cart. If you need more control over the target page, you can use a

NotificationSubscriber and handle the redirect through code.

NotificationSubscribers are discussed in Chapter 15.

7.3 Displaying a Cart Summary on All Pages

A common request in many eCommerce web sites is the ability to display a summary of the cart on all pages. In this summary you could then show the number of items in the cart, and the total price for example. Fortunately, this is very easy to do as the Order tags are available in global scope. This makes it trivial to add the summary to a page template or a master template in a design. Here’s an example that shows the number of products, the price and the total order amount:

<!--@If Not Defined(Ecom:Order.IsEmpty)-->

<strong>Shopping Cart</strong><br />

Items in basket: <!--@ Ecom:Order.OrderLines.TotalProductQuantity --><br />

Subtotal: <!--@Ecom:Order.Price.Currency.Symbol--> <!--@Ecom:Order.PriceWithoutFees.PriceWithVAT--><br /> Delivery: <!--@Ecom:Order.Price.Currency.Symbol--> <!--@Ecom:Order.ShippingFee.PriceWithVAT--><br /> Payment: <!--@Ecom:Order.Price.Currency.Symbol--> <!--@Ecom:Order.PaymentFee.PriceWithVAT--><br /> Total: <!--@Ecom:Order.Price.Currency.Symbol--> <!--@Ecom:Order.Price.PriceWithVAT--><br />

<a href="<!--@Global:Pageview.Url-->&amp;cartcmd=emptycart"">Empty basket</a><br /> <a href="Default.aspx?ID=<!--@DwAreaCartPageID-->">Check out</a><br />

(17)

Page 17 of 32

You’re not limited to displaying a summary though. You have the complete order data available, so you can just as easily loop over the OrderLines collection and output information for specific products if you have the need.

To completely hide the summary I am checking the IsEmpty tag. When there’s at least one item in the cart, this tag returns false and thus the code renders the summary. You can have a similar If Defined tag that displays a message to the user when the cart is empty.

Notice how the code uses the tag

Ecom:Order.OrderLines.TotalProductQuantity. This tags returns the number of actual products and skips discounts. If you also want to display the discounts, you could use Ecom:Order.OrderLines.TotalQuantity instead.

If you’ve created a number of orders in your test web site, you may have noticed that you’re not really required to enter any data to complete an order. Clearly, this can lead to bad data entering your system. You see how to fix this and force users to enter valid data in the next section which shows you how to work with Validation groups.

7.4 Validation User Input

You may be familiar with the developer’s mantra: Never trust user input. For any open system, such as an eCommerce web site, it’s extremely important to validate data to make sure it matches some strict criteria before you can let it enter your system. This is not only important to protect you from malicious users who submit bad data to your system. It’s also very useful to help users who make mistakes. Entering a comma in an e-mail address instead of a dot is a mistake easily made, but presents all kinds of problems if you want to send the user an order confirmation. This in turn may put unnecessary pressure on your support people, who first need to figure out what the actual problem is before it can be fixed.

In order to force users to enter required and valid data, Dynamicweb comes with a feature called Validation groups. A Validation group can contain one or more validation fields, which in turn define the rules that are applied to a field the user enters in the Cart module. You can then select one or more validation groups that need to be applied when you create a page with the Shopping Cart module on it. The global process of using Validation groups looks like this:

1. You create a new Validation group in the Management Center

2. You add one or more fields to the group. Fields can come from standard order fields (such as the user’s name or address details), custom order fields, or custom order line fields.

3. For each field, you define the rules that are applied, such as Required, Is Integer, Is Valid Email and so on. The following table lists the available rules and describes what they do:

Rule Description

Required Makes sure the field is not left empty. Any value other than an empty string is considered valid.

(18)

Page 18 of 32 Contains

Does not contain

Enables you to check a field for the presence or absence of a specific value.

Equals

Does not equal

Enables you to check a field for an exact value and then either approve or reject it

Is integer Is numeric

Checks whether a field contains a valid number or integer. Note that Is integer is stricter, as it doesn’t allow decimals, while an integer would still be considered a valid number.

Minimum length Maximum length

Enables you to determine the minimum required or maximum allowed length of a piece of text.

Is less than Is greater than

Enables you to check the value against a minimum or maximum value. This works for both numbers and alphanumeric characters.

Is valid e-mail Checks whether the user has entered a valid e-mail address.

Regular expression If none of the rules satisfy your requirements, you can use the Regular expression field to check the data against your own expression. This gives you the ability to check other, non-built-in formats, such as phone numbers, postal codes and so on.

The regular expression should be written using .NET’s rules for regular expressions For more details on regular expressions in .NET, check out: http://msdn.microsoft.com/en-us/library/hs600312(v=VS.100).aspx

For some of the rules you can enter additional data used in the rule in the Parameters field, such as the length of a string for the minimum and maximum length rules.

4. With the fields saved, you can now choose a Validation group when configuring the Shopping Cart module on a paragraph. For each validation rule you set up, you can enter a (localized) error message that is shown to the user when a specific field is not valid.

5. At the frontend, the validation messages for invalid fields are available in template tags, enabling you to style their presence using CSS.

In the following section you’ll see how to create Validation groups and configure a number of fields. A later section then shows you how to use these groups to enforce valid data at the frontend.

7.4.1 Creating Validation groups

Showing how to create Validation groups is best done with a demo, so the next walkthrough shows you how to create a group and configure a number of fields.

Walkthrough – Adding a Validation Group for Customer Details

1. Open the Management Center and expand the path eCommerce | Orders | Validation groups.

2. Click New on the toolbar and then enter Customer details as the Name.

3. From the Field drop-down, select Customer name and then click the Add button. In the Rule drop-down that appears leave Required set as the select value.

(19)

Page 19 of 32

4. From the Field drop-down choose Customer city and click Add again. Set the Rule to Minimum length and enter 5 as the parameter. Next, just above the Parameters field for the city rule, click the tiny green Plus (+) icon. A new rule appears, together with a drop-down that enables you to determine how the rules should work together. As the Rule, choose Maximum length and enter 30 in the Parameters field. Leave the drop-down set to All rules must validate. For cases where you want only one of the rules to be validated, you can choose At least one rule must validate.

5. From the Field drop-down choose Customer e-mail and click Add again. Set the Rule to Is valid e-mail.

6. From the Field drop-down choose Customer phone and click Add again. Set the Rule to Regular expression and enter ^\d+$ as the expression. Your final dialog should look like Figure 7-7:

(20)

Page 20 of 32

Figure 7-7

Note that the regular expression for the phone number is a little weak as it allows only numbers such as 0123456789, which still doesn’t represent a valid phone number. In addition, valid numbers such as +31 30 1234567 won’t validate. However, for this demo, it’s more than enough. For detailed examples of regular expressions, check out my favorite regular expressions website: http://www.regular-expressions.info and take a look at this blog post: http://blog.stevenlevithan.com/archives/validate-phone-number.

6. Click Save and close on the toolbar to apply all your changes.

The Validation group is now stored in the database and is available to each page in your website that has a Cart module attached to it. You’ll see how to configure the Shopping Cart module to take your Validation group into account next.

(21)

Page 21 of 32

7.4.2 Applying Validation groups

The definition of your Validation groups is logically separated from the actual Cart pages. This makes it easy to reuse specific rule sets on multiple pages. When you add a

Shopping Cart module to a page, you can add one or more Validation groups that are validated. In addition, you can choose which rules you want to apply and you can supply an error message. Having the error message separated from the rule is particularly useful in web sites using multiple languages, as you can use translated messages in the different language areas.

In the next walkthrough you’ll add the Validation group to the page with the Shopping Cart module, select the rules you want to apply and supply validation messages. You’ll then see the effects of the rules when trying to complete an order with invalid data.

Walkthrough – Adding a Validation Group for Customer Details

1. Open the page with the Shopping Cart module and bring up the module’s settings. 2. Under the heading Custom validation groups select the Customer details group and

click Add. You’ll see the rules you defined earlier. Place a checkmark in each of the four checkboxes for the rules and then enter a custom validation error message. You should end up with a screen similar to Figure 7-8:

Figure 7-8

3. Click Save and close to apply your changes.

4. Next, open the frontend site in your browser, add a few products to your cart and click the Cart menu item.

5. Continue with the checkout process until you see the Customer Details page. Leave all fields empty and click Select payment and delivery options (this is the “next” button you changed in an earlier walkthrough). Instead of seeing the page with the payment providers, the page reloads and now shows a number of error messages:

(22)

Page 22 of 32

Figure 7-9

If you look at the HTML for the page, you’ll see a clean <ul> element containing a <li>

element for each broken rule, which in turn contains a link with some JavaScript that puts the focus on the offending field when clicked. You can change the output for the rules as you see fit (look in the Information.html file), for example by removing the “Error in the input field” prefix, adding CSS rules or replacing the in-line JavaScript with some leaner jQuery code.

In this walkthrough you only added a few rules, but in a real-world scenario you would make sure more fields are validated by defining additional rules. The good thing about the Validation groups and validation rules is that they are carried out at the server. This means it’s not an option for a malicious user to disable JavaScript to bypass the

validation. At the same time it also means you need to redo parts of the validation in JavaScript if you want to provide your user with immediate feedback. Fortunately, many validation frameworks exist that make this very easy, such as the excellent Validation jQuery plugin: http://bassistance.de/jquery-plugins/jquery-plugin-validation/.

7.4.3 Enabling Step Validation

Besides entering invalid data in the user details and other order steps, another potential attack vector is the query string. In earlier versions of Dynamicweb, the current step in the checkout process was maintained in the query string. That made it possible to “hack” your way to a complete order simply by changing Step=2 in the query string to Step=6. Note that this just marked the order as complete, not as paid, so it was still quite easy to see which orders were real and which ones were bogus. With the new cart

implementation, step state is maintained in a different way, minimizing but not removing this attack vector.

(23)

Page 23 of 32

You can still easily do this although it’s less obvious. To mark an order as completed without passing the payment page, follow these steps:

1. Add some stuff to your cart and then visit the main Cart page

2. Enter your user details and then agree to the terms and conditions (as an ethical user, you should of course comply with all the rules)

3. Click Next (or Select payment and delivery options if you followed along with the walkthroughs).

4. Rather than choose a payment provider, click the Cart link in the menu again to return to the first page.

5. Use Firebug or the Internet Explorer Developer toolbar to modify the underlying HTML for the next button from something like this:

<input type="submit" name="CartV2.GotoStep1" id="CartV2.GotoStep1" value="Next" />

To this:

<input type="submit" name="CartV2.GotoStep1" id="CartV2.GotoStep3" value="Next" />

6. Click the Next button in the browser to enjoy your free lunch.

Clearly, this is undesirable behavior as you could end up with lots of bogus orders in your database. Even though these order details are missing the payment data, it’s still inconvenient to sift through the orders to find the real ones.

Fortunately, you can prevent this from happening by enabling order step validation. When this is enabled, Dynamicweb makes sure all previous steps are visited before allowing you to the next one. This means you need to pass the payment step before you can visit the step that marks the order as complete. You need to do the following to enable order step validation:

1. Open the Management Center and expand the path eCommerce | Advanced configuration | Shopping cart.

2. Tick the box for Enable step validation. 3. Click Save and close to apply the changes.

In addition to Step validation you should also make the Payment method ID a required field in your Validation group. This further reduces your chances of ending up with bad data.

7.5 Sending Order Notifications

At this stage you have a pretty much complete eCommerce system. Customers can browse the product catalog, add selected products to the cart and then complete the order by entering their details. Two main things are still missing, though: a payment method that ensures users actually pay for the products they order, and order

(24)

Page 24 of 32

methods are discussed in the next chapter, while you’ll see how to configure e-mail in this section.

7.5.1 Configuring E-mail Order Confirmations

In a typical eCommerce site you send at least two e-mails when an order is completed: one to the customer to confirm the order, and the other to the shop manager to make her aware of the new order. The first message typically contains branding elements such as a logo, colors and so on, while the other could be as plain as a text message with just the order ID and some more details.

Sending out the order e-mails is done through the Shopping Cart method, as shown in the following walkthrough

Walkthrough – Configuring Order Confirmation E-mails

In this walkthrough you’ll configure the cart to send out two different e-mail messages when an order is completed: one to the customer and one to the manager. In the following steps you will see how to configure the module, and how to assign and customize the templates.

Note: For the e-mails to be sent correctly, you need to have a mail server configured. To do this, open up the Management Center and expand the path System | System setup. Then choose between a Microsoft Exchange server or an SMTP Server in the Type drop down and enter the name of the server in the Server field.

1. Open up the settings again for the Shopping Cart module on your Cart page.

2. Under the Notification e-mails heading, click the Add notification link. Complete the dialog as follows:

Figure 7-10

This screen configures the message that is sent to the customer and as such doesn’t allow you to enter a recipient e-mail. You can choose OrderEmail.html as the

(25)

Page 25 of 32

template that is used for the message’s body. You’ll see how to customize this template later.

Click OK to apply the changes.

3. Click the Add notification link again, but now configure an e-mail that will be sent to the shop owner as follows:

Figure 7-11

4. Save all your changes and then place a new order in the frontend web site, After a while you should receive the e-mails at the addresses you configured in step 3 and the one you provided as part of your user details when completing the order.

You can repeat steps 2 and 3 to add more e-mail notifications if required.

7.5.2 Customizing Mail Templates

Since the e-mail message sent to the customer typically contains some branding for your shop, you need to customize the e-mail body to match your shop’s design and style. You could, for example, add a logo to the top and use your design’s font and font colors in the text. For the best results, you shouldn’t use external CSS files but in-line CSS instead. In addition, you should prefer a table based layout (yay, old-skool tables again!) over a <div /> based design. Most of the changes you need to make to the template apply to all newsletters sent by e-mail, so you can use whatever technique you’ve used in the past. For a detailed description of what works and what doesn’t in e-mail

newsletters, check out this article:

http://www.reachcustomersonline.com/2010/01/23/09.27.00/

You can look at the templates that are part of a default installation of Dynamicweb eCommerce to see which tags and loops you have available.

A common request for this kind of e-mail message is the ability to link to images on your server. In older versions of Dynamicweb this wasn’t easy and you needed to hard code the path to the image in your e-mail, For example, to refer to the logo used for the main site you would use the following <img /> element:

(26)

Page 26 of 32

<img src="http://ecommerce8.local.dynamicweb.dk/Files/System/dw_logo.gif" />

While this certainly works, it has one big drawback: whenever you copied the template from your development to your production machine, you had to update the template manually. Fortunately, Dynamicweb now has a number of global Request based template tags available that give you access to the full domain name. To set up the image element so it links to an image on the originating server, you can use a tag like this:

<img src="http://<!--@Global:Request.Host-->/Files/System/dw_logo.gif" />

When the message is sent, the src of the image points to the exact same resource as in the preceding example.

If you need further control over the URL, such as the scheme, you can also use tags like

<!--@Global:Request.Scheme--> (which returns something like http or https),

<!--@Global:Request.IsSecureConnection--> (which indicates whether the current request is made over https) and <!--@Global:Request.Port--> (which returns the port number).

With the setup you’ve seen in this chapter, e-mails are sent as soon as a customer completes an order in the frontend. However, in some cases this is not enough, and you may need to send additional e-mails when an order is ready to be delivered, or has been accepted by the delivery company. In Chapter 10 that deals with orders, you’ll learn how to configure order flows at pre-defined stages of the order. In addition, you’ll see how to send your own e-mails with full control over the order flow process and e-mail in Chapter 18, which deals with Notification Subscribers.

7.6 Working with Custom Order Fields and Order Line

Fields

The templates and template tags that ship with the Shopping Cart module out-of-the-box are already pretty extensive. You’ll find lots of options for the user details, such as name, address, country, phone numbers, a notes field, and more. For many situations, this should be more than enough. But what if you need more? What if you want your user to enter the number of the Customer Loyalty Program card? Or what if you need some additional information for a specific product in the cart? For example, imagine you’re selling mugs with printed custom text like someone’s name. Clearly, you can’t create variants of all available names up front, so you need to ask the user for the name to be printed during the checkout process. You can easily implement these scenarios with custom Order Fields and Order Line Fields respectively, as you’ll see next.

7.6.1 Custom Order Fields

You create custom order fields using the Management Center as follows:

1. Open the Management Center and expand the path eCommerce | Orders | Order fields.

2. Click New on the toolbar and then enter a Name (such as Customer Loyalty Program Number; this name is shown to the end user), a System name (such as

(27)

Page 27 of 32

Template tag (such as CustomerLoyaltyProgramNumber; this tag is used to display the field at the frontend).

3. From the Field type drop-down, choose an appropriate type such as Text, Checkbox, or Date/time. The type you choose here determines the way the field is rendered at the frontend. This works more or less the same as the custom Group and Product fields you saw in Chapter 4.

4. Click Save and close on the toolbar.

Once you’ve created the order fields, you can use them directly in your templates. A common place is in the Information.html template, where users enter their personal details. Adding the fields is pretty straightforward, once you know how to add them. Since they don’t show up in the DwTemplateTags unless you use them, discovering the tags can be a bit hard at first. The following table lists the tags you have at your disposal. Here, TemplateTagName is the template tag you assigned to the field when you created it:

Tag Description

<!--@TemplateTagName--> This tag renders the complete UI for the order field. For a text field, you get a single-line text box, for a long text, you get a textarea, for a date/time you get a date picker and so on.

<!--@TemplateTagName.Clean--> This tag returns the value the user has entered or an empty string.

<!--@TemplateTagName.Name--> This tag renders the name of the field, which you can use as the label in front of the UI control.

So to implement the Customer Loyalty Program Number in your Information.html

template, you would add something like this to that template:

<dl>

<dt><label><!--@CustomerLoyaltyProgramNumber.Name--></label></dt> <dd><!--@CustomerLoyaltyProgramNumber--></dd>

</dl>

This renders the following in the user interface:

Figure 7-12

The value the user has entered is then made available in the backend for the order, directly below the main order details:

(28)

Page 28 of 32

Figure 7-13

7.6.2 Custom Order Line Fields

Order line fields are similar to Order fields, with three exceptions. Firstly, you can only create simple text fields, (not any other types, such as a checkbox or a date/time field). However, you can work around that by using your own HTML, as you’ll see in a bit. Secondly, you need to assign the fields you created to one or more eCommerce groups to which the fields apply. This avoids clutter in the user interface as you can make the fields light up only on the appropriate products. Finally, the fields don’t appear for the entire order, but only for an order line.

In addition to showing the field during the checkout process, you can also let the user enter a value for the field on the product’s details page, as you’ll see in the next walkthrough.

Walkthrough – Using Custom Order Line Fields

In this walkthrough you’ll create two custom fields that are used to collect data from the user. You’ll create a fictitious Cyclist shirts category and create a product called Shirt with custom text. When users order that product they can enter custom text, and determine through a checkbox if the text should be printed in bold or not.

1. Open the Management Center and expand the path eCommerce | Orders | Order line fields.

(29)

Page 29 of 32

Figure 7-14

The Name can be used in the product and cart pages and the System name is used to refer to this field from your templates. The Field length determines the size of the text box control that is rendered in the page.

Click Save and close.

3. Create another field with the following details:

Figure 7-15

The Field length doesn’t matter much here as the field will be rendered as a checkbox. 5. Next, create a new product group called Cyclist shirts. Inside this group create a new

product called Shirt with custom text. Assign the product a price and a stock level. There’s no need to set any of the other properties. Save your changes.

6. Right-click the new group you just created and click Edit group. Click the large Order line fields button to make order line fields the active panel. Then click the Down arrow at the bottom of the button. A popup menu appears showing your custom order line fields:

Figure 7-16

Click Custom Text to add it to the list of selected fields. Repeat that step for the Print in Bold field. Click Save and close on the Ribbon bar to apply the changes.

7. Next, open up the template you’re using to display a product. Near the Add to cart link add the following code:

(30)

Page 30 of 32 <!--@LoopStart(Product.OrderLineFields)--> <!--@HeaderStart--> <h2>Orderline fields</h2><table> <!--@HeaderEnd--> <tr> <td><!--@Ecom:Product.OrderLineField.Name-->:</td> <td> <!--@If(Ecom:Product.OrderLineField.SystemName=='PrintInBold')--> <input type="checkbox" name="<!--@Ecom:Product.OrderLineField.InputTextFieldName-->" /> <!--@EndIf--> <!--@If Not(Ecom:Product.OrderLineField.SystemName=='PrintInBold')--> <!--@Ecom:Product.OrderLineField.InputTextField--> <br /> <!--@EndIf--> </td> </tr> <!--@FooterStart--></table><!--@FooterEnd--> <!--@LoopEnd(Product.OrderLineFields)-->

This code loops over the available order line fields. When the SystemName of the field is

PrintInBold, a checkbox is rendered with its name attribute set to the value of the

InputTextFieldName. In all other cases, I let Dynamicweb handle the UI for the fields using Ecom:Product.OrderLineField.InputTextField. If you now request a product from a group that has these custom fields assigned, you will see something like Figure 7-17:

Figure 7-17

You can now enter some custom text and optionally check the Print in bold checkbox before you click Add to basket. The order line fields are saved with the product and are available in the cart and in the backend when the order is completed.

8. To let users alter the text and checkbox’s state in the cart, you need to make a few changes there as well. To do this, open up ShowCart.html and add the following code. You can add this code between the <td> cells that display the line price and the Increment, Decrement and Delete links:

<td> <!--@LoopStart(Order.OrderLineFields)--> <!--@If(Ecom:Order:OrderLine.OrderLineField.SystemName=='PrintInBold')--> <input type="checkbox" name="<!--@Ecom:Order:OrderLine.OrderLineField.InputTextField.Name-->" <!--@If(Ecom:Order:OrderLine.OrderLineField.Value<contains>'on')--> checked="checked"<!--@EndIf-->/> <input type="hidden" name="<!--@Ecom:Order:OrderLine.OrderLineField.InputTextField.Name-->" /> <!--@EndIf--> <!--@If Not(Ecom:Order:OrderLine.OrderLineField.SystemName=='PrintInBold')--> <!--@Ecom:Order:OrderLine.OrderLineField.Name--> : <!--@Ecom:Order:OrderLine.OrderLineField.InputTextField--> <!--@EndIf-->

(31)

Page 31 of 32

<!--@LoopEnd(Order.OrderLineFields)--> </td>

This code loops over the available order line fields for each product in the cart. When the

SystemName of the field is PrintInBold, a checkbox is rendered, just as in the product template. Using an If Defined tag with <contains> you can check if the field is “on” and thus checked. If that’s the case, the code adds checked=”checked”

to the checkbox element. There’s one caveat, though. By design, browsers don’t submit a checkbox in the request when it’s unchecked. This in turn causes Dynamicweb to overlook the order line field and doesn’t update its value if it was previously checked, but is unchecked in the cart. Therefore, I added a hidden field with the exact same name that does get sent to the server. This way, Dynamicweb sees the field and successfully updates the field. The only downside is that you may end up with just a comma, or the value “on,” for the order line field. But as long as you check for the “on” value anywhere in the string, you can always determine if the checkbox was checked or not.

If the SystemName of the field is not PrintInBold, I simply let Dynamicweb render the standard UI to edit a custom field in the cart, which results in a single checkbox, as shown in Figure 7-18:

Figure 7-18

If you now click the Next button, the custom order line field values are saved successfully with the order and appear in the backend as shown in Figure 7-18:

Figure 7-19

If you need to change the “on,” value to something more sensible, such as True, or Yes, you can use the Extensibility API to hook in the order process and modify the value when the order is completed. You’ll see how to do this in Chapter 18, which deals with Notification Subscribers.

7.7 Summary

In this chapter you saw how to work with the Shopping Cart module, an extensive module that enables customers to view their shopping cart and complete the checkout process. The chapter started off with an overview of the basic settings of the module. You then saw how to change the existing order steps and add your own to influence the flow of the checkout.

(32)

Page 32 of 32

After that you learned how to enable user input validation and order step validation; critical components in an eCommerce environment that help you protect your system from bad orders and data.

You also learned how to configure the Shopping Cart module to send out customized e-mails to the customer and backend administrators when an order has been submitted to your system.

The chapter closed off by showing you how to work with custom order and order line fields, which enable you to collect additional data from the user during the checkout process.

In the next chapter you’ll see how to add yet another piece to the eCommerce puzzle when you learn how to configure and use payment methods.

References

Related documents

A través de la descripción de la composición social del núcleo de estudio donde se han expuesto varios de los fenómenos que afecta al mundo rural, a saber, el despoblamiento,

exhaust trunk ispulni kanal (velikog presjeka) exhaust yalye ispusni ventil, ispulni ventil exit ofthe blade row izlaz iz rotorske reSetke exit of the compressor izlaz iz

In collaboration with the Centre for International and Comparative Studies on Law, Economics, Environment and Work, (DEAL) the Marco Biagi Department of Economics,

Inclusion criteria for eligible studies were: (1) adult patients (aged 18 years) receiving care either in the emergency department or hospital, (2) outcomes of interest includ-

Once you review and complete your order details, select “Place Order”. You will then arrive at the order

هتبلا یم ناوت روصت درک هک نیا هدعاق طسوت نومزآ ناگدنوش زین دیلقت یم دوش و نآ اه نامه راک هیهت ناگدننک نومزآ اه ار ماجنا یم دنهد و نیا رما لیامت هب

Develop policies that recognize that despite medical advances, not all people with HIV/AIDS will be able to work; ensure that the quality of health care and economic supports

Yet another possible negative consequence is the striking of evi- dence offered by the individual invoking the Fifth Amendment. As noted by the Fourth Circuit