0

Let's say we have a RECIPE content type that has a multi-value entity reference field to a FOOD content type, so as to represent the ingredients.

Each ingredient on a recipe needs to hold a quantity (eg: '1 cup') in addition to the reference itself. How can we add that attribute?

We'd like to avoid having an additional entity to hold the relationship for performance reasons. Also, sticking to core's entity reference field seems a good idea so the rest of the ecosystem can recognize the relationship.

  • You can extend the field type EntityReferenceItem and add the quantity as property. You can find some examples in core, where field types are extended, mainly to add properties. For example image is extended from file with added properties for width, height and alt text and file is extended from the entity reference field type. Easier is field collection, see @oknate answer, but this has more overhead because of the extra entity. – 4k4 Nov 16 '16 at 17:07
5

The best and standard way to do this is with paragraphs.

Enable the paragraphs module, then add a paragraph type called ingredient with the two fields, an entity reference field and a field for the quantity.

if you want an ingredient to be reusable, keep in mind that paragraphs are not reusable. If you want to reuse an ingredient, say "1 cup flour", then you could use an entity reference field to another reusable entity type, such as media or taxonomy, or another node type.

  • Seems I was looking exactly for the second option! Because besides performance, I fear field collection would prevent certain parts of core/contrib to recognize the relationship. So by extending the entity reference field, I can still use the new field as if it was a regular entity reference field? And core/contrib would recognize it as such? Thanks so much for your answer and even taking the time for the example! Much appreciated! – rafamd Nov 17 '16 at 13:38
  • Sure, no problem. There may be a few issues with compatibility since it's not an entity reference, but an extension of it. For example, I'm not sure if it would work out of the box with views. You may have to create your own view plugin to get it work as a views argument or filter, especially if you want to filter by the secondary text field. But you'd have issues with a field collection where the relationship is deeply nested. So for example, getting all the quantities on a node will be easier with this approach because they'll all be on one table. – oknate Nov 17 '16 at 14:56

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.