Conditionally Showing Datepicker Blocks Based on Product Types in Cart Using the Hidden Input Block
In this tutorial, we will demonstrate how to conditionally show or hide a Datepicker block based on whether a product of type “REQUIRES-DRY-ICE” is in the cart, using the Hidden Input Block.
Step 1: Duplicate Your Live Theme
It is good practice to work on a development theme.
Step 2: Upload Snippet
Create a JS file named “giftship-dry-ice” in the “assets” folder and copy and paste the following code:
(() => { const MODULE = { initialized: false, requiresDryIce: false, init() { this.registerEventHandlers(); this.initialized = true; }, registerEventHandlers() { document.addEventListener('giftship.loaded', () => { this.checkCartForDryIce(); }); document.addEventListener('giftship.drawer-cart.opened', () => { this.checkCartForDryIce(); }); }, registerElements() { this.hiddenInputProduct = document.querySelector('#gsAppContainer input[name="attributes[_type]"]'); this.hiddenInputDrawer = document.querySelector('#gsDrawer input[name="attributes[_type]"]'); }, checkCartForDryIce() { fetch('/cart.js') .then(response => response.json()) .then(cart => { //console.log('Cart fetched:', cart); return Promise.all(cart.items.map(item => fetch(`/products/${item.handle}.js`).then(res => res.json()) )); }) .then(products => { this.requiresDryIce = products.some(product => product.type === "REQUIRES-DRY-ICE"); this.registerElements(); this.populateHiddenInput(); Gs.cartOptions.actions.checkConditions(); }) .catch(error => console.error('Error fetching cart or products:', error)); }, populateHiddenInput() { if (this.hiddenInputProduct) this.hiddenInputProduct.value = this.requiresDryIce ? 'true' : 'false'; if (this.hiddenInputDrawer) this.hiddenInputDrawer.value = this.requiresDryIce ? 'true' : 'false'; }, }; MODULE.init(); })();
Step 3: Edit theme.liquid and Include Snippet
At the bottom of this document, directly above the closing </body>
tag, paste the following code:
<script src="{{ 'giftship-dry-ice.js' | asset_url }}" defer="defer"></script>
Step 4: Set Up a Cart Option Set
Create a cart option set and navigate to Display Settings. Make sure the cart set is set for display.
Step 5: Add a Hidden Input Block
Create a hidden input block. You can name the input anything, but for this tutorial, use “_type” and remember to uncheck “Ignore value.”
Step 6: Add the Datepicker Blocks
Create the first datepicker block and move to the display rules tab.
- Display Option: Select “When all conditions are met.”
- Block Conditions: Show IF block “_type” is equal to “true.”
- Do the opposite for the second date picker block (eg. equal to false).
Step 7: Test, Test and Test!
Preview the development theme, add items with and without product type “REQUIRES-DRY-ICE” and remove, refresh and repeat.