FormioJS:如何从data.custom向Select组件返回值及排障
Fixing FormioJS Select Component Custom Data Source Not Populating Values
Let's break down why your data.custom function isn't populating the Select component with values, and fix it step by step.
The Core Issues in Your Current Setup
- Incorrect Function Parameters: FormioJS passes specific arguments to custom data functions, not the
valuesandmyou're expecting. - Misplaced Value Assignment: Assigning a new array to the
valuesparameter won't work—you need to directly return the option array from the function. - Potential Context Access: Your
getModelsfunction might not be accessible in Formio's execution context.
Step 1: Define the Correct Custom Function
First, update your getModels function to match Formio's expected signature and behavior. Formio passes component (current select component object), data (full form's current values), filter, and update as arguments.
// Make the function globally accessible (Formio runs custom code in the global context) window.getModels = function(component, data) { // Get the selected manufacturer from the form data const selectedManufacturer = data.manufacturer; // Generate model options based on the selected manufacturer let modelOptions = []; // Replace this with your actual data logic if (selectedManufacturer === 'toyota') { modelOptions = [ { label: 'Camry', value: 'camry' }, { label: 'Corolla', value: 'corolla' } ]; } else if (selectedManufacturer === 'honda') { modelOptions = [ { label: 'Civic', value: 'civic' }, { label: 'Accord', value: 'accord' } ]; } // Critical: Return the option array directly—this is what Formio uses to populate the select return modelOptions; };
Step 2: Update the Select Component Configuration
Adjust your Model select component to pass the correct arguments and remove unnecessary properties:
{ type: 'select', label: 'Model', key: 'model', placeholder: 'Select your model', refreshOn: 'manufacturer', // This ensures the function re-runs when manufacturer changes dataSrc: 'custom', data: { custom: 'getModels(component, data)' // Pass the arguments Formio expects }, // Remove selectValues: it's not needed when returning { label, value } objects directly defaultValue: '' }
Key Checks to Ensure It Works
- Console Debugging: Add
console.log(selectedManufacturer)insidegetModelsto confirm you're receiving the correct manufacturer value when the select refreshes. - Global Access: Make sure
getModelsis attached towindow(or available in Formio's execution context) — otherwise, Formio will throw a "function not defined" error. - Option Format: Double-check that each option in your returned array has both
label(display text) andvalue(hidden stored value) properties. Formio relies on these fields to render options correctly.
内容的提问来源于stack exchange,提问作者Alexey Udovydchenko
相关产品推荐
相关产品推荐

