Skip to navigation

Lab - Create a Widget Template to display Dynamic Data

Plan: Stencil Developer

Lesson 15 of 23 · 45 min

Summary

In the previous section you used widget UI inputs to configure static content including a product image and some text entered in the visual editor. In this section, you will combine those inputs with your store’s GraphQL Storefront API to create a dynamic widget powered by GraphQL. The goal of this section is to create a widget template that dynamically displays a product’s default image and product description above a list of the product’s variants that displays the image, price, and SKU of each variant based on the content creator’s product selection:

Dynamic widget

In this lab you will

  • Write the GraphQL Query
  • Write the Widget Template Schema
  • Write the Widget Template Markup
  • Create and Use the Widget Template

Prerequisites

  • BigCommerce store with at least one product
  • (optional) A product with multiple variants and variant images
  • Stencil theme with at least one region
  • Widget Builder, installed and configured in Module 4: Lab - Widget Builder Setup
  • BigCommerce API credentials

This lab builds most of its widget template with Widget Builder, the same tool you set up in Module 4. If you haven’t completed that lab yet, go back and complete it first.

Create a Widget That Displays Data from the GraphQL API

In this section you will focus on integrating data from GraphQL into your widget template such that when a shopper selects a product using a Product ID setting in the Page Builder UI, information about that product will be displayed in JSON on the page.

GraphQL query data in widget

Write the GraphQL Query

In the following steps, you will use the Storefront API Playground to test a GraphQL query that, given a product ID, requests the following information:

  • The product name
  • The first 1000 characters of the product description
  • The product’s default image at multiple sizes
  • The product’s variants including each variant’s
    • image at multiple sizes
    • price
    • SKU
    • id

Until you integrate your query with your widget template you will need to manually supply the product ID to test it. Start by finding the product ID for your product.

  1. Log into your store’s control panel then navigate to Products > View and locate your test product.

Finding the right test product.

This example will work for any product, but you will have the best result if you use a product that has multiple variants, each with its own SKU and image.

KB Article - Variants

  1. Click the product’s name, then observe the product ID in your browser’s URL.

example

  1. Open the Storefront API Playground to begin testing your query. From your store’s control panel, navigate to Settings > API > Storefront API Playground.

You should see a UI with some example queries where you can write a query in the left pane, configure query variables in the lower left, run the request, and see the results on the right. You may need to expand the query variables section in the lower left.

Storefront API Playground

  1. Open a new tab in the playground or edit the query in an existing tab, then type or paste the following query into the query editor:
query productById(
$productId: Int
) {
site {
product(entityId: $productId) {
entityId
name
plainTextDescription(characterLimit: 1000)
defaultImage {
...ImageFields
}
variants {
edges {
node {
... VariantFields
defaultImage {
... ImageFields
}
}
}
}
}
}
}
fragment VariantFields on Variant {
entityId
sku
defaultImage {
... ImageFields
}
prices {
price{
... MoneyFields
}
salePrice {
... MoneyFields
}
}
}
fragment ImageFields on Image {
url160wide: url(width: 160)
url320wide: url(width: 320)
url640wide: url(width: 640)
url960wide: url(width: 960)
url1280wide: url(width: 1280)
}
fragment MoneyFields on Money {
value
currencyCode
}
  1. In the Query Variables section to the lower-left section of the playground, add the following:
{ "productId": 50918 }

Be sure to replace the product’s ID (50918) in the example above with your test product ID.

  1. Click the “Play” button to run the request.

You should see information about your product in the query results pane on the right:

Playground query results

Why does my result say “product”: null?

If you get a null result for your product query, that means that you, as an unauthenticated storefront API user, are not authorized to see that product. This could be because…

  • The productId variable is not a valid product id.
  • The product is not visible on the storefront or assigned to a category
  • The product is assigned to a category that is hidden by customer group permissions
  • The storefront is not publicly visible
  1. Once you successfully receive a query result, from your ~/widget-templates directory, run the following command to scaffold a new widget template:
widget-builder create product-variant-list

This creates a ./product-variant-list directory containing schema.json, config.json, and widget.html, and opens a live preview in your browser.

  1. In the product-variant-list directory, create a new file named query.graphql, and paste in your query exactly as written in the Playground — Widget Builder reads this file directly, so you don’t need to remove newlines or escape any characters. You may reference the completed query.graphql to check your work.
query productById(
$productId: Int
) {
site {
product(entityId: $productId) {
entityId
name
plainTextDescription(characterLimit: 1000)
defaultImage {
...ImageFields
}
variants {
edges {
node {
... VariantFields
defaultImage {
... ImageFields
}
}
}
}
}
}
}
fragment VariantFields on Variant {
entityId
sku
defaultImage {
... ImageFields
}
prices {
price{
... MoneyFields
}
salePrice {
... MoneyFields
}
}
}
fragment ImageFields on Image {
url160wide: url(width: 160)
url320wide: url(width: 320)
url640wide: url(width: 640)
url960wide: url(width: 960)
url1280wide: url(width: 1280)
}
fragment MoneyFields on Money {
value
currencyCode
}
  1. Create a file named queryParams.json in the same directory, with your test product’s ID, so Widget Builder’s local preview can run the query against your store:
{
"productId": 50918
}

Be sure to replace the product’s ID (50918) in the example above with your test product ID. You may reference the completed queryParams.json.example.

Write the Widget Template Schema

The widget template’s schema defines the inputs a content creator can use to configure a widget. When a widget template includes a GraphQL query, the schema is also used to populate the query variables with selections from other inputs (like a product ID). Widget templates use Handlebars to access the configured values to determine the content, markup, and styles to display. In this section, you will write an array of schemas containing a product ID input to select a product from the catalog.

Variant list widget

Throughout this section, you will edit the schema.json file in your product-variant-list directory. You may reference the completed schema.json to check your work.

These steps will walk you through creating the schema array in schema.json. To create the configurable fields in the Page Builder sidebar, the schema must include exactly one tab at the root level. To map the product ID from the user’s product selection to the $productId variable in the GraphQL query, the schema must also include exactly one hidden element on the root level. In this case, the tab contains one section which contains settings for heading text, image upload, image width, and text block content.

  1. Open schema.json and replace its contents with an array containing a single tab object:
[
{
"type": "tab",
"label": "Display GraphQL Query Data",
"sections": []
}
]
  1. Add a section object with a label string and an empty settings array to the sections array. Example:
[
{
"type": "tab",
"label": "Display GraphQL Query Data",
"sections": [
{
"label": "Product",
"settings": []
}
]
}
]
  1. In the settings array, add a Product ID setting. This setting’s value will be used to populate other information about a product in the catalog, so the default text and the label should reflect that usage:

Product ID setting

Example:

{
"type": "productId",
"label": "Select a Product",
"id": "productId"
}

At this point, your schema.json should contain a single tab that looks like the tab element in the completed schema.json.

  1. At the root level of the schema, add a hidden element that maps the value of productId to the $productId variable in the GraphQL schema:
{
"type": "hidden",
"settings": [
{
"type": "graphQl",
"id": "graphQueries",
"typeMeta": {
"mappings": {
"productId": {
"reads": "productId",
"type": "Int"
}
}
}
}
]
}

At this point, your schema.json should contain both the tab and hidden elements, like the completed schema.json.

Write the Widget Template Markup

While the widget template schema is used to define the input and map the input’s value to the GraphQL query, the template’s markup will be used to define the structure and styling of the widget. Widgets access the results of a GraphQL query on the underscore (_) object. For example, to reference the GraphQL data, you can use the following Handlebars expression:

{{_.data}}

By default the data is an object rather than a string, so simply adding {{_.data}} to a template will result in output like “[Object object]”. In this example, we simply want to print the result in a widget so you will use the {{json}} Handlebars helper to convert the object to a string and triple curly brackets to prevent BigCommerce from converting special characters into HTML entities:

{{{json _.data}}}
  1. Open widget.html and write a DIV tag containing the stringified GraphQL query result.

Example:

<div>{{{json _.data}}}</div>

Save the file — Widget Builder reads it as plain HTML, so there’s no need to escape it or wrap it in quotation marks.

Create and Use the Widget Template

Having written the GraphQL query, schema, and markup, you are now ready to publish your widget template to the store and use it in Makeswift or Page Builder.

  1. Run the following command from your ~/widget-templates directory to publish the template:
widget-builder publish product-variant-list

Widget Builder reads query.graphql, schema.json, and widget.html, and sends them to the Widgets API for you.

  1. Note that Widget Builder saved a widget.yml file in the product-variant-list directory containing the new widget template’s UUID. This file lets Widget Builder update the same widget template the next time you publish.

After the command succeeds, your widget template is available in both visual editors. Use it in whichever editor you’re working in.

Use it in Makeswift

Makeswift needs a Makeswift-connected channel. If you haven’t set one up, see Lab - Navigate Makeswift.

  1. Open the store control panel and go to the Channel Manager
  2. Select the Makeswift-connected channel and click Edit in Makeswift
  3. Navigate to a page in the editor that has an available region, such as the home page
  4. Open the component drawer and find the component for your widget template
  5. Drag the component into a region on the page
  6. Select a product using the product setting in the panel that opens. The widget should display the result of the GraphQL query for that product
  7. Save your changes so that you can observe the effects of updating the widget template in the next section

Use it in Page Builder

  1. Open Page Builder by navigating to Storefront > Customize in the BigCommerce. Look below the default list of basic widgets to find the Custom section.
  2. Drag your custom widget onto the page. Assuming the schema is structured correctly, you should be able to modify the settings in the left sidebar. When you first add the widget to the page, you should see a null result from your GraphQL query.
  3. Begin typing a product name or SKU into the “Select a Product” field on the left sidebar. Once you select a product in the left sidebar the result should display the result of the GraphQL query.
  4. Use the Save button in Page Builder to save your widget placement so that you can observe the effects of updating the widget template in the next section.

What if I can’t edit my widget schema settings?

If Page Builder shows a warning instead of the widget’s settings, there is an issue with the widget template schema. Examine your schema and review the Big Dev Docs. Specifically, ensure your schema has exactly two root elements: one tab element and one hidden element. All configurable settings should be contained by a section inside the tab.

Improve the Widget Template

Now that you have a widget template that displays dynamic information from GraphQL, it’s time to improve the template markup to display the product variant information in a human-readable list.

Write the Improved Template Markup

  1. Open widget.html and replace its contents with the following markup. As before, Widget Builder reads this file as plain HTML and Handlebars, so no JSON escaping is required:
{{#unless _.data.site.product}}
<div>Select a product in Page Builder to populate this widget</div>
{{else}}
<div style="width:100%">
<img
srcset="{{_.data.site.product.defaultImage.url320wide}} 320w,
{{_.data.site.product.defaultImage.url640wide}} 640w,
{{_.data.site.product.defaultImage.url960wide}} 960w,
{{_.data.site.product.defaultImage.url960wide}} 1280w"
sizes="(max-width: 600px) 320px,
960px"
src="{{_.data.site.product.defaultImage.url960wide}}"
style="display: block;max-width: 66%; margin-left:auto; margin-right:auto" />
</div>
<div style="display: block;margin-left:auto; margin-right:auto;">
<strong style="display: block;">{{_.data.site.product.name}}</strong>
<em style="display: block;">{{_.data.site.product.plainTextDescription}}</em>
<ul style="list-style: none;">
{{#each _.data.site.product.variants.edges }}
<li>
<div style="display:flex;flex-direction: row">
<div style="width:160px;flex-grow: 1">
{{#if node.defaultImage}}
<img src="{{node.defaultImage.url160wide}}"/>
{{/if}}
</div>
<div style="flex-grow: 1">
<span>
{{toFixed node.prices.price.value 2}} {{node.prices.price.currencyCode}}
</span>
</div>
<div style="flex-grow: 3">
<strong>{{node.sku}}</strong>
</div>
</div>
</li>
{{/each}}
</ul>
</div>
</div>
{{/unless}}

For brevity, this guide will not explain each line of code above but here are a few notable parts:

  • The content is wrapped in an {{#unless}} Handlebars helper so that placeholder text is rendered if the content creator has not yet selected a product with the productId input.
  • The first <img> tag utilizes srcset and size attributes so that the browser may choose the appropriate size for the image depending on the screen size. Because GraphQL can return image URLs at specified sizes, it’s easy to request several sizes of the same image from BC without uploading different versions of the same image.
  • The <li> elements are wrapped in an {{#each}} Handlebars helper so that a list item is rendered for each variant in the GraphQL data. It’s worth noting that all products, even simple products without variant options, have at least one variant.
  • The {{toFixed}} Handlebars helper is used to render prices with 2 decimal places.

You can check your work against the completed widget.html. With the live preview running, the preview now shows the variant list for the product ID in your queryParams.json file. If the preview isn’t running, start it with widget-builder start product-variant-list.

Update and Use the Widget Template

  1. Run the following command from your ~/widget-templates directory to publish the updated template:
widget-builder publish product-variant-list

Because Widget Builder tracks this template in widget.yml, it updates the existing widget template in place instead of creating a new one.

After the command succeeds, the updated widget template is available in both visual editors. Use it in whichever editor you’re working in.

Use it in Makeswift

Makeswift needs a Makeswift-connected channel. If you haven’t set one up, see Lab - Navigate Makeswift.

  1. Open the store control panel and go to the Channel Manager
  2. Select the Makeswift-connected channel and click Edit in Makeswift
  3. Navigate to the page where you added the widget, then open the component drawer and add a new instance of the component for your widget template to a region
  4. Select a product using the product setting in the panel that opens. The widget should display a list of the selected product’s variants

Use it in Page Builder

  1. Open Page Builder by navigating to Storefront > Customize in the BigCommerce. The widget you saved in the previous section now uses the updated template, and displays a list of the selected product’s variants. Look below the default list of basic widgets to find the Custom section to add a new instance of the widget.
  2. Drag your updated custom widget onto the page. Assuming the update was successful, you should be able to modify the settings in the left sidebar. When you first add the widget to the page, you should see the placeholder text in the template.
  3. Begin typing a product name or SKU into the “Select a Product” field on the left sidebar. Once you select a product in the left sidebar the result should display a variants list.

Widget Builder always updates a widget template in place, which also changes the widgets already created from it. To release an update without changing existing widgets, create a new widget template version instead. See Widget Versioning in Module 6. The “Update Widget Template (New Version)” request in the Widgets API Labs Postman collection sends that kind of update.

Section Challenge

For an extra challenge, try sprucing up the markup and CSS, adding “view product” and “add to cart” links, or implement new settings to control the typography and styling of the widget.

  • Modify the GraphQL query to retrieve the product page template and add a link to the product page.
  • Add links to Add to Cart URLs for each SKU.
  • Use a range setting to let the content creator configure the number of characters of the product description that should be displayed.