1

I am developing a module for Drupal 8 and want to make a field on one entity that references another along with some additional data. e.g. Library A has a copy of Book B (of Edition 2). There will be multiple values stored in the field for each source entity. In the above example Libraries will have multiple books.

I know how to implement a new FieldType and the widget and formatter for it, but I am wondering whether this is the best way for a reference. Would it be better to create a new entity to hold the relationship with the two endpoints and additional data (like I would create an xref table in MySQL)

If I do go with a FieldType, when it comes to implementing the storage of the new field, would I just store the id of the referenced entity and then have to wrap the access in a method to change id <-> entity?

Thanks in advance for your help! Jamie

5

So you're actually asking two questions.

  1. Should I use a field type or a relation?

Both works. Field type requires much less storage (everything is in the field table), but it's hardcoded to one specific use case. The alternative is basically https://www.drupal.org/project/relation or you could also use something like https://www.drupal.org/project/paragraphs, https://www.drupal.org/project/field_collection if you only have a source -> target reference (relation can to n-n references). For all, you'd create a relation/paragraph/collection type with your additional fields. More flexible, can be configured and doesn't require custom code, but each reference is another entity that has to be stored and loaded.

You will have to decide what's better for your case, depends on performance vs. flexibility requirements, how many variations (you probably don't want to create 10 field types..) and so on.

  1. If a field type, how do I create it.

That's actually fairly easy in Drupal 8. You just extend from the default entity reference field type (EntityReferenceItem), override methods like schema() and propertyDefinitions() to define what properties you have and how they are stored. Then you write a widget and formatter for it, extending from the widget/formatter that's closest to what you want (e.g. autocomplete or select for the reference selection).

The advantage is, all the actual reference things will just work through the parent classes, you just have to implement your additional properties.

  • Thank you! Your name seems to pop up all over the place while I've been learning Drupal... It's great to see someone willing to help us noobs get our heads around it! – Jazzer Apr 24 '16 at 22:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.