mglaman/drupal-typed-data-by-example

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:

  1. Creating a class that extends Drupal\Core\TypedData\TypedData or one of its subclasses
  2. Creating a class that extends Drupal\Core\TypedData\DataDefinition or one of its subclasses.
    1. Overriding getPropertyDefinitions method and creating the data definitions or property definitions within.
  3. Attaching a @DataType{ ... } annotation to the first class.
    1. Setting the definition_class attribute of the annotation to the fully qualified name of the second class
    2. Putting a machine name in the id attribute of the annotation
  4. 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)

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.