# Add your app block to the quick add modal

> Let merchants place your Shoplazza app block in the theme's quick add modal, and use ThemeApi to read the product, validate input, and carry customization data into the cart.

When a buyer clicks quick add on the home page, a collection page, or the search page, the modal has no place to enter engraving, sizing, a gift message, or other customization, so the buyer has to go to the product detail page anyway. This guide shows you how to put your app block into the theme's quick add modal so buyers can fill in the customization and add to cart right there.

:::note
This guide assumes you can already create and preview a theme extension. If not, work through [Build a theme extension](/docs/app/extensions/online-store/add-theme-extension) first. Every ThemeApi method used here links to its reference, so you don't need to read the [ThemeApi reference](/docs/app/extensions/online-store/theme-api) up front.
:::

## Background

Products that need input from the buyer, such as engraving, sizing, or a gift message, usually place the customization block on the product detail page. When a buyer clicks quick add in a product list, that block isn't in the modal, so they have to go to the product detail page to fill it in.

Putting your block in the quick add modal means handling a few things the product detail page doesn't have:

- **Not knowing which product**: the modal loads with the page, the product is only known when the buyer opens it, and the modal then opens different products again and again.
- **Stopping incomplete add to cart**: a buyer who clicks add to cart before filling in required fields needs to be stopped.
- **Not slowing down every page**: the modal is on almost every page, and your block loads with it on every page.
- **Not interfering with your product detail page block**: when the modal is opened on a product detail page, both blocks are on the page at the same time.

This guide is organized around these four things. Steps 1 to 7 are required for every app, and once they're done you can go live. The sections after them are optional, depending on your app.

## Key concepts

| Concept | Description |
|---|---|
| App block | A Liquid file under `blocks/` in your theme extension, added manually by merchants in the theme editor. See [Build a theme extension](/docs/app/extensions/online-store/add-theme-extension) |
| Product detail area | An area on the page that shows one product and lets the buyer select variants and submit. The product detail page is one, the quick add modal is another, and they don't affect each other |
| ThemeApi | The JavaScript interface `SPZ.themeApi` that themes provide on storefront pages. Your block uses it to read the product of the product detail area it's in, listen for changes, and validate before submission |
| `product_runtime` | A contract declared in your block's schema meaning "this block gets the product of its own product detail area through ThemeApi and doesn't read a page-wide product". The quick add modal only lets in blocks that declare it. Once you declare it, your code must get the product as shown in Step 3 |

## How it works

The diagram below shows the full flow. The quick add modal loads once with the page; after that, every time the buyer opens a product, your block receives a product notification, and the block's node itself stays the same.

```mermaid
sequenceDiagram
    actor U as Buyer
    participant T as Theme
    participant API as ThemeApi
    participant C as Your modal block
    participant S as Your service
    T->>C: Page loads, block and loader render (no product yet)
    C->>API: productDetail.get({ el })
    U->>T: Opens the quick add modal
    API->>C: onProductChange (product data)
    C->>S: Does this product need customization?
    S-->>C: Customization config, or not needed
    C->>C: Loads the customization script if needed and renders the form
    U->>T: Clicks Add to cart / Buy now / express checkout
    T->>T: Checks the variant
    T->>API: Runs the before-submit handlers
    API->>C: Calls your onBeforeSubmit
    C-->>T: Lets it through, or aborts
    T->>T: Sends the request if allowed (with properties fields)
```

## Prerequisites

- A theme extension linked to your app. If you don't have one, create it by following [Build a theme extension](/docs/app/extensions/online-store/add-theme-extension).
- A test store on Reformia v26.54.17 or later, with **Quick add style** set to **Quick add in popups** in the theme settings. The quick add modals of other themes don't support app blocks yet. Whether single-variant products open the modal is decided by the theme setting **Popup trigger scope** (All products / Products with variants only).
- An endpoint on your own service that returns a product's customization config by product ID, or nothing when the product doesn't need customization. The examples here assume it returns `{ "config": { "label": "Engraving", "required": true, "requiredMessage": "Please enter your engraving text." } }`. If you don't have one yet, you can start with a fixed config; see Step 4.

Once integrated, your block shows in quick add modals opened from the home page, collection pages, the search page, and product detail pages, on both desktop and mobile; Add to cart, Buy now, and express checkout all go through your validation.

After Steps 1 to 7, your extension has these three files:

| File | Purpose |
|---|---|
| `blocks/my_customizer_quick_add.liquid` | The modal block: an empty container, the loader reference, and the schema |
| `assets/my_app_quick_add_loader.js` | The loader: gets the product, fetches the config, loads the customization script on demand, and cleans up on unmount. It loads on every page, so keep it small |
| `assets/my_app_customizer.js` | The customization script: renders the form and validates before add to cart. It loads only for products that need customization |

## Preview and debug {#preview}

Each time you change your code, preview it in this order:

1. Run `shoplazza app dev` in your app project's root directory to push the extension to your test store. The command pushes only once when it starts, so after changing code, stop it with Ctrl+C and run it again.
2. Refresh the theme editor and check your block in the quick add modal's product information group.
3. Open the store's home page, click quick add on a product, and check the browser console for errors starting with `[my-app]`.

To confirm ThemeApi is available on the current page, run this in the console:

```javascript
await SPZ.themeApi.whenReady();
const detail = await SPZ.themeApi.productDetail.get();
detail && detail.getData();
```

On a product detail page it returns the product data; see [getData](/docs/app/extensions/online-store/theme-api#get-data) for the fields. On the home page, it returns `null` while the modal isn't open.

## Step 1: Create a modal block and declare `product_runtime` {#step-1}

Create a separate block file for the quick add modal instead of sharing one with your product detail page block. Create `my_customizer_quick_add.liquid` in your extension's `blocks/` directory. The schema at the end of the file needs at least these fields (the block's HTML is in Step 2):

```liquid
{% schema %}
{
  "name": {
    "en-US": "My Customizer (Quick add)",
    "zh-CN": "我的定制（快速加购弹窗）"
  },
  "limit": 1,
  "templates": [],
  "supports": ["product_runtime"],
  "sections": ["quick_add_modal"],
  "settings": []
}
{% endschema %}
```

| Field | Purpose |
|---|---|
| `supports: ["product_runtime"]` | The quick add modal only lets in blocks that declare this value. Without it, merchants don't see your block when adding content to the modal |
| `sections: ["quick_add_modal"]` | Limits your block to the quick add modal. Without it, your block also shows up in other app positions, such as the product information area of the product detail page and the footer, duplicating your product detail page block |
| `templates: []` | No page template restriction. The quick add modal appears on many pages, so leave this empty |
| `limit: 1` | At most one per modal. Once the merchant has added it, the block no longer appears in the list |

After you declare these fields, the merchant opens the product information group of the quick add modal in the theme editor, chooses to add content, and finds your block under **Apps**. Reformia reserves an app slot at this position; the block can't be added anywhere else. In your app's onboarding, suggest placing the block between the variant selector and the quantity selector (below the price for single-variant products).

**What you should see**: after running `shoplazza app dev` again, you can find **My Customizer (Quick add)** under **Apps** when adding content to the quick add modal's product information group in the theme editor.

:::note
`supports`, `sections`, and `templates` only decide whether the block can be added in the editor; they aren't checked when the page renders. If your block ends up outside a product detail area, ThemeApi can't find one, and the code in Step 3 simply doesn't show the block.
:::

## Step 2: Output only a container and a loader

The quick add modal renders on every page, and your block loads with it. So put only an empty container and a small loader script in the block file, and load the full customization script only when the buyer opens a product that needs customization. Otherwise every page of every store that installs your app loads your full script.

Put this before the schema in `my_customizer_quick_add.liquid`:

```liquid
<!-- Block container: the loader renders content here. data-customizer-src is the URL of the full customization script, loaded on demand -->
<div
  class="my-app-quick-add-root"
  data-my-app-quick-add
  data-customizer-src="{{ 'my_app_customizer.js' | asset_abs_url }}"
></div>

<!-- Include the loader with spz-script; asset_abs_url returns the full URL of a file in the extension's assets/ -->
<spz-script
  layout="logic"
  type="application/javascript"
  src="{{ 'my_app_quick_add_loader.js' | asset_abs_url }}"
></spz-script>
```

When several blocks include the same script, it runs once per block. For example, on a product detail page, if your product detail page block and your modal block include the same loader, it runs twice. So the loader checks at the start whether it has already run; see Step 3.

## Step 3: Find the product detail area your block is in

In `assets/my_app_quick_add_loader.js`, use the block container to find the product detail area it's in, then receive the product through change notifications. The code in Steps 3, 4, and 7, put together in order, is the complete loader.

```javascript
(function () {
  // The same loader may be included by several blocks and run several times; initialize only once
  if (window.__myAppQuickAddLoader) return;
  window.__myAppQuickAddLoader = true;

  // Mounted block containers → render state, used on unmount in Step 7
  const mounted = new Map();

  function mount(root) {
    if (mounted.has(root)) return;
    // Each block container keeps its own state instead of using globals
    const state = { seq: 0, card: null, offProductChange: null };
    mounted.set(root, state);

    SPZ.themeApi.whenReady()
      // Pass the block container; ThemeApi finds the product detail area it's in (here, the quick add modal)
      .then(() => SPZ.themeApi.productDetail.get({ el: root }))
      .then((detail) => {
        // The theme isn't supported, or the block isn't in a product detail area: don't show the block
        if (!detail || !mounted.has(root)) return;

        // Right after the page loads the modal has no product yet, so getData() returns null
        renderCard(root, detail, state, detail.getData());

        // Notified when the buyer opens the modal or switches products; null means no product right now
        state.offProductChange = detail.onProductChange((data) => renderCard(root, detail, state, data));
      });
  }
```

- Always pass `el` to `productDetail.get()`. On a product detail page, there are two product detail areas, the page itself and the modal, and without `el` you get the product detail page's. See [ProductDetail object](/docs/app/extensions/online-store/theme-api#product-detail).
- You don't need a timeout while waiting for ThemeApi: when ThemeApi fails to load, `whenReady()` never resolves, and your block shouldn't show in that case anyway.
- Only listen for change notifications on `detail`. Don't listen for the theme's global variant events on `document`: variant events in the modal bubble up to the whole page, and a global listener would mistake the modal's product for the product detail page's product.
- To find theme elements such as the price or the add-to-cart button, use `detail.getElement()`; see [getElement / getElements](/docs/app/extensions/online-store/theme-api#get-element).

## Step 4: Load the customization form per product

The same modal opens different products again and again. Every time a product notification arrives, unmount the old form first, then decide for the new product whether to load the customization script. Continue the loader:

```javascript
  // The modal in the theme editor has no product; show a placeholder so the merchant knows the block was added
  const PLACEHOLDER = '<div class="my-app-placeholder">My Customizer: shown when a buyer opens a customizable product.</div>';

  function renderCard(root, detail, state, data) {
    // Number each render so stale results can be dropped
    const seq = ++state.seq;

    // Unmount the old form first, which also clears what was typed for the previous product
    if (state.card) {
      state.card.destroy();
      state.card = null;
    }

    // No product right now (the page just loaded, or we're in the theme editor): show only the placeholder
    if (!data) {
      root.innerHTML = PLACEHOLDER;
      return;
    }
    root.innerHTML = '';

    fetchCustomizerConfig(data.product.id)
      .then((config) => {
        // When the buyer switches products quickly, an older request can return later than a newer one; drop stale results
        if (seq !== state.seq) return;
        // This product doesn't need customization: don't show the block or load the customization script
        if (!config) return;

        // While the customization script loads, show a skeleton and hold off add to cart so the buyer can't add before the form appears
        root.classList.add('my-app-loading');
        const guard = detail.onBeforeSubmit((payload, context, abort) => {
          return abort('Loading customization, please try again in a moment.');
        }, { id: 'my-app-quick-add-loading' });

        return loadCustomizerScript(root.dataset.customizerSrc)
          .then(() => {
            if (seq !== state.seq) return;
            // MyAppCustomizer is defined by the customization script; see Step 5
            state.card = window.MyAppCustomizer.create(root, detail, config);
          })
          .finally(() => {
            // Whether the form has registered its own validation or the script failed to load, remove the temporary guard;
            // otherwise nothing can ever be added to cart from this modal
            guard.off();
            root.classList.remove('my-app-loading');
          });
      })
      .catch((error) => console.warn('[my-app] customizer not shown:', error));
  }

  // Ask your own service for the product's customization config; return null when it doesn't need customization.
  // The product data from ThemeApi doesn't include metafields, so your service has to decide.
  function fetchCustomizerConfig(productId) {
    return fetch('https://your-app.example.com/api/customizer?product_id=' + encodeURIComponent(productId))
      .then((res) => (res.ok ? res.json() : null))
      .then((body) => (body && body.config) || null);
  }

  // Load the customization script only once; allow a retry after a failure
  let customizerScript = null;
  function loadCustomizerScript(src) {
    if (!customizerScript) {
      customizerScript = new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.src = src;
        script.onload = resolve;
        script.onerror = () => {
          customizerScript = null;
          reject(new Error('failed to load ' + src));
        };
        document.head.appendChild(script);
      });
    }
    return customizerScript;
  }
```

- The theme resets the variant selection in the modal when the product switches, but it doesn't clear the inputs in your block. That's why every product switch calls `destroy()` on the old form first.
- When the buyer switches products quickly, A → B → A, B's config may return after the second A's. The code above uses the sequence number `state.seq` to drop stale results.
- You can cache the customization config per product, but don't cache failed requests.
- If you don't have a backend endpoint yet, replace the body of `fetchCustomizerConfig` with `return Promise.resolve({ label: 'Engraving', required: true, requiredMessage: 'Please enter your engraving text.' });` so every product shows the customization form. Switch back to your real endpoint once the flow works.

## Step 5: Render the form and validate before add to cart

Create `assets/my_app_customizer.js`. It defines `MyAppCustomizer.create()`, renders the form, and registers a before-submit handler with [`onBeforeSubmit`](/docs/app/extensions/online-store/theme-api#on-before-submit): when a required field is empty, it calls `abort` to stop the submission.

```javascript
window.MyAppCustomizer = {
  create(root, detail, config) {
    root.innerHTML =
      '<label class="my-app-field"><span class="my-app-label"></span><input type="text" class="my-app-input"></label>' +
      '<p class="my-app-error" hidden></p>';
    root.querySelector('.my-app-label').textContent = config.label;
    const input = root.querySelector('.my-app-input');
    const error = root.querySelector('.my-app-error');

    // Give the input a name only when it has content, so empty values don't go into the cart as properties (see Step 6)
    input.addEventListener('input', () => {
      if (input.value.trim()) input.name = 'properties[' + config.label + ']';
      else input.removeAttribute('name');
      error.hidden = true;
    });

    // Validate only the fields in your own block
    const handle = detail.onBeforeSubmit((payload, context, abort) => {
      if (config.required && !input.value.trim()) {
        // Mark the missing field in your block, then stop the submission; the theme shows the text to the buyer
        error.textContent = config.requiredMessage;
        error.hidden = false;
        return abort(config.requiredMessage);
      }
    }, { id: 'my-app-quick-add' });

    return {
      // Called on product switch or unmount: unregister the handler and clear the form
      destroy() {
        handle.off();
        root.innerHTML = '';
      },
    };
  },
};
```

The order of execution on add to cart:

```mermaid
sequenceDiagram
    actor U as Buyer
    participant T as Modal product form
    participant API as ThemeApi
    participant C as Your modal block
    U->>T: Clicks Add to cart / Buy now / express checkout
    T->>T: Checks the variant, prompts and stops if not every option is selected
    T->>T: Assembles line items (with the properties fields in your block)
    T->>API: Runs this modal's before-submit handlers
    API->>C: Calls your registered handler
    alt Validation fails
        C-->>T: abort, the theme sends no request
    else Validation passes
        C-->>T: Lets it through, the theme sends the request
    end
```

- Write `return abort(...)`, and don't keep modifying line items after aborting.
- When not every option is selected, the theme first prompts the buyer to select one, and your handler doesn't run.
- The theme decides how the text passed to `abort` is shown; Reformia shows it as a prompt. So your block should also mark the missing field in its own UI, like `.my-app-error` above.
- Handlers must be idempotent: they run on every submission, and once per click on express checkout. Only validate and tidy line items in them; don't upload files or accumulate data.
- When several apps register handlers on the same product detail area, they run from the highest `priority` to the lowest, then in registration order. If any of them aborts, the rest don't run and the page shows only that one message.

## Step 6: Carry the customization data into the cart

Your block sits inside the modal's product form. When the form submits, it collects every field in your block with `name="properties[...]"`, writes them into the line item's properties, and they flow through checkout into the order. That's how the input in Step 5 gets into the cart; you don't call any other API.

For how properties are displayed and read back from orders, see [Add custom properties to carts and orders](/docs/app/use-cases/product-merchandising/add-custom-properties). In the quick add modal, keep these in mind:

- **Empty fields are submitted too.** When a field has a `name` but an empty value, the checkout page shows an `Engraving:` label with no value. That's why Step 5 gives the input a `name` only when it has content.
- **Use properties starting with `_` for internal data.** For example, `properties[_my_app_design_id]` isn't shown to buyers or merchants on the cart page, the checkout page, or the order details in the admin, but the order API still returns it in the line item's `custom_properties`.
- **Upload files ahead of time.** Upload previews, designs, and other files to your service when the buyer finishes customizing, and write the returned URL or ID into a hidden field. Don't upload in a before-submit handler; it runs on every submission.
- **Make order processing tolerant.** ThemeApi can only stop a submission on the frontend. If your block fails to show because of a network problem, the buyer can still add to cart, so your order processing must handle line items with missing or incomplete customization data.

All three purchase buttons carry these properties.

## Step 7: Clean up when the block unmounts

The product detail area may re-render as a whole, replacing your block container with a new node. ThemeApi doesn't clean up registrations on the old container for you, and before-submit handlers registered repeatedly with the same `id` stack up rather than replace each other. The last part of the loader finds new containers and cleans up old ones:

```javascript
  function unmount(root) {
    const state = mounted.get(root);
    mounted.delete(root);
    state.seq++; // Invalidate requests that haven't returned yet
    if (state.card) state.card.destroy();
    if (state.offProductChange) state.offProductChange();
  }

  // Mount the block containers already on the page
  document.querySelectorAll('[data-my-app-quick-add]').forEach(mount);

  // When a product detail area re-renders: clean up old containers that left the document, and mount new ones
  new MutationObserver(() => {
    mounted.forEach((state, root) => {
      if (!root.isConnected) unmount(root);
    });
    document.querySelectorAll('[data-my-app-quick-add]').forEach(mount);
  }).observe(document.body, { childList: true, subtree: true });
})();
```

Besides the before-submit handler and change notification in the code above, also remove in `destroy()` any event listeners, timers, and preview-canvas listeners on `window` (such as `resize`) that you added yourself.

All three files are now complete. The full code is below; copy from it rather than from the pieces above. Run `shoplazza app dev` again and check items 1 to 8 in the [Verify](#verify) table; once they all pass, your modal block is ready to go live.

<details>
<summary>Full code (three files)</summary>

**`blocks/my_customizer_quick_add.liquid`**

```liquid
<div
  class="my-app-quick-add-root"
  data-my-app-quick-add
  data-customizer-src="{{ 'my_app_customizer.js' | asset_abs_url }}"
></div>

<spz-script
  layout="logic"
  type="application/javascript"
  src="{{ 'my_app_quick_add_loader.js' | asset_abs_url }}"
></spz-script>

{% schema %}
{
  "name": {
    "en-US": "My Customizer (Quick add)",
    "zh-CN": "我的定制（快速加购弹窗）"
  },
  "limit": 1,
  "templates": [],
  "supports": ["product_runtime"],
  "sections": ["quick_add_modal"],
  "settings": []
}
{% endschema %}
```

**`assets/my_app_quick_add_loader.js`**

```javascript
(function () {
  if (window.__myAppQuickAddLoader) return;
  window.__myAppQuickAddLoader = true;

  const mounted = new Map();
  const PLACEHOLDER = '<div class="my-app-placeholder">My Customizer: shown when a buyer opens a customizable product.</div>';
  let customizerScript = null;

  function mount(root) {
    if (mounted.has(root)) return;
    const state = { seq: 0, card: null, offProductChange: null };
    mounted.set(root, state);

    SPZ.themeApi.whenReady()
      .then(() => SPZ.themeApi.productDetail.get({ el: root }))
      .then((detail) => {
        if (!detail || !mounted.has(root)) return;
        renderCard(root, detail, state, detail.getData());
        state.offProductChange = detail.onProductChange((data) => renderCard(root, detail, state, data));
      });
  }

  function renderCard(root, detail, state, data) {
    const seq = ++state.seq;
    if (state.card) {
      state.card.destroy();
      state.card = null;
    }
    if (!data) {
      root.innerHTML = PLACEHOLDER;
      return;
    }
    root.innerHTML = '';

    fetchCustomizerConfig(data.product.id)
      .then((config) => {
        if (seq !== state.seq || !config) return;
        root.classList.add('my-app-loading');
        const guard = detail.onBeforeSubmit((payload, context, abort) => {
          return abort('Loading customization, please try again in a moment.');
        }, { id: 'my-app-quick-add-loading' });

        return loadCustomizerScript(root.dataset.customizerSrc)
          .then(() => {
            if (seq !== state.seq) return;
            state.card = window.MyAppCustomizer.create(root, detail, config);
          })
          .finally(() => {
            guard.off();
            root.classList.remove('my-app-loading');
          });
      })
      .catch((error) => console.warn('[my-app] customizer not shown:', error));
  }

  function fetchCustomizerConfig(productId) {
    return fetch('https://your-app.example.com/api/customizer?product_id=' + encodeURIComponent(productId))
      .then((res) => (res.ok ? res.json() : null))
      .then((body) => (body && body.config) || null);
  }

  function loadCustomizerScript(src) {
    if (!customizerScript) {
      customizerScript = new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.src = src;
        script.onload = resolve;
        script.onerror = () => {
          customizerScript = null;
          reject(new Error('failed to load ' + src));
        };
        document.head.appendChild(script);
      });
    }
    return customizerScript;
  }

  function unmount(root) {
    const state = mounted.get(root);
    mounted.delete(root);
    state.seq++;
    if (state.card) state.card.destroy();
    if (state.offProductChange) state.offProductChange();
  }

  document.querySelectorAll('[data-my-app-quick-add]').forEach(mount);

  new MutationObserver(() => {
    mounted.forEach((state, root) => {
      if (!root.isConnected) unmount(root);
    });
    document.querySelectorAll('[data-my-app-quick-add]').forEach(mount);
  }).observe(document.body, { childList: true, subtree: true });
})();
```

**`assets/my_app_customizer.js`**

```javascript
window.MyAppCustomizer = {
  create(root, detail, config) {
    root.innerHTML =
      '<label class="my-app-field"><span class="my-app-label"></span><input type="text" class="my-app-input"></label>' +
      '<p class="my-app-error" hidden></p>';
    root.querySelector('.my-app-label').textContent = config.label;
    const input = root.querySelector('.my-app-input');
    const error = root.querySelector('.my-app-error');

    input.addEventListener('input', () => {
      if (input.value.trim()) input.name = 'properties[' + config.label + ']';
      else input.removeAttribute('name');
      error.hidden = true;
    });

    const handle = detail.onBeforeSubmit((payload, context, abort) => {
      if (config.required && !input.value.trim()) {
        error.textContent = config.requiredMessage;
        error.hidden = false;
        return abort(config.requiredMessage);
      }
    }, { id: 'my-app-quick-add' });

    return {
      destroy() {
        handle.off();
        root.innerHTML = '';
      },
    };
  },
};
```

</details>

The sections below are optional, depending on your app.

## Optional: Coexist with your product detail page block

If your app also has a block on the product detail page, opening the quick add modal on a product detail page puts both blocks on the page at the same time.

When both blocks use `onBeforeSubmit`, you don't need to do anything extra: the product detail page and the modal are two product detail areas, and the handlers registered on each only run in their own area. Adding to cart in the modal runs only your modal block's handler, and adding to cart on the product detail page runs only your product detail page block's handler.

Keep these separate per block instance:

| Where conflicts happen | Requirement |
|---|---|
| Global variables and module-level singletons (form instances, canvas instances, "already started" flags) | Each block uses its own; starting the modal block must not destroy the product detail page block |
| Fixed DOM IDs | Don't use them; when you need one, suffix it with the block instance ID |
| Variant changes | Only handle notifications from your own product detail area; see Step 3 |

**When your product detail page block doesn't use `onBeforeSubmit`**

If your product detail page block handles submission with a page-level product form hook or its own request logic, it also blocks or rewrites add to cart from the modal. To make it recognize and skip submissions from the modal block:

1. Put an instance marker field in the modal block's root:

   ```html
   <input type="hidden" name="properties[_my_app_instance]" value="quick-add" />
   ```

2. At the start of its submission logic, your product detail page block checks this field and lets the submission through when the value is `quick-add`.

The marker starts with `_`, so buyers don't see it. Leave it in the line item; there's no need to remove it.

## Optional: Show a preview in the modal

Your block is already in a modal, so don't stack another full-screen overlay on top. On desktop, attach the preview canvas to the modal's product gallery and fall back to an overlay only when the gallery can't be found; on mobile you can keep the overlay.

Try ThemeApi's `getElement('gallery')` first. In Reformia's quick add modal, the gallery isn't inside the product detail area ThemeApi recognizes, so `getElement('gallery')` returns `null`, and you need to find it by the theme's structure:

```javascript
const gallery = detail.getElement('gallery');
// When the gallery can't be found in Reformia's quick add modal, look it up by the theme's structure
const galleryEl = gallery
  ? gallery.el
  : document.querySelector('#quick-add-dialog #quick-add-media-render');
```

:::tip
- While the modal's opening animation plays, the gallery and other elements have zero width and height. Before drawing a canvas in the modal, wait for the size to settle, and recalculate when the window resizes.
- If you use an overlay, restore the page's scroll lock to its state before the overlay opened when you close it. Don't simply clear it, or you'll also release the quick add modal's own scroll lock.
- The product information column on the right of the modal is a scroll container with no horizontal padding. Shadows that extend beyond your block get clipped; check that dropdowns and tooltips aren't cut off or covered by the bottom of the modal.
:::

## Optional: Add a surcharge for customization

When a customization option costs extra, add the surcharge on the server with a platform [Function extension](/docs/app/extensions/function). For the full approach, see [Add a per-product surcharge with a function](/docs/app/use-cases/product-merchandising/add-surcharge-by-metafield).

## Verify {#verify}

On the Reformia theme, check each item for "modals opened from the home page / a collection page / the search page / a product detail page" × "desktop / mobile":

| # | Action | Expected result | Step |
|---|---|---|---|
| 1 | Add the block in the theme editor | The block appears only in the Apps list of the quick add modal's product information group, and shows the placeholder once added | Steps 1, 4 |
| 2 | Open a product that doesn't need customization | `my_app_customizer.js` doesn't load and the block doesn't show | Step 4 |
| 3 | Open a product that needs customization | A skeleton shows first, then the form; add to cart is held off while the skeleton shows | Step 4 |
| 4 | With a required field empty, click Add to cart, Buy now, and express checkout | Each is stopped, and both your block and the theme show a message | Step 5 |
| 5 | Add to cart after filling everything in | The line item in the cart carries the customization; properties starting with `_` aren't shown | Step 6 |
| 6 | Add to cart without filling in an optional field | No empty property label appears on the checkout page | Step 6 |
| 7 | Switch products quickly, A → B → A | The form for A is shown in the end, with nothing left over from B | Step 4 |
| 8 | Open and close the modal more than 20 times | There's still only one before-submit handler and one set of listeners, and listeners on `window` don't grow | Step 7 |
| 9 | Open the same product's modal on its product detail page and add to cart | The modal's add to cart isn't blocked by the product detail page block and carries the modal block's data; adding to cart on the product detail page itself is unaffected | Optional: coexist |
| 10 | Switch variants in the modal | The variant and price of the product detail page block don't change | Step 3 |
| 11 | Close the preview overlay | The quick add modal still locks background scrolling | Optional: preview |
| 12 | Put a lot of content in the block | The modal scrolls inside while its frame stays put | Optional: preview |

## Next steps

- [ThemeApi reference](/docs/app/extensions/online-store/theme-api): all methods, rules, and error messages.
- [Theme CSS variables reference](/docs/app/extensions/online-store/theme-css-variables): make your block's buttons, prices, and fonts follow the theme.
- [Theme extension reference](/docs/app/extensions/online-store/reference): schema fields, asset references, and locales.
- [Guide merchants to install your extension with deep links](/docs/app/extensions/online-store/deep-link): let merchants place your block at a specific position in one click.
