The Goal
Drupal Commerce order types can be configured to email the customer a receipt when an order is placed, with or without a BCC copy sent to a specified email address. Additionally, administrative users can use a "Resend receipt" button to send a receipt to the contact email address set for the order; no copy is sent to an additional email address.
When re-sending an order receipt, administrative users may want to:
- Set their own addresses to be copied on the emails, rather than a generic store-wide email.
A Solution
We will add a checkbox to the Order Receipt confirmation form to allow administrative users to copy themselves on emails:
To implement, we can override the Order Receipt confirmation form provided Commerce Core.
Implementation:
Create a custom form class that extends Drupal\commerce_order\Form\OrderReceiptResendForm
:
- Implement the
buildForm
method:- If the current user has an email address, add a
checkbox
element to the form withtitle
: Send copy of order receipt to me at email_address.
- If the current user has an email address, add a
if (!empty($copy = $this->currentUser->getEmail())) {
$form['copy_me'] = [
'#type' => 'checkbox',
'#title' => $this->t('Send copy of order receipt to me at @copy.', [
'@copy' => $copy,
]),
'#default_value' => TRUE,
];
}
- Implement the
submitForm
method:- If the checkbox was checked, append the current user's email to the order's email, separated by a comma. Use this value as the
$to
; otherwise, use just the order's email as the$to
. - Use the order receipt mail service to send the email:
$result = $this->orderReceiptMail->send($order, $to);
- If the checkbox was checked, append the current user's email to the order's email, separated by a comma. Use this value as the
/** @var \Drupal\commerce_order\Entity\OrderInterface $order */
$order = $this->entity;
$to = $order->getEmail();
if (!empty($copy = $this->currentUser->getEmail()) && ($form_state->getValue('copy_me'))) {
$to = implode(', ', array_filter([$to, $copy]));
}
$result = $this->orderReceiptMail->send($order, $to);
// Drupal's MailManager sets an error message itself, if the sending failed.
if ($result) {
$this->messenger()->addMessage($this->t('Order receipt resent.'));
}
To replace the default OrderReceiptResendForm
implementation with your own, implement hook_entity_type_build
in a custom module:
$entity_types['commerce_order']->setFormClass('resend-receipt', CustomOrderReceiptResendForm::class);
Don't forget the "use" statement for your custom form class!
Note: The $bcc
parameter could be used instead of the comma-separated $to
addresses, if desired.
Comments