如何在WhatsApp Flow JSON中实现动态字段管理
实现WhatsApp Flow动态展示选中产品及定制属性的方案
WhatsApp Flow支持通过上下文数据绑定和动态组件遍历实现列表内容的自动渲染,无需手动逐个编写组件。核心思路是将选中的产品集合存入Flow上下文,再在后续界面通过循环生成对应定制组件。
1. 确保SCREEN_ONE正确传递选中产品数组到上下文
在SCREEN_ONE的提交逻辑中,把用户选中的所有产品(包含ID、名称、定制属性配置等信息)存入Flow的context,示例如下:
// SCREEN_ONE的action配置片段 "actions": [ { "type": "navigate", "screen": "SCREEN_TWO", "data": { "selectedProducts": "{{components.productMultiSelector.value}}" // 假设productMultiSelector是多选组件,value返回选中产品的数组 } } ]
需保证selectedProducts为标准数组格式,每个元素包含标识字段和定制属性配置:
[ {"id": "prod_001", "name": "陶瓷咖啡杯", "customFields": ["size", "engraving_text"]}, {"id": "prod_002", "name": "皮质笔记本", "customFields": ["cover_color", "page_count"]} ]
2. 在SCREEN_TWO中用动态遍历渲染定制组件
替换原手动编写的组件,改用forEach循环遍历context.selectedProducts,为每个产品自动生成标题和定制输入项:
{ "name": "SCREEN_TWO", "title": "定制你的订单", "components": [ { "type": "text", "text": "请为选中产品填写定制信息:" }, // 遍历选中产品数组 "{{#forEach context.selectedProducts as product}}", { "type": "text", "text": "*产品:{{product.name}}*" }, // 遍历当前产品的定制字段 "{{#forEach product.customFields as field}}", { "type": "input", "name": "prod_{{product.id}}_{{field}}", "label": "{{field === 'size' ? '尺寸' : field === 'engraving_text' ? '刻字内容' : field === 'cover_color' ? '封面颜色' : '页数'}}", "required": true }, "{{/forEach}}", "{{/forEach}}", { "type": "button", "text": "提交订单", "action": { "type": "submit" } } ] }
3. 关键细节说明
- 动态字段命名:用
prod_{{product.id}}_{{field}}作为输入组件的name,提交时可清晰区分每个产品的定制属性(如prod_prod_001_size对应咖啡杯的尺寸)。 - 差异化定制支持:通过每个产品的
customFields数组,自动渲染对应定制字段,适配不同产品的定制需求。 - 空数据处理:可在SCREEN_TWO开头加入判断,若未选中产品则提示并返回选择界面:
{{#if context.selectedProducts.length === 0}} { "type": "text", "text": "你还未选择任何产品,请返回重新选择。" }, { "type": "button", "text": "返回选择", "action": { "type": "navigate", "screen": "SCREEN_ONE" } } {{/if}}
内容的提问来源于stack exchange,提问作者Md Mahiuddin
相关产品推荐
相关产品推荐

