惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Schneier on Security
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
T
Threat Research - Cisco Blogs
C
Cyber Attacks, Cyber Crime and Cyber Security
C
CXSECURITY Database RSS Feed - CXSecurity.com
A
Arctic Wolf
Security Latest
Security Latest
Simon Willison's Weblog
Simon Willison's Weblog
I
Intezer
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
T
Troy Hunt's Blog
Latest news
Latest news
Help Net Security
Help Net Security
S
Security Affairs
Webroot Blog
Webroot Blog
The Hacker News
The Hacker News
AI
AI
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Tor Project blog
Forbes - Security
Forbes - Security
Google DeepMind News
Google DeepMind News
AWS News Blog
AWS News Blog
Attack and Defense Labs
Attack and Defense Labs
P
Proofpoint News Feed
www.infosecurity-magazine.com
www.infosecurity-magazine.com
H
Help Net Security
L
Lohrmann on Cybersecurity
S
SegmentFault 最新的问题
Google Online Security Blog
Google Online Security Blog
MongoDB | Blog
MongoDB | Blog
Cyberwarzone
Cyberwarzone
The Last Watchdog
The Last Watchdog
S
Securelist
N
News and Events Feed by Topic
S
Secure Thoughts
F
Fortinet All Blogs
博客园_首页
C
Cybersecurity and Infrastructure Security Agency CISA
量子位
M
MIT News - Artificial intelligence
F
Full Disclosure
T
The Blog of Author Tim Ferriss
T
Tailwind CSS Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Microsoft Security Blog
Microsoft Security Blog
I
InfoQ
P
Privacy International News Feed
L
LangChain Blog
Know Your Adversary
Know Your Adversary
C
CERT Recently Published Vulnerability Notes

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Cascading Configuration UI: Building Dependent Selection Chains in the Properties Panel
Sam Abaasi · 2026-04-28 · via DEV Community

Part 12 of the series: "Extending bpmn-io Form-JS Beyond Its Limits"


A form designer needs to configure auto-fill for a field. They want to pull data from another ticket — a linked ticket that's part of the same process. To configure this, they need to:

  1. Select a behavior (pull from current ticket or from another ticket)
  2. Select the ticket type (which process definition to look at)
  3. Select the ticket phase (which activity/step in that process)
  4. Select the field name (which form field from that phase to pull data from)

Each selection narrows the next. Ticket phases are meaningless without knowing the ticket type. Field names are meaningless without knowing the phase. The available options at each level come from a live API — they change as the process definitions evolve.

This is a cascading configuration UI. Building it in Form-JS's properties panel — in Preact, inside getGroups, with async data fetching — requires solving several problems simultaneously. This article documents each one.


The Problem

A basic select entry in the properties panel is synchronous. You provide a getOptions function that returns an array, and the panel renders a select element with those options. This works for static choices.

Ticket types are not static. They come from Camunda's process definition API. Ticket phases depend on which type was selected — you can't know them until the user has made their type selection and you've fetched from the API. Field names depend on which phase was selected.

The naive approach — pre-load all options at panel open time — doesn't scale. Fetching all ticket types, all phases for all types, and all field names for all phases would be hundreds of API calls on every panel open. You need lazy loading: fetch each level's options only when the previous level has been selected.

The problems to solve:

  1. Async fetching inside Preact component hooksuseEffect with the right dependency array
  2. Reset cascade — when level N changes, clear all levels below N
  3. Storing enriched data — you need the full details object, not just the selected ID, for downstream fetching
  4. Atomic multi-path updates — resetting multiple schema paths in one operation
  5. Per-level loading states — each level has its own loading indicator
  6. Per-level error handling — a failure at level 2 shouldn't prevent level 1 from working
  7. SearchableSelect — hundreds of options at each level make native select unusable

What I Tried First

My first attempt was to fetch all the data at the provider level — in getGroups — and pass options as props to each entry component:

// ❌ Attempt 1: Fetch in getGroups
async getGroups(element, editField) {
  // Can't do this — getGroups is synchronous
  const ticketTypes = await fetchTicketTypes();

  return (groups) => {
    // ...
  };
}

Enter fullscreen mode Exit fullscreen mode

getGroups is synchronous. You cannot await inside it. The middleware function it returns is also synchronous. Async data fetching cannot happen in getGroups.

My second attempt was to fetch in the module constructor, store results in instance variables, and pass them to components:

// ❌ Attempt 2: Fetch in constructor, store on instance
export class TicketAutoFillPropertiesProvider {
  constructor(propertiesPanel, eventBus) {
    propertiesPanel.registerProvider(this, 1000);
    this._ticketTypes = [];
    this._loading = true;

    // Fetch in constructor
    fetchTicketTypes().then(types => {
      this._ticketTypes = types;
      this._loading = false;
      // But now how do you trigger a re-render? You can't.
    });
  }
}

Enter fullscreen mode Exit fullscreen mode

This fetches data but has no way to trigger a panel re-render when the data arrives. The panel renders once with _loading: true and never updates when the fetch completes.

The correct approach: async data fetching belongs inside the entry components, using Preact's useState and useEffect hooks. The components are functional Preact components — they can use hooks, maintain local state, and fetch data asynchronously. When their state changes, they re-render. The panel re-renders the affected entry.


The Solution: Async Fetching in Entry Components

Each level of the cascade is a separate entry component. Each component manages its own loading state, options list, and error state using Preact hooks.

The Full Four-Level Cascade

Here is the complete implementation of all four levels, showing how they connect:

Level 1: Behavior Selection

The first level is synchronous — static options, no async fetching:

function TicketAutoFillBehaviorEntry(props) {
  const { field, getValue, setValue, id } = props;

  // ✅ Static options — no async needed
  const getOptions = () => [
    { value: '', label: '-- None --' },
    { value: 'current_ticket', label: 'Current Ticket' },
    { value: 'another_ticket', label: 'Another Ticket' }
  ];

  return SelectEntry({
    element: field,
    getValue,
    id,
    label: 'Ticket Auto Fill',
    description: 'Auto-fill from ticket data',
    getOptions,
    setValue,
    tooltip: 'Select how to auto-fill this field from ticket data'
  });
}

Enter fullscreen mode Exit fullscreen mode

When this selection changes, the setValue function (from the entry definition) is called. The onChange factory in createTicketAutoFillEntries handles the reset cascade:

const onChange = (key) => (value) => {
  const currentConfig = get(field, ['ticketAutoFillLogic']) || {};
  const newConfig = { ...currentConfig, [key]: value };

  // ✅ Reset cascade when behavior changes
  if (key === 'behavior') {
    if (value === 'current_ticket') {
      // Clear all 'another_ticket' fields
      delete newConfig.ticketFieldKey;
      delete newConfig.ticketType;
      delete newConfig.ticketTypeDetails;
      delete newConfig.ticketPhase;
      delete newConfig.ticketPhaseDetails;
      delete newConfig.fieldName;
      delete newConfig.populateOptions;
      delete newConfig.condition;
    } else if (value === 'another_ticket') {
      // Clear all 'current_ticket' fields
      delete newConfig.currentTicketFieldName;
    } else {
      // None selected — clear everything
      delete newConfig.currentTicketFieldName;
      delete newConfig.ticketFieldKey;
      delete newConfig.ticketType;
      delete newConfig.ticketTypeDetails;
      delete newConfig.ticketPhase;
      delete newConfig.ticketPhaseDetails;
      delete newConfig.fieldName;
      delete newConfig.populateOptions;
      delete newConfig.condition;
    }
  }

  // ✅ Reset downstream when ticket type changes
  if (key === 'ticketType') {
    newConfig.ticketPhase = '';
    newConfig.ticketPhaseDetails = null;
    newConfig.fieldName = '';
  }

  // ✅ Reset field name when phase changes
  if (key === 'ticketPhase') {
    newConfig.fieldName = '';
  }

  return editField(field, 'ticketAutoFillLogic', newConfig);
};

Enter fullscreen mode Exit fullscreen mode

The reset cascade happens in onChange — the function that setValue calls. Every time a selection changes, all downstream selections are cleared. This ensures the panel never shows a stale downstream selection after an upstream change.

Level 2: Ticket Type Selection

function TicketAutoFillTicketTypeEntry(props) {
  const { field, getValue, setValue, id, editField } = props;

  const config = get(field, ['ticketAutoFillLogic']) || {};
  const behavior = config.behavior;

  // ✅ Pattern 3 from Article 11: return null when condition not met
  if (behavior !== 'another_ticket') {
    return null;
  }

  // ✅ Per-level state: loading, options, error
  const [ticketTypes, setTicketTypes] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  // ✅ Fetch on mount — behavior is already 'another_ticket' at this point
  useEffect(() => {
    const fetchTicketTypes = async () => {
      setLoading(true);
      setError(null);

      try {
        const response = await deploymentClient.get('/workflow-engine/process-definitions/', {
          params: {
            limit: 100,
            offset: 0,
            sort_by: 'version',
            sort_order: 'desc',
            latest_version_only: true,
            latest_active_startable_only: true
          }
        });

        const definitions = response.data?.process_definitions || [];

        const options = definitions.map(def => ({
          value: def.id,
          label: def.name || def.key,
          // ✅ Store full object alongside ID
          processData: def
        }));

        setTicketTypes(options);
      } catch (err) {
        setError(err.message);
        notify.error(`Failed to load ticket types: ${err.message}`, 5000);
        setTicketTypes([]);
      } finally {
        setLoading(false);
      }
    };

    fetchTicketTypes();
  }, []); // ✅ Empty deps — fetch once when component mounts

  // ✅ Custom setValue that stores full details, not just the ID
  const handleSetValue = (selectedId) => {
    const selectedOption = ticketTypes.find(opt => opt.value === selectedId);

    if (selectedOption && selectedOption.processData) {
      const currentConfig = get(field, ['ticketAutoFillLogic']) || {};

      // ✅ Use editField directly — updating multiple paths atomically
      // We can't use setValue (which only updates ticketType)
      // because we also need to store ticketTypeDetails
      // and reset downstream selections
      const newConfig = {
        ...currentConfig,
        ticketType: selectedId,
        ticketTypeDetails: selectedOption.processData, // ✅ Full object stored
        // ✅ Reset downstream
        ticketPhase: '',
        ticketPhaseDetails: null,
        fieldName: ''
      };

      editField(field, 'ticketAutoFillLogic', newConfig);
      notify.success(`Selected: ${selectedOption.label}`, 2000);
    } else {
      // Fallback: just update the ID if no processData
      setValue(selectedId);
    }
  };

  const getOptions = () => {
    if (loading) return [];
    if (error) return [{ value: '', label: 'Error loading ticket types' }];
    return [
      { value: '', label: '-- Select Ticket Type --' },
      ...ticketTypes
    ];
  };

  return SearchableSelect({
    element: field,
    getValue,
    id,
    label: 'Ticket Type',
    description: 'Process definition to use',
    getOptions,
    setValue: handleSetValue, // ✅ Custom handler, not raw setValue
    loading,
    placeholder: 'Search ticket types...',
    tooltip: 'Select the ticket type/process definition'
  });
}

Enter fullscreen mode Exit fullscreen mode

Why store ticketTypeDetails? Level 3 — the ticket phase selector — needs to know the ticket type's ID to fetch phases. It already has config.ticketType. But the phase fetch URL requires the ticket type ID, and different API endpoints may use different ID formats. Storing the full processData object means level 3 can extract whatever it needs without making another API call to re-fetch the ticket type.

Why use editField instead of setValue? setValue (from the entry definition) updates only the specific path it was created for — in this case, ['ticketAutoFillLogic', 'ticketType']. But when the ticket type changes, you also need to update ticketTypeDetails, clear ticketPhase, clear ticketPhaseDetails, and clear fieldName. These are five separate schema paths. Calling setValue five times would result in five separate schema updates and five panel re-renders. Using editField directly lets you build the complete new config object and write it in one operation — one schema update, one re-render.

Level 3: Ticket Phase Selection

function TicketAutoFillTicketPhaseEntry(props) {
  const { field, getValue, setValue, id, editField } = props;

  const config = get(field, ['ticketAutoFillLogic']) || {};
  const behavior = config.behavior;
  const ticketType = config.ticketType; // ✅ Depends on level 2's selection

  // ✅ Only show when behavior AND ticketType are set
  if (behavior !== 'another_ticket' || !ticketType) {
    return null;
  }

  // ✅ Per-level state — independent from level 2's loading state
  const [phases, setPhases] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  // ✅ Fetch when ticketType changes
  // ticketType is in the dependency array — re-fetch if it changes
  useEffect(() => {
    if (!ticketType) {
      setPhases([]);
      return;
    }

    const fetchPhases = async () => {
      setLoading(true);
      setError(null);

      try {
        const response = await deploymentClient.get(
          `/camunda/tickets/types/${encodeURIComponent(ticketType)}/phases/`,
          { params: { exclude_form_content: true } }
        );

        const phasesData = response.data?.phases || [];

        const options = phasesData.map(phase => ({
          value: phase.activity_id,
          label: phase.activity_name || phase.activity_id,
          // ✅ Store full activity data for downstream use
          activityData: {
            id: phase.activity_id,
            name: phase.activity_name,
            type: phase.activity_type,
            form_key: phase.form_key
          }
        }));

        setPhases(options);
      } catch (err) {
        setError(err.message);
        notify.error(`Failed to load ticket phases: ${err.message}`, 5000);
        setPhases([]);
      } finally {
        setLoading(false);
      }
    };

    fetchPhases();
  }, [ticketType]); // ✅ ticketType in deps — re-fetch when it changes

  const handleSetValue = (selectedId) => {
    const selectedOption = phases.find(opt => opt.value === selectedId);

    if (selectedOption && selectedOption.activityData) {
      const currentConfig = get(field, ['ticketAutoFillLogic']) || {};

      // ✅ Atomic update: phase + phaseDetails + reset downstream
      const newConfig = {
        ...currentConfig,
        ticketPhase: selectedId,
        ticketPhaseDetails: selectedOption.activityData, // ✅ Store full details
        fieldName: '' // ✅ Reset downstream
      };

      editField(field, 'ticketAutoFillLogic', newConfig);
      notify.success(`Selected: ${selectedOption.label}`, 2000);
    } else {
      setValue(selectedId);
    }
  };

  const getOptions = () => {
    if (loading) return [];
    if (error) return [{ value: '', label: 'Error loading phases' }];
    if (phases.length === 0) return [{ value: '', label: 'No phases available' }];
    return [
      { value: '', label: '-- Select Phase --' },
      ...phases
    ];
  };

  return SearchableSelect({
    element: field,
    getValue,
    id,
    label: 'Ticket Phase',
    description: 'Activity to pull data from',
    getOptions,
    setValue: handleSetValue,
    loading,
    placeholder: 'Search phases...',
    tooltip: 'Select the phase/activity'
  });
}

Enter fullscreen mode Exit fullscreen mode

The useEffect dependency array is critical here. When the designer selects a different ticket type, level 2's handleSetValue calls editField which updates config.ticketType. Level 3's component re-renders because field changed. The useEffect runs again because ticketType in the dependency array is now different. Level 3 fetches phases for the new ticket type. Level 3's options update automatically.

Without ticketType in the dependency array, the effect only runs on mount. If the designer changes the ticket type, level 3 would show stale phases from the previous type.

Level 4: Field Name Selection

function TicketAutoFillFieldNameEntry(props) {
  const { field, getValue, setValue, id } = props;

  const config = get(field, ['ticketAutoFillLogic']) || {};
  const behavior = config.behavior;
  const ticketType = config.ticketType;
  const ticketPhase = config.ticketPhase; // ✅ Depends on level 3's selection

  // ✅ Three conditions — all three upstream levels must be set
  if (behavior !== 'another_ticket' || !ticketType || !ticketPhase) {
    return null;
  }

  const [fieldOptions, setFieldOptions] = useState([]);
  const [loading, setLoading] = useState(false);

  // ✅ Fetch when EITHER ticketType OR ticketPhase changes
  useEffect(() => {
    if (!ticketType || !ticketPhase) {
      setFieldOptions([]);
      return;
    }

    const fetchFormFields = async () => {
      setLoading(true);

      try {
        // ✅ Uses ticketType to identify the process
        const response = await deploymentClient.get(
          `/camunda/tickets/types/${encodeURIComponent(ticketType)}/search-options`
        );

        // ✅ Uses ticketPhase to find the specific activity
        const activities = response.data?.activities || [];
        const selectedActivity = activities.find(act => act.id === ticketPhase);

        if (!selectedActivity) {
          notify.warning(`Activity "${ticketPhase}" not found`, 3000);
          setFieldOptions([]);
          return;
        }

        const formFields = selectedActivity.form_fields || [];
        const options = formFields.map(field => ({
          value: field.key,
          label: field.label || field.key
        }));

        setFieldOptions(options);
      } catch (err) {
        console.error('Failed to fetch form fields:', err);
        notify.error(`Failed to load form fields: ${err.message}`, 5000);
        setFieldOptions([]);
      } finally {
        setLoading(false);
      }
    };

    fetchFormFields();
  }, [ticketType, ticketPhase]); // ✅ Both deps — re-fetch when either changes

  const getOptions = () => {
    if (loading) return [{ value: '', label: 'Loading fields...' }];
    if (fieldOptions.length === 0) return [{ value: '', label: 'No fields available' }];
    return [
      { value: '', label: '-- Select Field --' },
      ...fieldOptions
    ];
  };

  return SearchableSelect({
    element: field,
    getValue,
    id,
    label: 'Field Name',
    description: 'Variable to use for auto-fill',
    getOptions,
    setValue,
    loading,
    placeholder: 'Search fields...',
    tooltip: 'The field variable to populate this field with'
  });
}

Enter fullscreen mode Exit fullscreen mode

Level 4 depends on both ticketType and ticketPhase. When either changes, the fetch re-runs. This means if the designer changes the ticket type, level 3's handleSetValue clears ticketPhase — which causes level 4 to return null immediately (condition: !ticketPhase) and unmount. When the designer selects a new phase in level 3, level 4 mounts again and fetches for the new combination of type and phase.


Why SearchableSelect Is Necessary at Every Level

Ticket types can number in the hundreds across a mature Camunda deployment. A native HTML <select> element with 200 options is unusable — the designer has to scroll through a long list to find what they want.

SearchableSelect (covered in detail in Article 14) provides:

  • A text input to filter options as you type
  • Keyboard navigation (ArrowUp, ArrowDown, Enter, Escape)
  • A loading state that shows "Loading..." while fetching
  • Accessible label association
  • Consistent styling with the rest of the properties panel

For cascading configuration specifically, the loading state is essential. Between the moment a designer selects a ticket type and the moment the phases finish loading, the level 3 component shows its select button with "Loading..." text. Without this, the designer might think the panel is frozen and click again.


The Full Picture: What Happens on Each Selection

Here is the sequence for a complete configuration:

Designer selects behavior: "another_ticket"
  → onChange('behavior')('another_ticket') called
  → ticketType, ticketPhase, fieldName all cleared
  → field schema updated via editField
  → Panel re-renders
  → TicketAutoFillTicketTypeEntry mounts (behavior === 'another_ticket')
  → useEffect fires, API called
  → Ticket types loaded into local state
  → SearchableSelect renders with type options

Designer selects ticket type: "process-123"
  → handleSetValue('process-123') called
  → ticketType = 'process-123', ticketTypeDetails = {full object}
  → ticketPhase = '', ticketPhaseDetails = null, fieldName = ''
  → editField updates schema atomically
  → Panel re-renders
  → TicketAutoFillTicketPhaseEntry mounts (behavior + ticketType set)
  → useEffect fires with ticketType = 'process-123'
  → Phases loaded for process-123
  → TicketAutoFillFieldNameEntry stays null (ticketPhase not set)

Designer selects ticket phase: "activity-456"
  → handleSetValue('activity-456') called
  → ticketPhase = 'activity-456', ticketPhaseDetails = {full object}
  → fieldName = ''
  → editField updates schema atomically
  → Panel re-renders
  → TicketAutoFillFieldNameEntry mounts (all three conditions met)
  → useEffect fires with ticketType + ticketPhase
  → Form fields loaded for process-123, activity-456

Designer selects field name: "assignee"
  → setValue('assignee') called
  → fieldName = 'assignee'
  → schema updated
  → Configuration complete

Designer changes ticket type to "process-789"
  → handleSetValue('process-789') called
  → ticketType = 'process-789'
  → ticketPhase cleared, fieldName cleared  ← Reset cascade
  → editField updates schema atomically
  → Panel re-renders
  → TicketAutoFillTicketPhaseEntry useEffect fires with new ticketType
  → New phases fetched for process-789
  → TicketAutoFillFieldNameEntry returns null (ticketPhase cleared)

Enter fullscreen mode Exit fullscreen mode

The reset cascade and the component-level null checks work together to keep the UI consistent. You can never have a phase selected that belongs to a different ticket type than the one currently selected.


The Minimal Two-Level Cascade Template

If you have a simpler cascading select — for example, a region selector followed by a city selector — here is the minimal template:

// Entry factory — creates both levels
function createRegionCityEntries(field, editField, eventBus) {
  const fieldId = field.id;

  // Helper: update config path
  const onConfigChange = (key) => (value) => {
    const current = get(field, ['my_config'], {});
    const newConfig = { ...current, [key]: value };

    // ✅ Reset city when region changes
    if (key === 'region') {
      newConfig.city = '';
    }

    editField(field, 'my_config', newConfig);
  };

  const getConfigValue = (key) => () => {
    return get(field, ['my_config', key], '');
  };

  return [
    // ✅ Level 1: Region — static options
    {
      id: `region-select-${fieldId}`,
      component: RegionEntry,
      getValue: getConfigValue('region'),
      setValue: onConfigChange('region'),
      field,
      isEdited: () => !!get(field, ['my_config', 'region'])
    },
    // ✅ Level 2: City — dynamic, depends on region
    {
      id: `city-select-${fieldId}`,
      component: CityEntry,
      getValue: getConfigValue('city'),
      setValue: onConfigChange('city'),
      field,
      isEdited: () => !!get(field, ['my_config', 'city'])
    }
  ];
}

// Level 1: Static options — no async needed
function RegionEntry(props) {
  const { field, id, getValue, setValue } = props;

  return SelectEntry({
    element: field,
    getValue,
    id,
    label: 'Region',
    getOptions: () => [
      { value: '', label: '-- Select Region --' },
      { value: 'north', label: 'North' },
      { value: 'south', label: 'South' },
      { value: 'east', label: 'East' },
      { value: 'west', label: 'West' }
    ],
    setValue
  });
}

// Level 2: Dynamic options — async, depends on level 1
function CityEntry(props) {
  const { field, id, getValue, setValue } = props;

  const config = get(field, ['my_config']) || {};
  const region = config.region;

  // ✅ Return null when upstream not set
  if (!region) return null;

  // ✅ Per-level state
  const [cities, setCities] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  // ✅ Fetch when region changes
  useEffect(() => {
    if (!region) {
      setCities([]);
      return;
    }

    const fetchCities = async () => {
      setLoading(true);
      setError(null);
      try {
        const response = await myApiClient.get(`/cities?region=${region}`);
        const data = response.data || [];
        setCities(data.map(city => ({
          value: city.id,
          label: city.name
        })));
      } catch (err) {
        setError(err.message);
        setCities([]);
      } finally {
        setLoading(false);
      }
    };

    fetchCities();
  }, [region]); // ✅ region in deps — re-fetch when it changes

  const getOptions = () => {
    if (loading) return [];
    if (error) return [{ value: '', label: 'Error loading cities' }];
    return [
      { value: '', label: '-- Select City --' },
      ...cities
    ];
  };

  // ✅ SearchableSelect for large option lists
  return SearchableSelect({
    element: field,
    getValue,
    id,
    label: 'City',
    getOptions,
    setValue,
    loading,
    placeholder: 'Search cities...'
  });
}

Enter fullscreen mode Exit fullscreen mode

This two-level template is the foundation. Add more levels by following the same pattern: check upstream conditions at the top (return null if not met), put the dependency in the useEffect array, reset downstream selections in onChange.


The Tradeoffs

Every API call happens in a component, not a service. Ideally, data fetching would happen in a dedicated service class that caches results and manages loading states centrally. In the properties panel context, there's no convenient service layer — you're inside functional Preact components. Moving fetching to the provider class (as a service method) would work but requires passing references through the entire component tree.

No shared cache between component instances. If the designer opens the properties panel for two different fields that both use ticket auto-fill, each renders its own component instances with separate useState for ticket types. Both fetch the ticket types list independently. The simplest fix is a module-level cache:

// Module-level cache — shared across all component instances
let cachedTicketTypes = null;
let cachedTicketTypesPromise = null;

async function getTicketTypes() {
  if (cachedTicketTypes) return cachedTicketTypes;
  if (!cachedTicketTypesPromise) {
    cachedTicketTypesPromise = deploymentClient.get('/workflow-engine/process-definitions/', {
      params: { ... }
    }).then(response => {
      cachedTicketTypes = response.data?.process_definitions || [];
      return cachedTicketTypes;
    });
  }
  return cachedTicketTypesPromise;
}

// In the component:
useEffect(() => {
  setLoading(true);
  getTicketTypes()
    .then(types => setTicketTypes(types.map(...)))
    .catch(err => setError(err.message))
    .finally(() => setLoading(false));
}, []);

Enter fullscreen mode Exit fullscreen mode

I didn't implement this cache in the initial version. It's a straightforward improvement that reduces API calls at the cost of stale data if process definitions change while the panel is open.

The reset cascade is in onChange, not in the component. This means the cascade only runs when the designer changes a value through the properties panel. If the field's schema is modified programmatically (e.g., by a form import or schema migration), the cascade doesn't run and the schema may have inconsistent state — a phase ID that belongs to a different ticket type than the stored type ID. Adding schema validation to the panel open event would catch this.

Loading states per level don't communicate to each other. If level 2 is loading and level 3 tries to render (which shouldn't happen because level 3's null check requires ticketType to be set, and it isn't set until level 2 completes), there's no synchronization mechanism. In practice, level 3 can't render while level 2 is loading because level 2 hasn't called editField yet — ticketType is still empty. The null checks provide the synchronization naturally.


What Comes Next

The cascading configuration UI works because of SearchableSelect — a component that makes hundreds of options navigable. Building SearchableSelect for the properties panel (in Preact, not React) involves specific challenges that don't apply to building it for form renderers.

Article 13 covers SearchableSelect in the Preact properties panel context — keyboard navigation with Preact hooks, the onInput vs onChange difference in Preact, click-outside detection, and why you can't use a React library here even if you've already built one for your form renderers.


This is Part 12 of "Extending bpmn-io Form-JS Beyond Its Limits." The series covers the complete architecture for production-grade Form-JS extensions — the documentation that doesn't exist yet.


Tags: camunda bpmn formjs properties-panel async cascading-select form-editor javascript devex