Create a new custom entity on Drupal 8, with all necessary user interfaces.
This is a full Example of the Entity 'Vehicle' with user interfaces for:
- Actions (Create, Edit, Delete)
- Listing builder
- Entity settings pages
- Manage fields
- Manage form display
- Manage display
Few tips
Read values of an entity
Here : $this = The entity.
Get a field value:
$this->get('fieldname')->value
Get an entity from entity_reference field:
$this->get('entity_field_name')->entity;
Get entity id from entity_reference field:
$quote->get('entity_field_name')->entity->id()
OR
//$this->getEntityKey('entity_field_name'); //Not tested
File Field (Example)
$fields['fid'] = BaseFieldDefinition::create('file')
->setLabel(t('Photo (fid)'))
->setDescription(t('The photo'))
->setSetting('target_type', 'file')
->setSetting('file_extensions', 'jpg jpeg')
->setSetting('file_directory', 'images/myphotosdir')
->setSetting('max_filesize', 1024*1024)
->setDisplayOptions('view', array(
'type' => 'file', 'weight' => -8,
))
->setDisplayOptions('form', array(
'type' => 'file', 'weight' => -8,
))
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE)
->setReadOnly(TRUE);
Comments3
Thank you for the File field…
Thank you for the File field example. Very helpful!
About the File field
Could you give as an example to add multiple images?
I want to have my custom entity with multiple images, I understand that this will be done by adding another table referencing to my custon entity, but I couldn't do that.
Just add cardinality
...
->setLabel(t('Photo'))
->setCardinality(BaseFieldDefinition::CARDINALITY_UNLIMITED)
....