Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
How do you add a field to the entity in code (programmatically)?
When I install this module I can create entity types each with there own set of fields using the UI, but I need to do it programmatically.
Do you add it to the primary entity or the entity_type entity?
Could you give a code example of that?
Comments
Comment #1
keyiyek CreditAttribution: keyiyek commentedLet say you have all the base code for your entities and entity types up and working,
then you can create a new entity type
or
where $type is the name of your entity type and $values is an array with things such label & description.
Then you must define 2 thing: fields and instances.
Field is an array that says the type of data you are going to store, cardinality and other things
once you have defined a field you have to create it
Up to this you just created the field, you have to tell Drupal to wich kind of entities you want it to be attached (even more than one if you like), for this you have to define an instance (properly a field-instance). Again with the arrays:
after the definition you create it
you can have a look to http://drupal.org/project/examples there is the node examples that adds fields and instances, it works the same for entities
Comment #2
liquidcms CreditAttribution: liquidcms commentedi dont think the above for adding an instance works. try this:
Comment #3
AnybodyClosing this because there was no further feedback from @captaindav. Please tell us how you solved it if possible.
Should this be or is this documented somewhere?
Comment #5
shmeterlin CreditAttribution: shmeterlin commentedI'm also trying to figure how to add entities programmatically, the explanation in #1 is very vague. I'm trying to follow the node example but it's not that straight forward when applying here.