Shopware 6自定义插件:如何通过customer的created_by_id获取用户姓名?
Shopware 6扩展sw-customer-base-info展示创建客户的用户信息
步骤1:修改index.js实现数据获取
我们需要在组件中添加数据存储、获取当前客户的创建者ID,再通过ID查询用户信息,最终让数据能在模板中调用:
import template from './sw-customer-base-info.html.twig'; const { Criteria } = Shopware.Data; Shopware.Component.override('sw-customer-base-info', { inject: ['repositoryFactory'], template, // 定义存储创建者信息的变量 data() { return { createdUser: null }; }, computed: { userRepository() { return this.repositoryFactory.create('user'); }, // 继承原组件的customer属性,确保能获取当前客户对象 customer() { return this.$super('customer'); } }, // 异步钩子中处理数据查询 async created() { // 调用原组件的created逻辑,避免破坏原有功能 this.$super('created'); // 1. 获取当前客户的创建者ID const createdById = this.customer?.createdBy; if (!createdById) return; try { // 2. 构造查询条件,只获取需要的字段(减少数据量) const criteria = new Criteria(); criteria.setFields(['firstName', 'lastName']); // 通过ID查询对应用户信息 this.createdUser = await this.userRepository.get( createdById, Shopware.Context.api, criteria ); } catch (error) { console.error('获取创建者信息失败:', error); } } });
步骤2:修改模板文件展示数据
在sw-customer-base-info.html.twig中,继承原组件内容并添加创建者信息的展示:
{% block sw_customer_base_info_content %} {{ parent() }} {# 展示创建者姓名,仅当数据存在时显示 #} {% if createdUser %} <div class="sw-customer-base-info__field"> <label class="sw-field__label">创建者</label> <div class="sw-field__content"> {{ createdUser.firstName }} {{ createdUser.lastName }} </div> </div> {% endif %} {% endblock %}
关键细节说明
- 字段映射规则:Shopware实体采用驼峰命名,数据库的
created_by_id对应实体属性createdBy,first_name对应firstName,last_name对应lastName,要注意命名匹配。 - 继承原组件属性:通过
this.$super('customer')继承原组件的客户对象,避免override后丢失原有数据。 - 性能优化:使用
criteria.setFields()指定仅获取需要的字段,减少接口返回的数据量。 - 错误处理:添加
try-catch捕获查询异常,防止组件因接口请求失败而崩溃。
内容的提问来源于stack exchange,提问作者Auhona
相关产品推荐
相关产品推荐

