Skip to content

Block used in new order email template does not pass data

I’m trying to call a block in the template notifying me that an order has been placed in the store, but the value of order or orderId is not passed through so I can’t retrieve the Order object in the block.

Interestingly, by adding the name attribute value with the order_sms value as a test, I can handle it in the .phtml file

{{block class="MagentoFrameworkViewElementTemplate" order=$order name="order_sms" template="Kcode_Emails::email/new_order.phtml" area="frontend"}}

registration.php

use MagentoFrameworkComponentComponentRegistrar;

ComponentRegistrar::register(
    ComponentRegistrar::MODULE,
    'Kcode_Emails',
    __DIR__
);

/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Kcode_Emails" setup_version="1.0.0"/>
</config>

email_template.xml

<block class="KcodeEmailsBlockNewOrder"
       name="order_sms"
       template="Kcode_Emails::email/new_order.phtml"
       area="frontend">
    <arguments>
        <argument name="orderId" xsi:type="string">000000129</argument>
    </arguments>
</block>

/Block/NewOrder.php

<?php

namespace KcodeEmailsBlock;

use MagentoFrameworkViewElementTemplate;
use MagentoSalesApiOrderRepositoryInterface;

class NewOrder extends Template
{
    protected $orderRepository;
    protected $orderId;

    public function __construct(
        TemplateContext $context,
        OrderRepositoryInterface $orderRepository,
        array $data = []
    ) {
        $this->orderRepository = $orderRepository;
        $this->orderId = $orderId;
        parent::__construct($context, $data);
    }

    public function getOrder()
    {
        if ($this->orderId) {
            return $this->orderRepository->get($this->orderId);
        }
        return null;
    }

    public function getOrderId()
    {
        return $this->orderId;
    }
}

/view/frontend/templates/email/new_order.phtml

<?php
$order = $block->getOrder();
$orderId = $block->getOrderId();
?>
nr zamowienia: <?= $orderId; ?>

<?php if ($order): ?>
    <p>Order ID: <?= $order->getEntityId(); ?></p>
    <p>Customer Name: <?= $order->getCustomerFirstname() . ' ' . $order->getCustomerLastname(); ?></p>
<?php else: ?>
    <p>Order is null</p>
<?php endif; ?>