[{"data":1,"prerenderedAt":20},["ShallowReactive",2],{"blog-post-en-branching-looping-complex-web-forms-broma":3},{"slug":4,"lang":5,"title":6,"summary":7,"date":8,"tags":9,"tag_slugs":15,"thumbnail_url":16,"translations":17,"body":18,"asset_base":19},"branching-looping-complex-web-forms-broma","en","Branching and Looping Logic for Complex Web Forms in Broma","Learn how to add conditional branches and loops to Broma workflows so you can automate multi‑step web forms that change based on user input or page state.","2026-11-02",[10,11,12,13,14],"branching","looping","web-forms","broma","automation",[10,11,12,13,14],"https:\u002F\u002Fblog-api.bromaapp.com\u002Fapi\u002Fblog\u002Fposts\u002Fbranching-looping-complex-web-forms-broma\u002Fthumbnail.svg?lang=en",[5],"## Why Branching and Looping Matter\n\nMost repetitive web tasks are not linear. A checkout flow may show different upsell options depending on the cart total. A support dashboard might require you to iterate over a dynamic list of tickets. Broma lets you model that variability with **Branch** and **Loop** steps, turning a single recorded sequence into a resilient, data‑driven workflow.\n\n## Core Concepts in Broma\n\n### Branch step\nA Branch evaluates a JavaScript expression. If the result is truthy the workflow follows the *True* path; otherwise it follows the *False* path. The expression can read any variable that exists in the run context — page text, extracted attribute, or a value you stored earlier.\n\n### Loop step\nA Loop repeats a block of steps for each item in an array. You supply the array (often the result of a **Read text** or **Get elements** step) and Broma exposes the current item as `item` and the index as `index` inside the loop body.\n\n### Variables\nEvery step can write to the run‑time variable store (`Set variable`). Later steps, including Branch conditions and Loop iterators, read those variables with the `{{varName}}` syntax or directly in JavaScript.\n\n## Building a Conditional Branch\n\n1. **Open the target page** – `Open url` → `https:\u002F\u002Fexample.com\u002Fcheckout`.\n2. **Read a decisive element** – `Read text` on the element that shows the cart total, store as `cartTotal`.\n3. **Add a Branch step** – Condition:\n```js\nNumber({{cartTotal}}.replace(\u002F[^\\d.]\u002Fg, '')) >= 100\n```\n   *True* path: click the “Free shipping” banner.\n   *False* path: continue to standard shipping selection.\n4. **Continue the workflow** – Both paths converge on the “Place order” click.\n\n> **Tip:** Keep the condition pure JavaScript. Avoid side effects; the expression runs in a sandboxed context each time the branch is evaluated.\n\n## Looping Over a List of Items\n\nImagine a product‑grid page where each row has an “Add to cart” button. You want to add the first five items.\n\n1. **Get elements** – `Get elements` with selector `css:.product-row` → stores array in `rows`.\n2. **Add a Loop step** – Iterator: `{{rows}}`. Limit iterations to 5 by adding a **Break** step inside the loop when `index === 4`.\n3. **Inside the loop**:\n   - `Click` on `item.querySelector('button.add-to-cart')`.\n   - `Wait for element` confirming the cart badge updates.\n   - `Set variable` `addedCount = {{addedCount}} + 1` (initialize `addedCount` to 0 before the loop).\n4. **After the loop** – Proceed to checkout.\n\n```js\n\u002F\u002F Example of a Break condition placed as a Branch inside the loop\n{{index}} >= 4\n```\n\n## Combining Branches and Loops: Real‑World Scenario\n\n**Order‑processing bot** – A marketplace seller needs to confirm each order, but the confirmation UI differs for “digital” vs “physical” goods.\n\n1. **Fetch order list** – API call (via a short JS snippet) returns `orders` array.\n2. **Loop over `orders`**.\n3. **Inside loop** – `Open url` to order detail page.\n4. **Branch on `order.type`** (extracted from a hidden data attribute):\n   ```js\n   {{order.type}} === 'digital'\n   ```\n   *True* → click “Deliver digitally”, fill license key field.\n   *False* → click “Print shipping label”, wait for PDF download.\n5. **Set variable** `processed = {{processed}} + 1`.\n6. **After loop** – Write summary to a local CSV using a **Run JavaScript** step:\n```js\nconst fs = require('fs');\nfs.writeFileSync('processed_orders.csv', 'OrderID,Type\\n' + {{orders}}.map(o => `${o.id},${o.type}`).join('\\n'));\n```\n\n## Debugging Tips\n\n- **Run logs** – Every Branch and Loop logs the evaluated condition and the current `item`\u002F`index`. Open the run history panel to see which path fired.\n- **Breakpoints** – Right‑click any step → *Add breakpoint*. Execution pauses before the step, letting you inspect variables in the console.\n- **Console.log in JS steps** – `console.log('cartTotal:', {{cartTotal}});` appears in the run log output tab.\n- **Limit loop size during development** – Add a temporary Branch at the top of the loop: `{{index}} \u003C 2` to test only the first two iterations.\n\n## Best Practices\n\n| Practice | Reason | How to implement in Broma |\n|---|---|---|\n| **Stable selectors** | Prevent breakage when markup changes | Use data‑attributes (`[data-test-id]`) or relative XPath (`\u002F\u002Fbutton[contains(., 'Add')]`). |\n| **Explicit variable naming** | Makes conditions readable | Prefix with domain: `order_`, `cart_`, `ui_`. |\n| **Guard loops** | Avoid infinite runs on empty arrays | Add a Branch before Loop: `{{rows}}.length > 0`. |\n| **Separate concerns** | Easier maintenance | Put each logical phase (login, navigation, processing) in its own **Sub‑workflow** and call via **Run workflow** step. |\n| **Version control** | Track changes across team | Export workflow JSON, commit to git; Broma’s *Import\u002FExport* menu handles this. |\n\n## Example Workflow (Export Snippet)\n\nBelow is a trimmed JSON export showing the Branch and Loop structure. You can paste it into Broma’s *Import* dialog to see the steps instantly.\n\n```json\n{\n  \"name\": \"ProcessOrders\",\n  \"steps\": [\n    {\"type\": \"RunJavaScript\", \"code\": \"const orders = await fetch('\u002Fapi\u002Forders').then(r=>r.json()); return orders;\", \"outputVar\": \"orders\"},\n    {\"type\": \"Loop\", \"iterator\": \"{{orders}}\", \"steps\": [\n      {\"type\": \"OpenUrl\", \"url\": \"https:\u002F\u002Fmarket.example.com\u002Forder\u002F{{item.id}}\"},\n      {\"type\": \"ReadAttribute\", \"selector\": \"[data-order-type]\", \"attr\": \"data-order-type\", \"outputVar\": \"orderType\"},\n      {\"type\": \"Branch\", \"condition\": \"{{orderType}} === 'digital'\", \"trueSteps\": [\n        {\"type\": \"Click\", \"selector\": \"button.digital-deliver\"},\n        {\"type\": \"Type\", \"selector\": \"input.license-key\", \"text\": \"{{item.licenseKey}}\"}\n      ], \"falseSteps\": [\n        {\"type\": \"Click\", \"selector\": \"button.print-label\"},\n        {\"type\": \"WaitForDownload\", \"pattern\": \"*.pdf\"}\n      ]},\n      {\"type\": \"SetVariable\", \"name\": \"processed\", \"value\": \"{{processed}} + 1\"}\n    ]}\n  ]\n}\n```\n\n## Next Steps\n\n1. **Prototype a single branch** on a page you already automate. Verify the condition logic with a few manual runs.\n2. **Add a loop** around a repetitive click‑sequence (e.g., pagination, table rows).\n3. **Combine** them in a sub‑workflow and share the export with teammates for review.\n4. **Monitor run logs** for a week; adjust selectors or conditions only when a genuine page change occurs.\n\nBy mastering branches and loops you turn fragile linear scripts into adaptable automations that survive UI tweaks and handle real‑world variability — exactly the kind of resilience Broma is built for.\n","https:\u002F\u002Fblog-api.bromaapp.com\u002Fapi\u002Fblog\u002Fposts\u002Fbranching-looping-complex-web-forms-broma\u002Fassets",1794729622410]