You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shopware6邮件模板报错:变量order不存在,寻求技术支持

解决Shopware6邮件模板中order变量不存在的问题

问题根源

你当前直接把$order对象赋值给data字段,但Shopware的邮件模板渲染机制要求data是关联数组,模板里的变量需要对应数组中的键名。模板使用{{ order.orderNumber }},就需要data数组里存在'order'这个键,对应的值是你的订单对象。

解决步骤

1. 修正数据传递方式

把原代码里的:

$dataBag->set('data', $order);

替换成:

$dataBag->set('data', [
    'order' => $order
]);

这样模板就能通过order键访问到订单对象的属性了。

2. 确保订单加载必要关联数据

如果后续模板访问order.orderCustomer、order.deliveries这类关联属性时仍报错,要保证查询订单时已经加载了这些关联。比如获取订单时:

// 示例:查询订单时预加载所需关联
$order = $this->orderRepository->search(
    new Criteria([$orderId]),
    (new Context())->enableVersioning()->addExtension(
        'associations',
        new AssociationCollection([
            new Association('orderCustomer'),
            new Association('deliveries', [
                new Association('stateMachineState', [
                    new Association('translated')
                ])
            ])
        ])
    )
)->first();

这样能避免Twig渲染时因关联数据未加载而抛出异常。

3. 核对模板变量命名

确认后台创建的邮件模板里,变量名确实是order,和你传递的键名完全一致,避免拼写错误导致变量无法识别。

修正后的完整代码片段

protected function reminderMail($fname, $email, $order, $context)
{
    $salesChannelConfig = $this->systemConfigService->get('core.defaultSalesChannel');
    $salesChannelId = isset($salesChannelConfig['salesChannel'][0]) ? $salesChannelConfig['salesChannel'][0] : null;

    $mailTemplate = $this->mailTemplateRepository->search(
        (new Criteria(['£££'])), // Search by ID
        $context
    )->get('£££'); // Get the template by ID

    if (!$mailTemplate) {
        throw new \RuntimeException('Mail template not found');
    }

    // Prepare the data bag
    $dataBag = new DataBag();
    $recipients = [
        $email => $fname,
        // Add more recipients as needed
    ];
    $dataBag->set('recipients', $recipients);
    $dataBag->set('senderName', 'Your Sender Name');
    $dataBag->set('contentHtml', $mailTemplate->getContentHtml());
    $dataBag->set('contentPlain', $mailTemplate->getContentPlain());
    $dataBag->set('subject', $mailTemplate->getSubject());
    $dataBag->set('salesChannelId',  $salesChannelId);

    // 修正:将order放入关联数组中传递
    $dataBag->set('data', [
        'order' => $order
    ]);

    // Send the email
    $this->mailService->send($dataBag->all(), $context);
}

内容的提问来源于stack exchange,提问作者chap man

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 07:05:53