Add custom document type

Overview

Using the Shopware administration, you can easily create new documents. This guide will teach you how to achieve the same result, which is creating a new document, using your plugin.

Prerequisites

This guide is built upon the plugin base guide, but of course you can use those examples with any other plugin.
Furthermore adding a custom document type via your plugin is done by using plugin database migrations. Since this isn't explained in this guide, you'll have to know and understand the plugin database migrations first.

Adding a custom document type to the database

Let's start with adding your custom document type to the database, so it's actually available for new document configurations. This is done by adding a plugin database migration. To be precise, we need to add an entry to the database table document_type table and an entry for each supported language to the document_type_translation table.
Let's have a look at an example migration:
<plugin root>/src/Migration/Migration1616677952AddDocumentType.php
1
<?php declare(strict_types=1);
2
3
namespace Swag\BasicExample\Migration;
4
5
use Doctrine\DBAL\Connection;
6
use Shopware\Core\Defaults;
7
use Shopware\Core\Framework\Migration\MigrationStep;
8
use Shopware\Core\Migration\Traits\ImportTranslationsTrait;
9
use Shopware\Core\Framework\Uuid\Uuid;
10
use Shopware\Core\Migration\Traits\Translations;
11
12
class Migration1616677952AddDocumentType extends MigrationStep
13
{
14
use ImportTranslationsTrait;
15
16
public function getCreationTimestamp(): int
17
{
18
return 1616677952;
19
}
20
21
public function update(Connection $connection): void
22
{
23
$documentTypeId = Uuid::randomBytes();
24
25
$connection->insert('document_type', [
26
'id' => $documentTypeId,
27
'technical_name' => 'example',
28
'created_at' => (new \DateTime())->format(Defaults::STORAGE_DATE_TIME_FORMAT)
29
]);
30
31
$this->addTranslations($connection, $documentTypeId);
32
}
33
34
public function updateDestructive(Connection $connection): void
35
{
36
}
37
38
private function addTranslations(Connection $connection, string $documentTypeId): void
39
{
40
$englishName = 'Example document type name';
41
$germanName = 'Beispiel Dokumententyp Name';
42
43
$documentTypeTranslations = new Translations(
44
[
45
'document_type_id' => $documentTypeId,
46
'name' => $germanName,
47
],
48
[
49
'document_type_id' => $documentTypeId,
50
'name' => $englishName,
51
]
52
);
53
54
$this->importTranslation(
55
'document_type_translation',
56
$documentTypeTranslations,
57
$connection
58
);
59
}
60
}
Copied!
So first of all we're creating the new document type with the technical_name "example". Make sure to save the ID here, since you're going to need it for the following translations.
Afterwards we're inserting the translations, one for German, one for English. For this we're using the Shopware\Core\Migration\Traits\ImportTranslationsTrait, which adds the helper method importTranslation. There you have to supply the translation table and an instance of Shopware\Core\Migration\Traits\Translations. The latter accepts two constructor parameters:
  • An array of German translations, plus the respective ID column
  • An array of English translations, plus the respective ID column
    It will then take care of properly inserting those translations.
After installing your plugin, your new document type should be available in the administration. However, it wouldn't work yet, since every document type has to come with a respective DocumentGeneratorInterface. This is covered in the next section.

Adding a generator

The generator for a document type is responsible for actually generating the respective document, including a template. That's why we'll have to create a custom generator for the new type as well, we'll call it ExampleDocumentGenerator.
We'll place it in the same directory like all other default document generators: <plugin root>/src/Core/Checkout/Document/DocumentGenerator
Your custom document generator has to implement the Shopware\Core\Checkout\Document\DocumentGenerator\DocumentGeneratorInterface, which forces you to implement two more methods:
  • supports: Has to return a string of the document type it supports. We named our document type "example", so our generator has to return "example".
  • generate: This needs to return the actually rendered template as a string. You will have access to the respective order, the document configuration,
    the context and the optional template path.
  • getFileName: Return the file name here. This is basically the same for all generators, but if you want to do custom stuff
    with the file name, this is the place to go.
Furthermore your generator has to be registered to the service container using the tag document.generator.
Let's have a look at an example generator:
<plugin root>/src/Core/Checkout/Document/DocumentGenerator/ExampleDocumentGenerator.php
1
<?php declare(strict_types=1);
2
3
namespace Swag\BasicExample\Core\Checkout\Document\DocumentGenerator;
4
5
use Shopware\Core\Checkout\Document\DocumentConfiguration;
6
use Shopware\Core\Checkout\Document\DocumentConfigurationFactory;
7
use Shopware\Core\Checkout\Document\DocumentGenerator\DocumentGeneratorInterface;
8
use Shopware\Core\Checkout\Document\Twig\DocumentTemplateRenderer;
9
use Shopware\Core\Checkout\Order\OrderEntity;
10
use Shopware\Core\Framework\Context;
11
use Twig\Error\Error;
12
13
class ExampleDocumentGenerator implements DocumentGeneratorInterface
14
{
15
public const DEFAULT_TEMPLATE = '@SwagBasicExample/documents/example_document.html.twig';
16
public const EXAMPLE_DOC = 'example';
17
18
private string $rootDir;
19
20
private DocumentTemplateRenderer $documentTemplateRenderer;
21
22
public function __construct(DocumentTemplateRenderer $documentTemplateRenderer, string $rootDir)
23
{
24
$this->rootDir = $rootDir;
25
$this->documentTemplateRenderer = $documentTemplateRenderer;
26
}
27
28
public function supports(): string
29
{
30
return self::EXAMPLE_DOC;
31
}
32
33
/**
34
* @throws Error
35
*/
36
public function generate(OrderEntity $order, DocumentConfiguration $config, Context $context, ?string $templatePath = null): string
37
{
38
$templatePath = $templatePath ?? self::DEFAULT_TEMPLATE;
39
40
return $this->documentTemplateRenderer->render($templatePath, [
41
'order' => $order,
42
'config' => DocumentConfigurationFactory::mergeConfiguration($config, new DocumentConfiguration())->jsonSerialize(),
43
'rootDir' => $this->rootDir,
44
'context' => $context,
45
], $context, $order->getSalesChannelId(), $order->getLanguageId(), $order->getLanguage()->getLocale()->getCode());
46
}
47
48
public function getFileName(DocumentConfiguration $config): string
49
{
50
return $config->getFilenamePrefix() . $config->getDocumentNumber() . $config->getFilenameSuffix();
51
}
52
}
Copied!
First of all we're injecting the rootDir of the Shopware installation into our generator, since we'll need that for rendering our template, and the DocumentTemplateRenderer, which will do the template rendering.
The supports method just returns the string "example", which is the technical name of our new document type. The getFileName method is very default - it just builds a string consisting of the file name prefix, that you configured, the current document number and the file name suffix.
Now let's have a look at the generate method. Technically it's possible to apply a custom template path, which is why this is an optional parameter, which we have to check for. Yet, it can't be defined in the administration and will most likely be empty. We're using a default template path here, which has to point to a template file for our new document type. This can be an existing default document template, in that case you can use them via the following path: @Framework/documents/delivery_note.html.twig
In this example we're rendering a custom template though, which we will have a short look at in the next section.
Afterwards we're using the previously injected DocumentTemplateRenderer to actually render and return the template at the said template path.

Adding a document type template

Let's have a quick look at an example document type template. Go ahead and create a new file at the path <plugin root>/src/Resources/views/documents/example_document.html.twig.
In there you should extend from the default document base template:
<plugin root>/src/Resources/views/documents/example:document.html.twig
1
{% sw_extends '@Framework/documents/base.html.twig' %}
Copied!
This could be it already. The base.html.twig template comes with a lot of default templating, which you can now override by using blocks. If you don't know how that's done, have a look at our guide regarding customizing templates.

Adding a number range

You're almost done here. You've got a new document type in the database, a generator for your new document type and it even uses a custom template. However, you also need to add a new number range for your documents, otherwise a new number for your documents wouldn't be generated.
Adding a new number range is also done by using a plugin database migration.
For this we need a few more things:
  • An entry in number_range_type, which is just a new type of a number range with a technical name
  • An entry in number_range, which represents a properly configured number range, which then will use the previously created type
  • An entry in number_range_sales_channel to assign a sales channel to our configured number range
  • An entry for each language in the tables number_range_translation and number_range_type_translation
Sounds like a lot, but having a look at an example migration, you will notice that it's not too much of a hassle.
<plugin root>/src/Migration/Migration1616974646AddDocumentNumberRange.php
1
<?php declare(strict_types=1);
2
3
namespace Swag\BasicExample\Migration;
4
5
use Doctrine\DBAL\Connection;
6
use Shopware\Core\Defaults;
7
use Shopware\Core\Framework\Migration\MigrationStep;
8
use Shopware\Core\Framework\Uuid\Uuid;
9
use Shopware\Core\Migration\Traits\ImportTranslationsTrait;
10
use Shopware\Core\Migration\Traits\Translations;
11
12
class Migration1616974646AddDocumentNumberRange extends MigrationStep
13
{
14
use ImportTranslationsTrait;
15
16
public function getCreationTimestamp(): int
17
{
18
return 1616974646;
19
}
20
21
public function update(Connection $connection): void
22
{
23
$numberRangeId = Uuid::randomBytes();
24
$numberRangeTypeId = Uuid::randomBytes();
25
26
$this->insertNumberRange($connection, $numberRangeId, $numberRangeTypeId);
27
$this->insertTranslations($connection, $numberRangeId, $numberRangeTypeId);
28
29
}
30
31
public function updateDestructive(Connection $connection): void
32
{
33
}
34
35
private function insertNumberRange(Connection $connection, string $numberRangeId, string $numberRangeTypeId): void
36
{
37
$connection->insert('number_range_type', [
38
'id' => $numberRangeTypeId,
39
'global' => 0,
40
'technical_name' => 'document_example',
41
'created_at' => (new \DateTime())->format(Defaults::STORAGE_DATE_TIME_FORMAT)
42
]);
43
44
$connection->insert('number_range', [
45
'id' => $numberRangeId,
46
'type_id' => $numberRangeTypeId,
47
'global' => 0,
48
'pattern' => '{n}',
49
'start' => 10000,
50
'created_at' => (new \DateTime())->format(Defaults::STORAGE_DATE_TIME_FORMAT)
51
]);
52
53
$storefrontSalesChannelId = $this->getStorefrontSalesChannelId($connection);
54
if (!$storefrontSalesChannelId) {
55
return;
56
}
57
58
$connection->insert('number_range_sales_channel', [
59
'id' => Uuid::randomBytes(),
60
'number_range_id' => $numberRangeId,
61
'sales_channel_id' => $storefrontSalesChannelId,
62
'number_range_type_id' => $numberRangeTypeId,
63
'created_at' => (new \DateTime())->format(Defaults::STORAGE_DATE_TIME_FORMAT)
64
]);
65
}
66
67
private function getStorefrontSalesChannelId(Connection $connection): ?string
68
{
69
$sql = <<<SQL
70
SELECT id
71
FROM sales_channel
72
WHERE type_id = :typeId
73
SQL;
74
$salesChannelId = $connection->fetchOne($sql, [
75
':typeId' => Uuid::fromHexToBytes(Defaults::SALES_CHANNEL_TYPE_STOREFRONT)
76
]);
77
78
if (!$salesChannelId) {
79
return null;
80
}
81
82
return $salesChannelId;
83
}
84
85
private function insertTranslations(Connection $connection, string $numberRangeId, string $numberRangeTypeId): void
86
{
87
$numberRangeTranslations = new Translations(
88
[
89
'number_range_id' => $numberRangeId,
90
'name' => 'Beispiel',
91
],
92
[
93
'number_range_id' => $numberRangeId,
94
'name' => 'Example',
95
]
96
);
97
98
$numberRangeTypeTranslations = new Translations(
99
[
100
'number_range_type_id' => $numberRangeTypeId,
101
'type_name' => 'Beispiel',
102
],
103
[
104
'number_range_type_id' => $numberRangeTypeId,
105
'type_name' => 'Example',
106
]
107
);
108
109
$this->importTranslation(
110
'number_range_translation',
111
$numberRangeTranslations,
112
$connection
113
);
114
115
$this->importTranslation(
116
'number_range_type_translation',
117
$numberRangeTypeTranslations,
118
$connection
119
);
120
}
121
}
Copied!
As already said, we're first creating the entries in the tables number_range, number_range_type and number_range_sales_channel. For the latter, we're assigning a Storefront sales channel, if any available. Make sure to check here, since in theory there could be no storefront sales channel.
Afterwards we import the translations for the number_range_translation and the number_range_type_translation tables by using the ImportTranslationsTrait once again.
And that's it now! You've just created:
  • A custom document type, including translations
  • A custom document generator, including a custom template
  • A custom number range and number range type, which will now be used by your custom document type

Next steps

With your custom document type, you also might want to add a new actual document configuration, which is making use of your new type. Creating a custom document is explained in this guide.