How do I include data from the order item type fields in the order receipt email?
質問
I have created an "Event Registration" product type and order item type. In the order item type, I added fields for the registrant's name and job title. How can I print the submitted values for those fields in the commerce-order-receipt.html.twig?
解決
Figured it out! Took a few steps:
- I created a View of type: Order Item. Added my custom fields to that view (Job Title, etc).
- Added a Contextual Filter "Order item: ID". Provide Default Value: Content ID from URL.
- I created a Viewfield on each of my Order Item Types, using the View I created in the previous step.
I went to /admin/commerce/config/order-item-types/default/edit/display and hid all the fields except for the Viewfield. Repeat for the other Order Item Types. In commerce-order-receipt.html.twig, add this code (which was found in commerce-checkout-order-summary.html.twig):
{{ order_item|commerce_entity_render('summary') }}
Style the output as you like in the receipt twig. Here is the pertinent portion of mine in case anyone finds it helpful:
<tr> <td> {% block order_items %} <table style="padding-top: 15px; padding-bottom:15px; width: 100%"> <tbody style="text-align: left;"> {% for order_item in order_entity.getItems %} <tr> <td> <span style="font-size: 15px;"> {{ order_item.getQuantity|number_format }} x <span style="font-weight: bold;">{{ order_item.label }}</span> <span style="float: right;">{{ order_item.getTotalPrice|commerce_price_format }}</span> </span> <br> {{ order_item|commerce_entity_render('summary') }} <br><br><hr><br> </td> </tr> {% endfor %} </tbody> </table> {% endblock %} </td> </tr>
Clear cache, and that's it!
他のヒント
I just needed one product attribute (with field machine name 'field_message') to be included in the item rows in the e-mail, so I adapted the template like this:
{% for order_item in order_entity.getItems %}
<tr>
<td>
{{ order_item.getQuantity|number_format }} x
</td>
<td>
{{ order_item.label }}
</td>
<td>
{% if order_item.field_message.value %}
{{ order_item.field_message.value }}
{% endif %}
</td>
<td style="text-align: right;">
{{ order_item.getTotalPrice|commerce_price_format }}</span>
</td>
</tr>
{% endfor %}
So if the order_item has a value for field_message, that value goes into a new third table column (if not then the cell is empty), with the fourth column now right-aligned with the total price as before.
And instead of putting this commerce-order-receipt.html.twig file in a new custom module, I just included it in my existing custom theme (in its templates directory), with the following in the THEMENAME.theme file:
/**
* Implements hook_theme().
*/
function THEMENAME_theme($existing, $type, $theme, $path) {
return [
'commerce_order_receipt' => [
'template' => 'commerce-order-receipt',
'base hook' => 'commerce_order_receipt',
],
];
}