I need a custom action in Views VBO with Drupal Commerce to print a selected group of invoices to a browser print dialog. I have configured this as a src plugin and a custom twig template. Here is an example of the code in the action .php:
<?php
namespace Drupal\my_action_module\Plugin\Action;
use Drupal\Core\Action\ActionBase;
use Drupal\Core\Session\AccountInterface;
use Drupal\commerce_order\Entity\OrderInterface;
/**
* Prints an invoice for the selected order(s).
*
* @Action(
* id = "print_invoice_action",
* label = @Translation("Print Invoice"),
* type = "commerce_order"
* )
*/
class PrintInvoiceAction extends ActionBase {
/**
* {@inheritdoc}
*/
public function execute($entities = []) {
if (!empty($entities)) {
foreach ($entities as $entity) {
if ($entity instanceof OrderInterface) {
$this->printInvoice($entity);
}
}
}
}
/**
* Print the invoice for an order.
*
* @param \Drupal\commerce_order\Entity\OrderInterface $order
* The order entity.
*/
protected function printInvoice(OrderInterface $order) {
// Get the array of orders from the context.
$orders = $this->getContextValue('entity');
// Initialize the output variable.
$output = '';
// Loop through each order and generate the invoice output.
foreach ($orders as $order) {
// Render the Twig template with the order entity.
$build = [
'#theme' => 'mymodule_theme_template',
'#order' => $order,
];
// Render the Twig template.
$output .= \Drupal::service('renderer')->renderPlain($build);
}
// Set the content type to HTML.
$headers = ['Content-Type' => 'text/html; charset=utf-8'];
// Print the invoice output with JavaScript to trigger the print dialog.
print '<html><head><title>Invoice</title></head>';
print '<body onload="print();">';
print '<div id="invoice-container">' . $output . '</div>';
print '</body></html>';
exit;
}
/**
* {@inheritdoc}
*/
public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
return $object instanceof OrderInterface;
}
}
So far I cannot get the print dialog of the browser to open my selected group of invoices