SlideShare a Scribd company logo
Your Entity, Your Code
Your Entity
Your Code
Marco Vito Moscaritolo
@mavimo@gmail.com
me.yml
users:
mavimo:
name: Marco Vito Moscaritolo
email: mavimo-at-gmail.com
twitter: @mavimo
technologies: [ php, drupal, symfony ]
role: [ developer, teacher, architect ]
work: freelance
founder: @sparkfabrik
Why	entities	?
We can	create	custom
node type…
…right?
• D6 & 5 $node = new stdClass();
// Sad L
• D7 $node = new stdClass();
// DrupalEntityControllerInterface
// EntityFieldQuery, …
• D8 $node = new DrupalnodeEntityNode();
// Yah yahhhh!!! J
A	bit	of	history
• Entity (Node,	User,	Comment,	Taxonomy,	…)
• Bundle (Node	type,	Vocabularies,	…)
• Property (Node	id,	node	title,	vocabulary	name,	…)
• Field (Body,	Image	field,	Term	references,	…)
Core	elements
D7 - hook_entity_info()
return array(
’entity_name' => array(
'label' => t(’Custom entity'),
'controller class' => ’CustomEntityController',
'base table' => ’custom_entity',
'uri callback' => ’custom_entity_uri',
'fieldable' => TRUE,
'entity keys' => array( /* ... */ )
'bundle keys' => array(
'bundle' => 'machine_name',
),
'bundles' => array( /* ... */ ),
'view modes' => array( /* ... */ ),
),
);
D7 - Entity API
D7 - Entity
Bla bla…
class CustomEntity extends Entity {
public function __construct(array $values = [], $entity_type = NULL) {}
public function identifier() {}
public function bundle() {}
public function uri() {}
public function hasStatus($status) {}
public function save() {}
public function delete() {}
public function view($view_mode = 'full', $lang = NULL, $page = NULL) {}
public function buildContent($view_mode = 'full', $langcode = NULL) {}
// ...
}
D7 - hook_entity_info()
extended by Entity API
return array(
’entity_name' => array(
// ...
’entity class' => ’CustomEntity',
// ...
'views controller class' => ’CustomEntityViewsController',
// ...
'exportable’ => TRUE,
// ...
'admin ui' => array(
// ...
'controller class' => ’CustomEntityUIController',
),
),
);
D7 - EntityAPIController
class CustomEntityController extends EntityAPIController {
public function __construct($entityType) {}
public function query($ids, $conditions, $revision_id = FALSE) {}
public function load($ids = array(), $conditions = array()) {}
public function invoke($hook, $entity) {}
public function delete($ids, DatabaseTransaction $trans = NULL) {}
public function save($entity, DatabaseTransaction $trans = NULL) {}
public function create(array $values = array()) {}
public function buildContent($entity, $view_mode = 'full’,
$lang = NULL, $content = []) {}
public function view($entities, $view_mode = 'full’,
$langcode = NULL, $page = NULL) {}
// ...
}
D7 - EntityDefaultUIController
Bla bla…class CustomEntityUIController extends EntityDefaultUIController {
public function __construct($entity_type, $entity_info) {}
public function hook_menu() {}
public function hook_forms() {}
public function overviewTable($conditions = array()) {}
public function overviewForm($form, &$form_state) {}
public function operationForm($form, &$form_state, $entity, $op) {}
// and also [overview|operation]Form[Submit|Validate] methods.
public function applyOperation($op, $entity) {}
// ...
}
D7 – Entity	(Admin	UI)
D7 - Entity	UI	(admin)
D7 - Entity	UI	(edit)
Too	much	work…	why???
Integration
view, rules, features
Code testability
easy to isolate
Reusability
code once, use more
Remote entity
social network, webservices
Drupal 8 ;-)
Integration	(eg:	views)
EntityFieldQuery
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'custom_entity')
->entityCondition('bundle', 'my_bundle')
->propertyCondition('uid', $user->uid, '=')
->fieldCondition('field_faculty_tag', 'tid', 10)
->fieldOrderBy('field_faculty_tag', 'tid', 'DESC')
->range(0, 10);
$result = $query->execute();
if (isset($result['custom_entity'])) {
$items = entity_load('custom_entity’, array_keys($result['custom_entity']));
}
EntityMetadataWrapper
$wrapper = entity_metadata_wrapper('custom_entity', $entity);
$wrapper->author->mail->set('demo@drupalday.it');
$wrapper->description->value('This is a demo!');
$labels = array();
foreach ($wrapper->field_faculty_tag->getIterator()
as $delta => $term_wrapper) {
$labels[] = $term_wrapper->label->value();
}
$wrapper->save();
D7 - Create	Custom	Entity…	Fast!(1)
drush entity-scaffold entity_name dday
File dday/entity_name/includes/entity_name.admin.inc created. [ok]
File dday/entity_name/includes/entity_name.class.inc created. [ok]
File dday/entity_name/includes/entity_name.controller.inc created. [ok]
File dday/entity_name/includes/entity_name.type.controller.inc created. [ok]
File dday/entity_name/includes/entity_name_type.admin.inc created. [ok]
File dday/entity_name/entity_name.info created. [ok]
File dday/entity_name/entity_name.install created. [ok]
File dday/entity_name/entity_name.tpl.php created. [ok]
File dday/entity_name/entity_name.module created. [ok]
https://www.drupal.org/project/entity_scaffold
D7 - Create	Custom	Entity…	Fast!(2)
https://www.drupal.org/project/eck
…Drupal	8	?
Thanks!
ContentEntityTypeInterface
(Node,	User,	Comment,	Taxonomy,	…)
ConfigEntityTypeInterface
(Configuration	information)
…
(eg:	Bundle)
D8 - Entity	type
D8 - Entity Type
Module namespaced
Drupalmy_moduleEntityMyCustomeEntity()
Defined folder in module
src/Entity/MyCustomEntity.php
INFORMATION MANAGED BY
ANNOTATION
/**
* @XyzEntityType( … )
*/
Can be “code only”
config/install/my_custom_entity.sample_1.yml
Unit testable
class MyCustomEntityTest extends DrupalTestsUnitTestCase {}
D8 - ContentEntityType
Require database definition
hook_schema()
Can be fildable/REVISIONABLE
baseFieldDefinition()
CAN HAVE CUSTOM BEHAVIOR
redefine [pre|post][Save|Load|Delete] methods
CAN PROVIDE CUSTOM ACCESS RULES
checkAccess() and checkCreateAccess()
CAN PROVIDE CUSTOM HANDLERS
strorage, view_builder, route_provider, form, translation, config_export...
D8 - ContentEntityType
/**
* @ContentEntityType(
* id = "my_content",
* label = @Translation("My Content"),
* bundle_label = @Translation("My Content type"),
* handlers = { ... },
* base_table = "my_entity",
* data_table = "my_entity_field_data",
* revision_table = "my_entity_revision",
* revision_data_table = "my_entity_field_revision",
* translatable = TRUE,
* entity_keys = { ... },
* bundle_entity_type = "my_entity_type",
* field_ui_base_route = "entity.my_entity_type.edit_form",
* common_reference_target = TRUE,
* permission_granularity = "bundle",
* links = { ... }
* )
*/
class MyContentEntity extends ContentEntityBase implements
MyContentEntityInterface { }
D8 - ConfigEntityType
Difference	compared	to	ContentEntityType:
• Schema file definition
Instead	of	database	schema	definition,	using:
config/schema/my_entity.schema.yml
• INTEGRATED with CMI API
for exportability
See	dedicated	talk.
• No field
D8 - ConfigEntityType
/**
* @ConfigEntityType(
* id = "my_config",
* label = @Translation("My config"),
* handlers = {
* "list_builder" = "Drupalmy_moduleControllerMyConfigListBuilder",
* "form" = { ... }
* },
* config_prefix = "my_config",
* admin_permission = "administer site configuration",
* entity_keys = { ... },
* links = { ... }
* )
*/
class MyConfigEntity extends ConfigEntityBase implements
MyConfigEntityInterface { ... }
my_module/config/schema/my_config.schema.yml
my_module.my_config.*:
type: config_entity
label: My config’
mapping:
id:
type: string
label: 'ID’
label:
type: label
label: 'Label'
D8 - Create	Custom	Entity…	Fast!
drupal generate:entity:content 
--module=dday 
--entity-name=my_content_entity 
--entity-class=MyContentEntity 
--label="My Content Entity”
Generated or updated files Site path: ~/dday
1 - modules/custom/dday/dday.routing.yml
2 - modules/custom/dday/dday.permissions.yml
3 - modules/custom/dday/dday.links.menu.yml
4 - modules/custom/dday/dday.links.task.yml
. . .
13 - modules/custom/dday/src/Entity/Form/MyContentEntityDeleteForm.php
14 - modules/custom/dday/my_content_entity.page.inc
15 - modules/custom/dday/templates/My Content Entity.html.twig
https://www.drupal.org/project/console
Question?
Thank you!
milan2016.drupaldays.org
References
http://joshaust.in/wp-content/uploads/2012/06/Entities-and-Bundles-in-Drupal-7.pdf
https://www.drupal.org/project/entity
https://www.drupal.org/project/eck
https://www.drupal.org/project/entity_scaffold
http://www.bluespark.com/blog/drupal-entities-part-1-moving-beyond-nodes
http://www.sitepoint.com/build-custom-entities-drupal-setup/
https://www.drupal.org/developing/api/entity
https://hechoendrupal.gitbooks.io/drupal-console/content/en/index.html
http://www.wunderkraut.com/blog/configuration-entities-in-drupal-8/2014-07-14
http://nuvole.org/blog/drupal-8
http://blog.oskoui-oskoui.com/?p=8218
https://codedrop.com.au/blog/creating-custom-config-entities-drupal-8
Your Entity, Your Code

More Related Content

PPTX
Build your own entity with Drupal
PDF
Top Ten Reasons to Use EntityFieldQuery in Drupal
PDF
Your Entity, Your Code
PPT
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
PDF
jQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
PDF
Your code sucks, let's fix it - DPC UnCon
PPTX
PDF
Entities in drupal 7
Build your own entity with Drupal
Top Ten Reasons to Use EntityFieldQuery in Drupal
Your Entity, Your Code
ZFConf 2010: Zend Framework & MVC, Model Implementation (Part 2, Dependency I...
jQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
Your code sucks, let's fix it - DPC UnCon
Entities in drupal 7

What's hot (20)

PDF
Virtual Madness @ Etsy
PDF
Drupal Field API. Practical usage
PDF
Drupal 8: Forms
ODP
Symfony2, creare bundle e valore per il cliente
PDF
Drupal Entities - Emerging Patterns of Usage
PDF
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
PDF
Functionality Focused Code Organization
PDF
Doctrine 2
PDF
Drupal Step-by-Step: How We Built Our Training Site, Part 1
PDF
Command-Oriented Architecture
PDF
Drupal 8 Sample Module
PDF
05 JavaScript #burningkeyboards
PDF
Desarrollo de módulos en Drupal e integración con dispositivos móviles
KEY
PPTX
Drupal 8 migrate!
PDF
Drupal 8: Fields reborn
PPTX
Drupal 7 entities & TextbookMadness.com
PDF
06 jQuery #burningkeyboards
ODP
Entity Query API
PDF
Field api.From d7 to d8
Virtual Madness @ Etsy
Drupal Field API. Practical usage
Drupal 8: Forms
Symfony2, creare bundle e valore per il cliente
Drupal Entities - Emerging Patterns of Usage
Decouple Your Code For Reusability (International PHP Conference / IPC 2008)
Functionality Focused Code Organization
Doctrine 2
Drupal Step-by-Step: How We Built Our Training Site, Part 1
Command-Oriented Architecture
Drupal 8 Sample Module
05 JavaScript #burningkeyboards
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Drupal 8 migrate!
Drupal 8: Fields reborn
Drupal 7 entities & TextbookMadness.com
06 jQuery #burningkeyboards
Entity Query API
Field api.From d7 to d8
Ad

Viewers also liked (20)

PDF
Drupal per la PA
PDF
[drupalday2017] - Devel - D8 release party
PDF
[drupalday2017] - Async navigation with a lightweight ES6 framework
PDF
[drupalday2017] - Drupal 4 Stakeholders
PDF
[drupalday2017 - KEYNOTE] - Saving the world one Open Source project at a time
PDF
[drupalday2017] - Behat per Drupal: test automatici e molto di più
PDF
[drupalday2017] - DevOps: strumenti di automazione per Drupal8
PDF
[drupalday2017] - Contenuti educativi digitali aperti, creare contenuti e dis...
PDF
[drupalday2017] - Open Data con Drupal nella PA: considerazioni su licensing ...
PDF
[drupalday2017] - DRUPAL per la PA: il modello della Trasparenza di Sapienza
PDF
[drupalday2017] - Quando l’informazione è un servizio
PDF
[drupalday2017] - Venezia & Drupal. Venezia è Drupal!
PDF
[drupalday2017] - Cosa significa convertire un modulo da D7 a D8
PDF
Da X a Drupal 8, migra tutto e vivi sereno
PDF
Once you go cloud you never go down
PDF
Tooling per il tema in Drupal 8
PDF
[drupalday2017] - DevOps: strumenti di automazione per Drupal8
PDF
[drupalday 2017] - Accessibilità Web: Finalità, metodologie e strumenti.
PDF
[drupalday2017] - REST in pieces
PDF
[drupalday2017] - Drupal & Patternlab: un nuovo approccio al theming
Drupal per la PA
[drupalday2017] - Devel - D8 release party
[drupalday2017] - Async navigation with a lightweight ES6 framework
[drupalday2017] - Drupal 4 Stakeholders
[drupalday2017 - KEYNOTE] - Saving the world one Open Source project at a time
[drupalday2017] - Behat per Drupal: test automatici e molto di più
[drupalday2017] - DevOps: strumenti di automazione per Drupal8
[drupalday2017] - Contenuti educativi digitali aperti, creare contenuti e dis...
[drupalday2017] - Open Data con Drupal nella PA: considerazioni su licensing ...
[drupalday2017] - DRUPAL per la PA: il modello della Trasparenza di Sapienza
[drupalday2017] - Quando l’informazione è un servizio
[drupalday2017] - Venezia & Drupal. Venezia è Drupal!
[drupalday2017] - Cosa significa convertire un modulo da D7 a D8
Da X a Drupal 8, migra tutto e vivi sereno
Once you go cloud you never go down
Tooling per il tema in Drupal 8
[drupalday2017] - DevOps: strumenti di automazione per Drupal8
[drupalday 2017] - Accessibilità Web: Finalità, metodologie e strumenti.
[drupalday2017] - REST in pieces
[drupalday2017] - Drupal & Patternlab: un nuovo approccio al theming
Ad

Similar to Your Entity, Your Code (20)

PPT
Synapse india reviews on drupal 7 entities (stanford)
PDF
Entities in Drupal 8 - Drupal Tech Talk - Bart Feenstra
PDF
Entity api
PDF
Entity API in Drupal 8 (Drupal Tech Talk October 2014)
PDF
Drupal 8: Entities
ODP
Drupal 8 entities & felds
PDF
Web automation with #d8rules (European Drupal Days 2015)
PDF
Entities, Bundles, and Fields: You need to understand this!
PPTX
PDF
Drupal 7 Entity & Entity API
PDF
Drupalize your data use entities
PDF
ознакомления с модулем Entity api
PDF
Entities 101: Understanding Data Structures in Drupal
PDF
What's New in Drupal 8: Entity Field API
PDF
Fields, entities, lists, oh my!
PDF
Understanding the Entity API Module
PDF
DrupalJam 2018 - Maintaining a Drupal Module: Keep It Small and Simple
PDF
Dependency injection in Drupal 8
PDF
Customizing oro crm webinar
Synapse india reviews on drupal 7 entities (stanford)
Entities in Drupal 8 - Drupal Tech Talk - Bart Feenstra
Entity api
Entity API in Drupal 8 (Drupal Tech Talk October 2014)
Drupal 8: Entities
Drupal 8 entities & felds
Web automation with #d8rules (European Drupal Days 2015)
Entities, Bundles, and Fields: You need to understand this!
Drupal 7 Entity & Entity API
Drupalize your data use entities
ознакомления с модулем Entity api
Entities 101: Understanding Data Structures in Drupal
What's New in Drupal 8: Entity Field API
Fields, entities, lists, oh my!
Understanding the Entity API Module
DrupalJam 2018 - Maintaining a Drupal Module: Keep It Small and Simple
Dependency injection in Drupal 8
Customizing oro crm webinar

More from DrupalDay (10)

PDF
[drupalday2017] - Cloud e integrazione per la PA: la sfida dell'Open Source t...
PDF
[drupalday2017] - Drupal come frontend che consuma servizi: HTTP Client Manager
PDF
[drupalday2017] - Decoupled frontend con Drupal 8 e OpenUI 5
PDF
[drupalday2017] - Speed-up your Drupal instance!
PDF
Come progettare e realizzare una distribuzione in Drupal 8
PDF
Mantenere una distribuzione Drupal attraverso test coverage: Paddle case study
PDF
Invisiblefarm condivide l'esperienza DrupalGIS
PDF
La semantica per automatizzare una redazione web: l'esperienza di Innolabplus.eu
PDF
"Twig e i belli dentro": panoramica sui nuovi standard di frontend-developmen...
PDF
Drupal 8: dal download del Core alla pubblicazione in produzione. Cos'è cambi...
[drupalday2017] - Cloud e integrazione per la PA: la sfida dell'Open Source t...
[drupalday2017] - Drupal come frontend che consuma servizi: HTTP Client Manager
[drupalday2017] - Decoupled frontend con Drupal 8 e OpenUI 5
[drupalday2017] - Speed-up your Drupal instance!
Come progettare e realizzare una distribuzione in Drupal 8
Mantenere una distribuzione Drupal attraverso test coverage: Paddle case study
Invisiblefarm condivide l'esperienza DrupalGIS
La semantica per automatizzare una redazione web: l'esperienza di Innolabplus.eu
"Twig e i belli dentro": panoramica sui nuovi standard di frontend-developmen...
Drupal 8: dal download del Core alla pubblicazione in produzione. Cos'è cambi...

Recently uploaded (20)

PDF
Approach and Philosophy of On baking technology
PPTX
MYSQL Presentation for SQL database connectivity
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PDF
cuic standard and advanced reporting.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Machine learning based COVID-19 study performance prediction
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Approach and Philosophy of On baking technology
MYSQL Presentation for SQL database connectivity
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
NewMind AI Weekly Chronicles - August'25 Week I
NewMind AI Monthly Chronicles - July 2025
Understanding_Digital_Forensics_Presentation.pptx
Empathic Computing: Creating Shared Understanding
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
20250228 LYD VKU AI Blended-Learning.pptx
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
cuic standard and advanced reporting.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Advanced methodologies resolving dimensionality complications for autism neur...
Machine learning based COVID-19 study performance prediction
The AUB Centre for AI in Media Proposal.docx
CIFDAQ's Market Insight: SEC Turns Pro Crypto
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx

Your Entity, Your Code