Part 3 | Shipping Address
Overview:
In this part we are going to work on the form in our checkout page. We need to add some logic to this page that changes what users will see depending on whether their cart contains an item that needs to be shipped.
Page Logic Explanation
If item needs shipping → Show Address Fields
We don't need to show the shipping form if none of the products are physical products. No need to ship a digital product.
Let’s start by adding a method to our "Order" model to check for items in cart that may not be digital, then using this information to change how our for and payment option gets rendered.
Step 1 | Shipping Method
00:40:18The first thing we need to do is create a method for our "Order" model that checks if we have any items that are not digital.
This can be done with a simple loop that changes the status of ”shipping” to "true" if a child OrderItem is not digital. Then the method simply returns a true OR false value.
View Source CodeStep 2 | Order Shipping Status
00:41:48Since we added the "shipping" method to our order we can use it in the template right away by accessing it like any other property.
ex: {{ order.shipping }}
The thing we need to plan for is when a non-logged in user visits the page. Our order dictionary doe's not have a "shipping" attribute, so we need to add it in our cart view. To keep consistency, let's add "shipping" to all 3 views in the order object dictionary.
order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False}
View Source CodeStep 3 | Hide Shipping Form
00:42:48We need to get the status of “shipping” from our "order" object and remove the address field if shipping is false.
Let's write our Javascript right in "checkout.html". Since this is the only page, we will need this functionality.
Create a script tag just above our {% endblock %}
View Source CodeStep 4 | Payment Option
00:46:15When a user adds form data and clicks continue; we want to open up the payment option but still let them edit the form. Let's first create an event handler that hides the form button and opens up the payment option wrapper (payment-info), it currently has the class of "hidden".
When the form is submitted, we want to remove the class of "hidden" from the payment option and add the class of "hidden" to the button.
Hide button & open payment option on submit
We’ll query the form by id and set the event listener on submit.
This will open up the payment-info wrapper as shown below. Notice the button is not visible.
Add demo Payment button
Inside the payment-info wrapper; let's add a button with the id of "make-payment". This will be the placeholder that will trigger orders to be processed until we get to the payment integration module.
View Source CodeStep 5 | Trigger Payment Action
00:50:59Let's add an event handler to the new "payment-submit" button and a function to trigger on submission, we’ll take care of what the function does in the next part.
View Source Code