Toggle Panel Controller

Control native Toggle panels from a temporary variable: -1 expands all, 0 collapses all, 1..N opens one position, and text such as 2,3 or 1,5 opens multiple selected panels. Includes a full setup guide and example configuration.

Custom CodeUI Design & LayoutsYeeflow
TogglePanel navigationTemporary variablesExpand allCollapse allApproval forms

What this template helps teams build

Required placement — read before setup

REQUIRED: Custom Code and Toggle must be at the same layout level, preferably as sibling controls inside one Container. Different nested levels can prevent the controller from working. Keep the Custom Code outside the Toggle panels.

See it in action

Animated illustration: 2 opens the second panel; 2,3 opens the second and third; 1,5 opens the first and fifth; -1 expands all; 0 collapses all.

Illustrated interaction demo. Use a text-capable temporary variable for multiple positions such as 2,3 or 1,5. The controller and Toggle must share a layout level or Container.

Control panel expansion by position

Keep native Toggle panels and field bindings. A nonvisual Custom Code control reads a temporary-variable value and triggers the native expansion handlers.

Value mapping

-1 expands all panels. 0 collapses all panels. Positive integers 1..N open only that one-based top-to-bottom position. Text such as 2,3 or 1,5 opens exactly those selected positions and closes the others. Empty and invalid values leave the current state unchanged. Out-of-range positive positions do not change any panel.

Setup requirements

REQUIRED PLACEMENT: put the Custom Code and native Toggle at the same layout level, preferably as sibling controls inside one Container. Different nested levels can prevent the controller from working. Keep the controller outside the Toggle panels. Use Classic layout and assign a unique CSS ID. For multiple positions, use a text-capable temporary variable. Bind activePanelIndex to the temporary variable value. The downloadable guide covers Single select and button assignment, load defaults, display rules, repeated values, limitations and troubleshooting.

Runtime verification

Browser preview verified on an Approval form with three panels for -1, 0, 1, 2, 3 and multiple selection 2,3. Multiple selected positions (including 2,3 and 1,5), a fifth panel, duplicate/order normalization and atomic rejection of unavailable positions have local regression coverage. Other hosts and clients require their own runtime verification. This is a DOM integration that must be retested after UI upgrades.

Build patterns behind this template

Use this template as a reference while reviewing the Custom Code developer guide. Learn how the required export structure, input parameters, and rendering patterns fit together.

Code preview

Download source file
import * as React from 'react';

// Custom Code CONTROL source. Paste into Code editor, not a Form Action step.
// Bind activePanelIndex to the VALUE of Temp variables > ActivePanelIndex.
// Place this control and the Toggle at the same level, preferably siblings in one Container.
// Keep it outside the Toggle panels and conditionally hidden containers.
// Classic layout: -1 opens all; 0 closes all; 1..N selects one; "2,3" selects several.
// Empty/invalid commands leave the current state unchanged.

interface ToggleControllerProps {
  cssId: string;
  command: string;
}

function unwrap(value: any): any {
  for (var depth = 0; depth < 5 && value && typeof value === 'object'; depth++) {
    if (Array.isArray(value)) return value;
    if (Object.prototype.hasOwnProperty.call(value, 'value')) value = value.value;
    else if (Object.prototype.hasOwnProperty.call(value, 'Value')) value = value.Value;
    else return null;
  }
  return value;
}

function panelCommand(value: any): string {
  value = unwrap(value);
  if (value === null || value === undefined || typeof value === 'boolean') return '';
  var parts: any[];
  if (Array.isArray(value)) parts = value;
  else if (typeof value === 'string') parts = value.split(/[,,]/);
  else if (typeof value === 'number') parts = [value];
  else return '';
  if (!parts.length) return '';
  var positions: number[] = [];
  for (var i = 0; i < parts.length; i++) {
    var part = unwrap(parts[i]);
    if (typeof part !== 'string' && typeof part !== 'number') return '';
    if (typeof part === 'string' && part.trim() === '') return '';
    var position = Number(part);
    if (!isFinite(position) || Math.floor(position) !== position || position < -1) return '';
    // -1 and 0 are complete commands; never mix them with panel positions.
    if (position <= 0) return parts.length === 1 ? String(position) : '';
    if (positions.indexOf(position) < 0) positions.push(position);
  }
  return positions.sort(function (a, b) { return a - b; }).join(',');
}

class ToggleController extends React.Component<ToggleControllerProps, {}> {
  private marker: HTMLSpanElement | null = null;
  private timer: any = null;
  private mounted = false;
  private attempts = 0;

  componentDidMount() {
    this.mounted = true;
    this.start();
  }

  componentDidUpdate(previous: ToggleControllerProps) {
    if (previous.command !== this.props.command || previous.cssId !== this.props.cssId) {
      this.start();
    }
  }

  componentWillUnmount() {
    this.mounted = false;
    this.cancel();
  }

  private cancel() {
    if (this.timer !== null) clearTimeout(this.timer);
    this.timer = null;
  }

  private start() {
    this.cancel();
    this.attempts = 0;
    if (!this.props.command) return;
    // Restrict the configurable ID so it can safely be used as a CSS selector.
    if (!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(this.props.cssId)) {
      console.warn('[Toggle controller] Use a CSS ID such as approval-toggle.');
      return;
    }
    var self = this;
    // Wait until React has committed the sibling controls.
    this.timer = setTimeout(function () { self.tick(); }, 0);
  }

  private findTarget(): HTMLElement | null {
    if (!this.marker) return null;
    // Use the closest shared container so Designer/Preview duplicate IDs do not
    // accidentally cause this instance to operate on the other form instance.
    var scope: HTMLElement | null = this.marker.parentElement;
    while (scope) {
      var matches = scope.querySelectorAll('#' + this.props.cssId);
      if (matches.length === 1) return matches[0] as HTMLElement;
      if (matches.length > 1) return null;
      scope = scope.parentElement;
    }
    return null;
  }

  private headers(root: HTMLElement): HTMLElement[] {
    var collapse: Element | null = null;
    var result: HTMLElement[] = [];
    for (var i = 0; i < root.children.length; i++) {
      if (root.children[i].classList.contains('ant-collapse')) {
        collapse = root.children[i];
        break;
      }
    }
    if (!collapse) return result;
    for (var itemIndex = 0; itemIndex < collapse.children.length; itemIndex++) {
      var item = collapse.children[itemIndex];
      if (!item.classList.contains('ant-collapse-item')) continue;
      for (var childIndex = 0; childIndex < item.children.length; childIndex++) {
        var child = item.children[childIndex];
        if (child.classList.contains('ant-collapse-header')) {
          result.push(child as HTMLElement);
          break;
        }
      }
    }
    return result;
  }

  private apply(): boolean {
    var root = this.findTarget();
    if (!root) return false;
    var headers = this.headers(root);
    var command = this.props.command;
    if (!headers.length || !command) return false;
    var positions = command.split(',').map(function (part) { return Number(part); });
    // Validate the whole selection before changing anything: "1,99" must not
    // partially apply if the 99th panel does not exist.
    if (command !== '-1' && command !== '0') {
      for (var p = 0; p < positions.length; p++) {
        if (positions[p] < 1 || positions[p] > headers.length) return false;
      }
    }
    // Use native handlers, not CSS overrides. Classic layout supports several
    // open panels, while positive single values still close unselected panels.
    for (var i = 0; i < headers.length; i++) {
      var shouldOpen = command === '-1' || (command !== '0' && positions.indexOf(i + 1) >= 0);
      var isOpen = headers[i].getAttribute('aria-expanded') === 'true';
      if (shouldOpen !== isOpen) {
        headers[i].click();
        return false;
      }
    }
    return true;
  }

  private tick() {
    this.timer = null;
    if (!this.mounted) return;
    this.attempts++;
    try {
      if (this.apply()) return;
    } catch (error) {
      console.warn('[Toggle controller] Could not switch panel.', error);
      return;
    }
    // Bounded retries for initial mounting/animation; never continually enforce
    // the variable after success, so manual panel selection remains usable.
    if (this.attempts >= 50) {
      console.warn('[Toggle controller] Panel command did not complete within 5 seconds. Check CSS ID, panel positions, Classic layout, same-level placement and visibility rules.');
      return;
    }
    var self = this;
    this.timer = setTimeout(function () { self.tick(); }, 100);
  }

  render() {
    return <span aria-hidden="true" style={{ display: 'none' }}
      ref={(node) => { this.marker = node; }} />;
  }
}

export class CodeInApplication implements CodeInComp {
  description() { return 'Control one, several or all native Toggle panels from a temporary-variable value.'; }
  requiredFields(params?: any) { return []; }
  inputParameters() {
    return [
      { id: 'toggleCssId', type: 'string', desc: 'Toggle CSS ID, without #: approval-toggle' },
      { id: 'activePanelIndex', type: 'variable', desc: 'Bind a temporary-variable value. Classic layout: -1 opens all; 0 closes all; 1..N selects one position; text "2,3" or "1,5" opens exactly those positions.' }
    ];
  }
  render(context: any, fieldsValues: any, readonly: boolean) {
    var params = context.params || {};
    var cssId = String(unwrap(params.toggleCssId) || 'approval-toggle').trim().replace(/^#/, '');
    return <ToggleController cssId={cssId} command={panelCommand(params.activePanelIndex)} />;
  }
}

User guide

Download guide

Toggle Panel Controller

Version: 1.1.0

REQUIRED PLACEMENT — READ BEFORE SETUP The Custom Code control and the native Toggle must be at the same layout level. The recommended setup is to place both as siblings inside the same Container. Putting the controller at a different nested layout level can prevent it from locating and controlling the Toggle. Keep the controller outside the Toggle panels.

Recommended structure:

Container
├── Custom Code: Toggle Panel Controller
└── Toggle: approval-toggle
    ├── First panel
    ├── Second panel
    └── Further panels...

Animated interaction demo

Animated illustration of commands 2, 2,3, 1,5, -1 and 0 controlling five Toggle panels

This illustrated demo shows the command-to-panel relationship. It contains no customer data. The native three-panel Approval form preview separately verified multiple selection 2,3 and the original numeric commands; the five-panel combinations have local regression coverage.

What this template does

Control an existing native Yeeflow Toggle from the value of a temporary variable. Expand one panel by its position, open a selected set with comma-separated positions such as 2,3 or 1,5, expand all panels with -1, or collapse all panels with 0. The template keeps your existing native panels, fields and field bindings. It adds a nonvisual Custom Code control that triggers the Toggle's native expand/collapse interaction.

Use it for guided approval forms, opening the section relevant to a selected request type, showing a section after validation, and adding Expand all / Collapse all commands to a long form.

Supported placement and verification

  • Place it in a Custom Code control on an Approval form, at the same layout level as the target Toggle, preferably as siblings inside one Container. Keep it outside the Toggle panels and outside conditionally hidden containers.
  • Browser preview verified on 2 December 2026 with three panels, a Single select, a button action and a temporary variable: -1, 0, 1, 2 and 3 produced the expected expansion states. Version 1.1.0 additionally verified text 2,3 opening the second and third panels together, followed by regression checks for 2, -1 and 0. Multiple positions including 1,5 have five-panel local regression coverage.
  • More than three panels are supported by the positional algorithm; validate your actual panel count and display rules before release.
  • Data list forms, dashboards, mobile clients and other product versions require separate runtime verification.
  • This file is a Custom Code control with render(...). It is not a Form Action Custom Code step with execute(...).

Value-to-panel mapping

Let N be the number of top-level panel items present in the target Toggle's rendered structure.

Value passed to activePanelIndexResult
-1Expand all N panels. Requires the Toggle's Classic layout.
0Collapse all panels.
1Expand only the first panel, at the top. Collapse the other panels.
2Expand only the second panel. Collapse the other panels.
3Expand only the third panel. Collapse the other panels.
4 through NExpand only the panel at that one-based position. For example, 4 selects the fourth panel and 5 selects the fifth panel, if those panels exist.
Text 2,3Expand exactly the second and third panels; collapse the others.
Text 1,5Expand exactly the first and fifth panels, if both exist; collapse the others.
Text 1,3,5Expand exactly those three positions. Any nonempty selection of existing positive positions is supported.
Empty, null or undefinedLeave the current expansion state unchanged.
Invalid inputLeave the current expansion state unchanged. Invalid examples include -2, 1.5, abc, Boolean values, an empty list entry (2,) and mixing special commands with positions (-1,2 or 0,3).
Any requested position greater than NThe entire command is left unapplied: 1,99 does not partially open the first panel. No panel is changed. The controller retries for up to approximately five seconds, then logs a warning.

Positions are one-based, not zero-based. 0 is a command to collapse all; it never means the first panel. -1 is a command to expand all; it never means the last panel.

Use position, not title or ID. If the second panel is titled “Financial Review”, pass 2, not Financial Review, Panel2, a control ID or a workflow variable name. Renaming a panel does not affect its position. Reordering or adding/removing panels changes the position mapping.

Numbers and numeric text are accepted: 2 and "2" select the same position. For multiple panels, use a temporary variable that can hold text, for example 2,3. A numeric-only variable cannot represent a comma-separated selection.

Use English commas (,); Chinese commas (,) and surrounding spaces are also accepted. Duplicate positions are removed, and positions are sorted for comparison: 3,2,2 has the same effect as 2,3. Advanced expression inputs may supply a numeric array such as [2,3]; a literal JSON string "[2,3]" is not supported. -1 and 0 must each be used alone.

Input parameters

ParameterParameter typeRequiredConfigure withExample
toggleCssIdPlain stringRecommended; defaults to approval-toggleThe unique CSS ID of the native Toggle controlapproval-toggle
activePanelIndexVariable / expression inputYes, to issue a commandThe current value of a temporary variable or expression: one integer or text containing comma-separated positionsSelect Temp variables → ActivePanelIndex

toggleCssId

In the Toggle's properties, open Advanced → Advanced → CSS ID and enter a unique ID. Enter that same ID in this parameter. Use letters, digits, hyphens or underscores, starting with a letter or underscore. Recommended: approval-toggle.

Enter the ID without #. A leading # is tolerated, but it is not needed. Use the CSS ID, not the CSS classes field, panel title or immutable designer control ID. Give every separately controlled Toggle its own unique CSS ID.

activePanelIndex

Open the parameter's expression/variable selector and choose the temporary variable. The script expects its evaluated value, such as 2, -1, or text 2,3. For 1,5, the Toggle must have at least five top-level panel items.

Do not enter the literal text ActivePanelIndex, __temp_ActivePanelIndex, or Temp variables:ActivePanelIndex into a plain-text box. Those strings name a variable; they are not its current numeric value. Select the variable through the editor.

The temporary variable is read-only from this controller's perspective. Your form actions assign it. The controller does not write business fields or write a selected panel back to the variable.

Step-by-step setup

1. Configure the existing Toggle

  1. Select the native Toggle containing the panels you want to control.
  2. Set Layout → Layout = Classic. Accordion allows only one expanded panel and cannot implement -1 correctly.
  3. Set its CSS ID to a unique value such as approval-toggle.
  4. Keep the existing panel contents and field bindings.
  5. Record the positions from top to bottom. For example: Applicant = 1, Financial Review = 2, Attachments = 3.

The native Active by default option remains a separate initial-state setting. This controller changes the expansion state when it receives a valid command. If no command is supplied, it leaves the native state unchanged.

2. Create the temporary variable

Create a temporary variable named ActivePanelIndex, or use an existing meaningful name. This name is an example, not a hard-coded requirement. Use a text-capable value when you need multiple positions, such as 2,3 or 1,5. Bind your chosen variable to the input parameter.

3. Add a separate Custom Code control

  1. Add a new Custom Code control outside the Toggle, preferably just before it in the form.
  2. Put the Custom Code control and the target Toggle at the same layout level. The recommended arrangement is to put both as siblings inside one Container. Keeping them somewhere on the same form/page is not sufficient; different nested levels can prevent control from working.
  3. Do not place it inside one of the collapsible panels or hide its host container using display rules. The component must mount to run; its own rendered marker is already nonvisual.
  4. Open Code editor and paste the entire toggle-panel-controller.tsx file into the source editor.
  5. Save and exit the code editor. Complete any compilation or save steps required by your product version.
  6. Preserve other existing Custom Code controls that perform unrelated work.

4. Bind the input parameters

Set toggleCssId to approval-toggle. For activePanelIndex, use the expression editor to select Temp variables → ActivePanelIndex.

5. Configure a Single select and a button

For a three-panel example, give the Single select the values -1, 0, 1, 2, 3, and 2,3. For a five-panel form, add 4, 5, 1,5, or other desired combinations. Each multi-panel option must store the complete text command (for example 2,3), rather than only a display label.

Configure the button to execute a form action containing Set variables:

Action settingCorrect configuration
Execution ConditionLeave empty unless you intentionally need a Boolean execution condition. Do not put ActivePanelIndex here as the assignment target.
Assignment modeSingle Value
VariableUse the variable selector to choose Temp variables → ActivePanelIndex. Do not leave the destination blank.
ValueUse the expression editor to select the Single select's associated workflow/form variable.

The data flow is: Single select value → button's Set variables action → temporary variable value → Custom Code input → native Toggle state.

Changing the Single select alone does not assign the temporary variable in this example. Press the button after choosing a value. Alternatively, use the Single select's change event to execute the same assignment action.

6. Set an initial panel, if required

In the form's load action, assign 2 to the temporary variable to open the second panel on initial load. Assign text 2,3 to start with two panels expanded, -1 to start with all panels expanded, or 0 to start with all panels collapsed. A declared but unassigned temporary variable does not issue a command.

The controller briefly retries while sibling controls mount. If the target is unavailable for approximately five seconds, make it available and issue a new command after it appears.

7. Preview and verify

  1. Select 2, press the button, and confirm only the second panel is expanded.
  2. Select -1, press the button, and confirm all panels are expanded.
  3. Select 0, press the button, and confirm all panels are collapsed.
  4. Select text 2,3, press the button, and confirm exactly the second and third panels are expanded. In a form with at least five panels, also test 1,5.
  5. Test 1, 3, and every additional valid position in your actual form.
  6. Verify the display rules, narrow-screen layout and relevant readonly views you intend to support.
  7. Save the form design after verification. Publishing the workflow is a separate release step.

Expected interaction behavior

The controller reacts on mount and when the normalized command or target CSS ID changes. 2,3 opens exactly those positions and closes all unselected positions. It checks native aria-expanded state and only clicks headers that need changing. In Classic layout, a positive position still closes the other panels programmatically.

After a command completes, users can manually expand or collapse panels. The controller does not continuously force the variable's state. Consequently, assigning the same value again may not reapply the command, because the input did not change. To reissue a command after manual changes, assign a genuinely different command first and then the required command in a separate completed update. Changing only the order (2,3 to 3,2) or adding duplicates does not create a new command. There is no refresh-token input in this version.

Manual panel clicks do not update ActivePanelIndex. It is a command value, not a live report of the current panel state. In Classic layout, users can manually keep multiple panels open.

Multiple Toggles

Use one controller per Toggle, each with a different CSS ID and normally a different temporary variable. For example, request-toggle with RequestPanelIndex, and review-toggle with ReviewPanelIndex. Do not attach two competing controllers to the same Toggle.

Business examples

  • Purchase approval: 1 opens requester details, 2 opens budget review, and 3 opens supporting documents. -1 shows the entire request for a final review.
  • Validation guidance: after determining which section contains an issue, assign its numeric position so the user sees that section, or a comma-separated list to open several sections with issues.
  • Review tools: separate Expand all and Collapse all buttons assign -1 and 0 directly, without a Single select.

Limitations and maintenance

  • This is a DOM integration with the current native Toggle, not a documented product API for controlling its state. It uses .ant-collapse, .ant-collapse-item, .ant-collapse-header and aria-expanded. Retest after Yeeflow UI upgrades.
  • Panel positions follow top-level panel items present in the rendered structure. The code does not maintain a persistent mapping to panel titles or IDs. Dynamic removal can shift positions; CSS-hidden items may still occupy a position. Validate every relevant display-rule state or keep the panel structure stable.
  • -1 expands the available native panel states; it does not override visibility rules or expose panels hidden by those rules.
  • Retries are bounded to approximately five seconds. The controller stops after success or timeout. It does not automatically resume when a hidden or delayed panel becomes available later.
  • The control changes presentation only. It does not submit the form, change workflow state, modify field values, grant access or provide data security.
  • The code does not disable itself in readonly views because expanding a panel is a viewing action; verify the readonly host you use.
  • This version uses React class components compatible with the documented Yeeflow runtime pattern and loads no external scripts or styles.

Troubleshooting

SymptomCheck
Button has no effectConfirm the action has a selected Variable destination, its Value reads the Single select, and Execution Condition is not accidentally used as the destination.
Variable changes but Toggle does notFirst confirm the Custom Code and Toggle are at the same layout level, preferably siblings in the same Container. Then check the evaluated variable binding, exact CSS ID and that both controls are mounted.
-1 or 2,3 only opens one panel, or panels keep switchingSet the native Toggle layout to Classic, not Accordion.
2,3 is not accepted by the variableUse a text-capable temporary variable and pass the whole text command through the expression binding. Do not use a numeric-only variable.
The wrong panel opensCount from 1 at the top; check reordered panels and dynamic display rules. Titles do not determine the index.
Empty value unexpectedly does nothingExpected: empty input leaves the current state unchanged. Use 0 to collapse all.
Repeatedly pressing the button does not restore a manually changed stateAn unchanged value is not a new command. Change the input value before reissuing it.
Warning about unavailable panel after five secondsCheck that the target exists, every requested position is within 1..N (or use standalone -1/0), CSS ID is unique, and display rules allow the target to mount.
Preview works but a different client does notValidate that client's native Toggle DOM and Custom Code runtime; other hosts are not covered by the Approval form preview proof.

Example configuration

Download config

Toggle Panel Controller — example configuration

Required placement: Put the Custom Code and native Toggle at the same layout level. Recommended: both are sibling controls inside one Container. A controller at a different nested level may not work even when its CSS ID and variable binding are correct.

Container
├── Custom Code: Toggle Panel Controller
└── Toggle: approval-toggle

Three-panel approval form

Panel positionExample titleCommand value
FirstRequester details1
SecondFinancial review2
ThirdSupporting documents3

Multiple panels: text 2,3 = expand the second and third panels only. With five or more panels, text 1,5 = expand the first and fifth only. Special commands: -1 = expand all; 0 = collapse all. A fourth panel, if added, uses 4; further panels use their one-based position through N.

Native Toggle

  • Layout: Classic.
  • CSS ID: approval-toggle.
  • Keep all existing fields inside their original panels.

Temporary variable

  • Name: ActivePanelIndex (example; another meaningful name is allowed).
  • Value source: form actions or an expression assignment.
  • Values: one integer, numeric text, or comma-separated positive positions. Use a text-capable temporary variable for 2,3 and 1,5.

New Custom Code control

  • Placement: same layout level as the Toggle, preferably sibling controls inside the same Container on the Approval form; outside the Toggle panels and any hidden container.
  • Source: the complete toggle-panel-controller.tsx file, entered in Code editor.
Input parameterValue/binding
toggleCssIdPlain text: approval-toggle
activePanelIndexExpression selector: Temp variables → ActivePanelIndex

Single select and button

Single select values: -1, 0, 1, 2, 3, 2,3. In a form with five panels, also add 4, 5, 1,5. Store each multi-panel value as the complete comma-separated text command.

Button action: Set variables → Single Value.

SettingConfiguration
Execution ConditionEmpty, unless a deliberate Boolean condition is required
VariableSelect Temp variables → ActivePanelIndex
ValueSelect the Single select's actual associated form/workflow variable

The associated Single select variable depends on your form; select it from the editor instead of copying a sample variable ID.

Initial state

In a form load action, optionally assign 2 to ActivePanelIndex to open Financial review on load. Use -1 to start expanded or 0 to start collapsed. An empty value leaves the native state unchanged.

Direct command buttons

For separate Expand all / Collapse all buttons, assign constants directly:

ButtonDestinationValue
Expand allTemp variables → ActivePanelIndex-1
Collapse allTemp variables → ActivePanelIndex0
Review financialsTemp variables → ActivePanelIndex2
Review financials and documentsTemp variables → ActivePanelIndexText 2,3
Review first and fifth sections (five panels required)Temp variables → ActivePanelIndexText 1,5

Acceptance checks

Choose, then press buttonExpected expanded panels
2Second only
Text 2,3Second and third only
-1First, second and third
0None
3Third only
1First only
-1All three again
Text 1,5 in a five-panel formFirst and fifth only
Text 1,99 when panel 99 does not existNo changes; no partial application

After a command, manual clicks remain available. The variable is a command, not live state. Reassigning the same value does not necessarily issue a new command. This is not a Form Action Custom Code step, and it does not submit the form or change business data.