1

I am working with a custom entity and I would like to be able to add taxonomy to the entity. The drupal 8 entity documentation is lacking.

I have tried reading Node.php and term.php entitiy files but I don't understand how any sort of taxonomy is linked to any other entity though this.

Do I need to change something in my entity definition to allow taxonomy to be added? Or is there a way to access the taxonomy entity?

Edit: I am working on the same pattern to add this to the install file of my module

'category' => array(
                'type' => 'varchar',
                'not null' => TRUE,
                'default' => '',
                'description' => 'The section front  to appear on',
            ),

this is the exception that I get trying to install the module

exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error [error]
or access violation: 1064 You have an error in your SQL syntax; check
the manual that corresponds to your MySQL server version for the
right syntax to use near 'NOT NULL DEFAULT '' COMMENT 'The section
front  to appear on',
2
  • 1
    Taxonomy terms are entities too, so an entity reference field would probably be the best choice
    – Clive
    Commented Sep 11, 2015 at 17:16
  • For the edit: varchar columns require a length
    – Clive
    Commented Sep 13, 2015 at 1:42

2 Answers 2

1

For custom entities, I would suggest to work with @ContentEntityType and baseFieldDefinitions() method, instead of creating the table on .install file.

You can see more details on why take this path in When to use BaseFieldDefinition instead of hook_schema an on this implementation.

A taxonomy field is now on D8 only an entity reference field, and you can have an example on how to use it at the field "voted_entity_id" at https://github.com/pedrorocha-net/votingapi/blob/8.x-1.x/src/Entity/Vote.php

2
2

As Clive said, you use an entity reference field for that, just like articles have a tags reference field to terms.

If you want to define it in code, it's really the same as the node.uid field, which is an entity reference to a user. Or the user.roles field, which is a multivalue reference to user roles. Entities reference others using an entity reference field, it's always the same pattern.

1
  • i am working on the same pattern to add this to the install file of my module Commented Sep 11, 2015 at 20:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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