如何在Shopware 6应用中将结账页自定义输入字段保存到订单
解决Shopware 6应用集成场景下保存结账自定义字段到订单的方案
1. 给订单添加自定义字段(存储容器)
首先需要为订单实体创建自定义字段来存储输入值,有两种实现方式:
- 后台手动配置:进入Shopware后台 → 设置 → 自定义字段 → 新建字段集,绑定到「订单」实体,添加文本类型字段
some_info_text。 - 应用Manifest自动创建:在应用的
manifest.xml中添加以下配置,安装应用时会自动生成对应字段:
<custom-fields> <custom-field-set name="order_custom_info" label="订单自定义信息" entity="order"> <custom-field name="some_info_text" type="text" label="自定义信息文本"/> </custom-field-set> </custom-fields>
2. 确保前端字段数据被提交到订单接口
你已经在Twig模板中添加了输入框,现在需要保证字段值能随结账请求一起提交到/checkout/order端点。可以通过自定义JavaScript拦截表单提交,追加字段数据:
创建src/Resources/app/storefront/src/js/custom-checkout.js文件:
document.addEventListener('DOMContentLoaded', () => { const checkoutForm = document.querySelector('form[data-form-id="confirm-shipping"]'); if (!checkoutForm) return; checkoutForm.addEventListener('submit', (e) => { e.preventDefault(); const inputValue = document.getElementById('some_info_text').value; const formData = new FormData(checkoutForm); formData.append('some_info_text', inputValue); fetch(checkoutForm.action, { method: 'POST', body: formData, headers: {'X-Requested-With': 'XMLHttpRequest'} }).then(response => { response.ok ? window.location.href = response.url : console.error('结账请求失败'); }); }); });
然后在manifest.xml中注册该JS文件,确保它在前台加载:
<assets> <asset path="src/Resources/app/storefront/src/js/custom-checkout.js" type="storefront" /> </assets>
3. 用App Scripts将字段值写入订单自定义字段
应用无法使用PHP事件订阅者,可借助Shopware的App Scripts监听订单创建事件,完成值的存储:
创建src/Resources/scripts/order/save-custom-field.twig文件:
{% block event %}checkout.order.placed{% endblock %} {% block priority %}100{% endblock %} {% set inputValue = request.request.get('some_info_text') %} {% if inputValue %} {% do order.customFields.set('some_info_text', inputValue) %} {% do order.save() %} {% endif %}
再在manifest.xml中注册这个脚本:
<scripts> <script name="save-order-custom-data" path="src/Resources/scripts/order/save-custom-field.twig" type="storefront" /> </scripts>
验证流程
- 更新应用后,确认订单的自定义字段已成功创建。
- 在结账页面输入自定义字段内容,完成下单流程。
- 进入后台查看对应订单的自定义字段,确认值已保存。
内容的提问来源于stack exchange,提问作者Ivan Kuzmin
相关产品推荐
相关产品推荐

