Automatic Typed Data Plugin Discovery
Opened this issue · 2 comments
The drupal.org documentation (as well as the code from other core modules) suggests that Typed Data Definitions can be discovered by the Typed Data Manager when a module is loaded, simply by:
- Creating a class that extends
Drupal\Core\TypedData\TypedData
or one of its subclasses - Creating a class that extends
Drupal\Core\TypedData\DataDefinition
or one of its subclasses.- Overriding
getPropertyDefinitions
method and creating the data definitions or property definitions within.
- Overriding
- Attaching a
@DataType{ ... }
annotation to the first class.- Setting the
definition_class
attribute of the annotation to the fully qualified name of the second class - Putting a machine name in the
id
attribute of the annotation
- Setting the
- Saving both classes in php files in the
src/Plugin/DataType
directory of a custom module.
However, despite my best attempts (including reloading cache and registry, and reinstalling module) it appears the Typed Data Manager hasn't discovered my custom data type automatically. Attempting to use Serialization API to deserialize some csv data into an object of the custom data type simply produces the expected error:
Drupal\Component\Plugin\Exception\PluginNotFoundException: The "Drupal\<module_name>\Plugin\DataType\<ClassName>" plugin does not exist.
I would appreciate if an example better than what drupal.org provides could be made.
I'll see what I can do, in the mean time here is an example from Commerce API for Address (which the address
module could provide)
- DataType plugin: https://git.drupalcode.org/project/commerce_api/-/blob/8.x-1.x/src/Plugin/DataType/Address.php
- Data definition: https://git.drupalcode.org/project/commerce_api/-/blob/8.x-1.x/src/TypedData/AddressDataDefinition.php
- Custom normalizer for the data type https://git.drupalcode.org/project/commerce_api/-/blob/8.x-1.x/src/Normalizer/AddressNormalizer.php
Well, I figured out what the issue was. Several examples I had seen used the fully qualified class name to indicate the data type to the Typed Data Manager service's createInstance
method, and following those examples I was unable to make it work.
It turns out that I have to use the id
value in the class annotation instead, after looking more closely at the error message and finding it buried among the enormous list of "valid" data types tossed out by the error message.