SlideShare a Scribd company logo
1 of 30
Download to read offline
Drupal 8: EntitiesDrupal 8: Entities
Working with entities in Drupal 8 modulesWorking with entities in Drupal 8 modules
Drupal Meetup StuttgartDrupal Meetup Stuttgart
06/11/2015
1. What are Entities?1. What are Entities?
“ loadable thingies, thatloadable thingies, that
can optionally be fieldablecan optionally be fieldable
https://www.drupal.org/node/460320
Entities areEntities are
Entity types - node, user, ...
-> Base fields, like nid, title, author
Bundles - article, story, ...
-> Bundle fields, like an image
All entities aren't equal, they may haveAll entities aren't equal, they may have
differentdifferent
Entities in Drupal 7 (Core)Entities in Drupal 7 (Core)
Nodes
Users
Taxonomy vocabularies
Taxonomy terms
Files
Comments
Entities in Drupal 8Entities in Drupal 8
Entities in Drupal 8 are classes
Can be content entities or config entities
Extend corresponding base classes
class Contact extends ContentEntityBase implements ContactInterface {
...
}
Entity examples in Drupal 8 (Core)Entity examples in Drupal 8 (Core)
Content Entities Configuration entities
Aggregator feed / item
Block content
Comment
Message
File
Menu link
Content (aka node)
Shortcut
Taxonomy term
User
Action
Block
Breakpoint
Comment type
Content type
Date format
Field
Image Style
Language
Menu
Role
View
...
2. Working with entities:2. Working with entities:
CRUDCRUD
CRUD =CRUD =
Create
Read
Update
Delete
entities, implemented by something called
Entity API
The problem with D7:The problem with D7:
Entity API is incomplete, only the R exists (entity_load)
Most missing parts implemented by contrib (entity module)
But many developers keep using proprietary D6 functions,
still not removed from core:
- node_load(), node_save()
- user_load(), user_save()
- taxonomy_get_term_by_name()
- taxonomy_vocabulary_delete()
- ...
Drupal 8: Entity API in core!Drupal 8: Entity API in core!
Streamlines the way of working with entities
Easy extendable / testable (OOP)
No need for proprietary stuff
3. Read entities (C3. Read entities (CRRUD)UD)
Drupal 7: proprietary functionsDrupal 7: proprietary functions
// Load a single node
$customer = node_load(526);
// Load multiple users
$users = user_load_multiple(array(77, 83, 121));
// Load a single term
$category = taxonomy_term_load(19);
Drupal 8: entity managerDrupal 8: entity manager
// Load a single node
$storage = Drupal::entityManager()->getStorage('node');
$customer = $storage->load(526);
// Load multiple users
$storage = Drupal::entityManager()->getStorage('user');
$users = $storage->loadMultiple(array(77, 83, 121));
// Load a single term
$storage = Drupal::entityManager()->getStorage('taxonomy_term');
$category = $storage->load(19);
Better: use Dependency Injection, not static calls!
Drupal 8: static callsDrupal 8: static calls
// Load a single node
$customer = Node::load(526);
// Load multiple users
$users = User::loadMultiple(array(77, 83, 121));
// Load a single term
$category = Term::load(19);
Drupal 8: procedural wrappersDrupal 8: procedural wrappers
// Load a single node
$customer = entity_load('node', 526);
// Load multiple users
$users = entity_load_multiple('user', array(77, 83, 121));
// Load a single term
$category = entity_load('taxonomy_term', 19);
4. Create entities (4. Create entities (CCRUD)RUD)
Drupal 7: generic classesDrupal 7: generic classes
$node = new stdClass();
$node->type = 'article';
node_object_prepare($node);
$node->title = 'Breaking News';
node_save($node);
$storage = Drupal::entityManager()->getStorage('node');
$node = $storage->create(array('type' => 'article', 'title' => 'Breaking News'));
$node->save();
Drupal 8: entity managerDrupal 8: entity manager
$node = Node::create(array('type' => 'article', 'title' => 'Breaking News'));
$node->save();
Drupal 8: static callDrupal 8: static call
5. Update entities (CR5. Update entities (CRUUD)D)
Drupal 7: proprietary functionsDrupal 7: proprietary functions
$node = node_load(331);
$node->title = 'Changed title';
node_save($node);
Drupal 8: entity managerDrupal 8: entity manager
$storage = Drupal::entityManager()->getStorage('node');
$node = $storage->load(526);
$node->setTitle('Changed title');
$node->save();
Drupal 8: procedural wrapperDrupal 8: procedural wrapper
$node = entity_load('node', 526);
$node->setTitle('Changed title');
$node->save();
6. Delete entities (CRU6. Delete entities (CRUDD))
Drupal 7: proprietary functionsDrupal 7: proprietary functions
node_delete(529);
node_delete_multiple(array(22,56,77));
Drupal 8: procedural wrapperDrupal 8: procedural wrapper
entity_delete_multiple('node', array(529));
entity_delete_multiple('node', array(22,56,77));
$storage = Drupal::entityManager()->getStorage('node');
$node = $storage->loadMultiple(array(529));
$storage->delete($node);
$storage = Drupal::entityManager()->getStorage('node');
$nodes = $storage->loadMultiple(array(22,56,77));
$storage->delete($nodes);
Drupal 8: entity managerDrupal 8: entity manager
7. Accessing entities7. Accessing entities
Accessing entities in D7Accessing entities in D7
$car = node_load(23);
$title = $car->title;
$color = $car->field_color['und'][0]['value']
$manufacturer = $car->field_manufacturer['und'][0]['target_id']
...
Or, thanks to Entity Metadata Wrapper (contrib):
$car = entity_metadata_wrapper('node', 23);
$title = $car->title;
$color = $car->field_color->value();
$manufacturer = $car->field_manufacturer->raw();
...
No getter / setter methods, but some lovely arrays:
Accessing entities in D8Accessing entities in D8
$nid = $car->id();
$nid = $car->get('nid')->value;
$nid = $car->nid->value;
$title = $car->label();
$title = $car->getTitle();
$title = $car->get('title')->value;
$title = $car->title->value;
$created = $car->getCreatedTime();
$created = $car->get('created')->value;
$created = $car->created->value;
$color = $car->field_color->value;
$color = $car->get('field_color')->value;
$uid = $car->getOwnerId();
$uid = $car->get('uid')->target_id;
$uid = $car->uid->value;
$user = $car->getOwner();
$user = $car->get('uid')->entity;
Getter / setter methods in core, but ambivalent:
Reasonable, or just bad DX ?
DrupalnodeEntityNode Object(
[values:protected] => Array(
[vid] => Array([x-default] => 1)
[langcode] => Array ([x-default] => en)
[revision_timestamp] => Array([x-default] => 1433958690)
[revision_uid] => Array([x-default] => 1)
[revision_log] => Array([x-default] => )
[nid] => Array([x-default] => 1)
[type] => Array([x-default] => test)
[uuid] => Array([x-default] => 46b4af73-616a-494a-8a16-22be8dfe592e)
[isDefaultRevision] => Array([x-default] => 1)
[title] => Array([x-default] => Breaking News)
[uid] => Array([x-default] => 1)
[status] => Array([x-default] => 1)
[created] => Array([x-default] => 1433958679)
[changed] => Array([x-default] => 1433958679)
[promote] => Array([x-default] => 1)
[sticky] => Array([x-default] => 0)
[default_langcode] => Array([x-default] => 1)
)
[fields:protected] => Array()
[fieldDefinitions:protected] =>
[languages:protected] =>
[langcodeKey:protected] => langcode
[defaultLangcodeKey:protected] => default_langcode
[activeLangcode:protected] => x-default
[defaultLangcode:protected] => en
[translations:protected] => Array(
[x-default] => Array([status] => 1)
)
[translationInitialize:protected] =>
[newRevision:protected] =>
[isDefaultRevision:protected] => 1
[entityKeys:protected] => Array(
[bundle] => test
[id] => 1
[revision] => 1
[label] => Breaking News
[langcode] => en
[uuid] => 46b4af73-616a-494a-8a16-22be8dfe592e
[default_langcode] => 1
)
[entityTypeId:protected] => node
[enforceIsNew:protected] =>
[typedData:protected] =>
[_serviceIds:protected] => Array()
)
By the way...By the way...
$node->values['title']['x-default'] ?
$node->entityKeys['label'] ?
Don't even think of it!
8. Entity Queries8. Entity Queries
Drupal 7: Entity Field QueryDrupal 7: Entity Field Query
$query = new EntityFieldQuery();
$query
->entityCondition('entity_type', 'node')
->entityCondition('bundle', array('product', 'movies'))
->propertyCondition('status', 1)
->fieldCondition('body', 'value', 'discount', 'CONTAINS')
->propertyOrderBy('created', 'DESC');
$result = $query->execute();
if (!empty($result['node'])) {
$nodes = node_load_multiple(array_keys($result['node']))
}
Useful, but
why is this called Entity Field Query?
why are there three condition types?
what's the result structure?
Drupal 8: Entity QueryDrupal 8: Entity Query
$storage = Drupal::entityManager()->getStorage('node');
$query = $storage->getQuery();
$query
->Condition('type', array('product', 'movies'))
->Condition('status', 1)
->Condition('body', 'value', 'discount', 'CONTAINS')
->OrderBy('created', 'DESC');
$result = $query->execute();
$nodes = $storage->loadMultiple($result);
9. There's even more...9. There's even more...
Create your own customCreate your own custom
Entity types
Bundles
Entity forms
Access handlers
Storage controllers
...
Thank You!Thank You!
http://slides.com/drubb
http://slideshare.net/drubb

More Related Content

What's hot

Drupal 8 templating with twig
Drupal 8 templating with twigDrupal 8 templating with twig
Drupal 8 templating with twig
Taras Omelianenko
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
Magecom Ukraine
 
Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5
Wildan Maulana
 
Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4
Fabien Potencier
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010
Fabien Potencier
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
Fabien Potencier
 

What's hot (20)

Field api.From d7 to d8
Field api.From d7 to d8Field api.From d7 to d8
Field api.From d7 to d8
 
Top Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in DrupalTop Ten Reasons to Use EntityFieldQuery in Drupal
Top Ten Reasons to Use EntityFieldQuery in Drupal
 
Drupal 8 templating with twig
Drupal 8 templating with twigDrupal 8 templating with twig
Drupal 8 templating with twig
 
Entity Query API
Entity Query APIEntity Query API
Entity Query API
 
Drupal 8 migrate!
Drupal 8 migrate!Drupal 8 migrate!
Drupal 8 migrate!
 
Система рендеринга в Magento
Система рендеринга в MagentoСистема рендеринга в Magento
Система рендеринга в Magento
 
Doctrine 2
Doctrine 2Doctrine 2
Doctrine 2
 
Drupal Field API. Practical usage
Drupal Field API. Practical usageDrupal Field API. Practical usage
Drupal Field API. Practical usage
 
Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 
8 things to know about theming in drupal 8
8 things to know about theming in drupal 88 things to know about theming in drupal 8
8 things to know about theming in drupal 8
 
Drupal Render API
Drupal Render APIDrupal Render API
Drupal Render API
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindia object oriented programming in php
Synapseindia object oriented programming in php
 
Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5
 
Object Oriented PHP5
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5
 
Multilingual drupal 7
Multilingual drupal 7Multilingual drupal 7
Multilingual drupal 7
 
Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4Dependency injection in PHP 5.3/5.4
Dependency injection in PHP 5.3/5.4
 
Dependency injection-zendcon-2010
Dependency injection-zendcon-2010Dependency injection-zendcon-2010
Dependency injection-zendcon-2010
 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
 
Drupal II: The SQL
Drupal II: The SQLDrupal II: The SQL
Drupal II: The SQL
 
Drupal 8 Hooks
Drupal 8 HooksDrupal 8 Hooks
Drupal 8 Hooks
 

Viewers also liked

Viewers also liked (12)

Drupal 8: TWIG Template Engine
Drupal 8:  TWIG Template EngineDrupal 8:  TWIG Template Engine
Drupal 8: TWIG Template Engine
 
Contribuir a Drupal
Contribuir a DrupalContribuir a Drupal
Contribuir a Drupal
 
Custom entities in d8
Custom entities in d8Custom entities in d8
Custom entities in d8
 
Things Made Easy: One Click CMS Integration with Solr & Drupal
Things Made Easy: One Click CMS Integration with Solr & DrupalThings Made Easy: One Click CMS Integration with Solr & Drupal
Things Made Easy: One Click CMS Integration with Solr & Drupal
 
Demystifying AJAX Callback Commands in Drupal 8
Demystifying AJAX Callback Commands in Drupal 8Demystifying AJAX Callback Commands in Drupal 8
Demystifying AJAX Callback Commands in Drupal 8
 
Single Page Applications in Drupal
Single Page Applications in DrupalSingle Page Applications in Drupal
Single Page Applications in Drupal
 
Making Sense of Twig
Making Sense of TwigMaking Sense of Twig
Making Sense of Twig
 
State of Search, Solr and Facets in Drupal 8 - Drupalcamp Belgium 2015
State of Search, Solr and Facets in Drupal 8 - Drupalcamp Belgium 2015State of Search, Solr and Facets in Drupal 8 - Drupalcamp Belgium 2015
State of Search, Solr and Facets in Drupal 8 - Drupalcamp Belgium 2015
 
Intro to Apache Solr for Drupal
Intro to Apache Solr for DrupalIntro to Apache Solr for Drupal
Intro to Apache Solr for Drupal
 
Drupal 8 + Elasticsearch + Docker
Drupal 8 + Elasticsearch + DockerDrupal 8 + Elasticsearch + Docker
Drupal 8 + Elasticsearch + Docker
 
Webform and Drupal 8
Webform and Drupal 8Webform and Drupal 8
Webform and Drupal 8
 
Using VueJS in front of Drupal 8
Using VueJS in front of Drupal 8Using VueJS in front of Drupal 8
Using VueJS in front of Drupal 8
 

Similar to Drupal 8: Entities

Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalyst
svilen.ivanov
 
Dependency injection in Drupal 8
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8
Alexei Gorobets
 

Similar to Drupal 8: Entities (20)

Your Entity, Your Code
Your Entity, Your CodeYour Entity, Your Code
Your Entity, Your Code
 
Drupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency InjectionDrupal 8 Services And Dependency Injection
Drupal 8 Services And Dependency Injection
 
Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
Drupal 7 Entity & Entity API
Drupal 7 Entity & Entity APIDrupal 7 Entity & Entity API
Drupal 7 Entity & Entity API
 
Utilization of zend an ultimate alternate for intense data processing
Utilization of zend  an ultimate alternate for intense data processingUtilization of zend  an ultimate alternate for intense data processing
Utilization of zend an ultimate alternate for intense data processing
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalyst
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 
Let's write secure Drupal code! Drupal MountainCamp 2019
Let's write secure Drupal code! Drupal MountainCamp 2019Let's write secure Drupal code! Drupal MountainCamp 2019
Let's write secure Drupal code! Drupal MountainCamp 2019
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mind
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
 
Drupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.comDrupal 7 entities & TextbookMadness.com
Drupal 7 entities & TextbookMadness.com
 
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
 
Let's write secure Drupal code!
Let's write secure Drupal code!Let's write secure Drupal code!
Let's write secure Drupal code!
 
Dependency injection in Drupal 8
Dependency injection in Drupal 8Dependency injection in Drupal 8
Dependency injection in Drupal 8
 
Drupal Module Development - OSI Days 2010
Drupal Module Development - OSI Days 2010Drupal Module Development - OSI Days 2010
Drupal Module Development - OSI Days 2010
 
Drupal Module Development
Drupal Module DevelopmentDrupal Module Development
Drupal Module Development
 
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, GermanyLet's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
Let's write secure Drupal code! - 13.09.2018 @ Drupal Europe, Darmstadt, Germany
 

More from drubb (9)

Barrierefreie Webseiten
Barrierefreie WebseitenBarrierefreie Webseiten
Barrierefreie Webseiten
 
Drupal 9 Entity Bundle Classes
Drupal 9 Entity Bundle ClassesDrupal 9 Entity Bundle Classes
Drupal 9 Entity Bundle Classes
 
Drupal 8 Dependency Injection Using Traits
Drupal 8 Dependency Injection Using TraitsDrupal 8 Dependency Injection Using Traits
Drupal 8 Dependency Injection Using Traits
 
Closing the Drupal Hosting Gap - A Review of Wodby
Closing the Drupal Hosting Gap - A Review of WodbyClosing the Drupal Hosting Gap - A Review of Wodby
Closing the Drupal Hosting Gap - A Review of Wodby
 
Composer & Drupal
Composer & DrupalComposer & Drupal
Composer & Drupal
 
Headless Drupal
Headless DrupalHeadless Drupal
Headless Drupal
 
Spamschutzverfahren für Drupal
Spamschutzverfahren für DrupalSpamschutzverfahren für Drupal
Spamschutzverfahren für Drupal
 
Drupal 8: Neuerungen im Überblick
Drupal 8:  Neuerungen im ÜberblickDrupal 8:  Neuerungen im Überblick
Drupal 8: Neuerungen im Überblick
 
Drupal Entities
Drupal EntitiesDrupal Entities
Drupal Entities
 

Recently uploaded

pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdfpdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
JOHNBEBONYAP1
 
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girlsRussian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Monica Sydney
 
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
pxcywzqs
 
一比一原版奥兹学院毕业证如何办理
一比一原版奥兹学院毕业证如何办理一比一原版奥兹学院毕业证如何办理
一比一原版奥兹学院毕业证如何办理
F
 
Abu Dhabi Escorts Service 0508644382 Escorts in Abu Dhabi
Abu Dhabi Escorts Service 0508644382 Escorts in Abu DhabiAbu Dhabi Escorts Service 0508644382 Escorts in Abu Dhabi
Abu Dhabi Escorts Service 0508644382 Escorts in Abu Dhabi
Monica Sydney
 
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
ydyuyu
 
Indian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Indian Escort in Abu DHabi 0508644382 Abu Dhabi EscortsIndian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Indian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Monica Sydney
 
call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7
call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7
call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

Meaning of On page SEO & its process in detail.
Meaning of On page SEO & its process in detail.Meaning of On page SEO & its process in detail.
Meaning of On page SEO & its process in detail.
 
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdfpdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
 
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girlsRussian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
 
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrStory Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
 
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime NagercoilNagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
 
APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53
 
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
20240507 QFM013 Machine Intelligence Reading List April 2024.pdf
 
Local Call Girls in Seoni 9332606886 HOT & SEXY Models beautiful and charmin...
Local Call Girls in Seoni  9332606886 HOT & SEXY Models beautiful and charmin...Local Call Girls in Seoni  9332606886 HOT & SEXY Models beautiful and charmin...
Local Call Girls in Seoni 9332606886 HOT & SEXY Models beautiful and charmin...
 
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
 
一比一原版奥兹学院毕业证如何办理
一比一原版奥兹学院毕业证如何办理一比一原版奥兹学院毕业证如何办理
一比一原版奥兹学院毕业证如何办理
 
Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...
Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...
Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...
 
Ballia Escorts Service Girl ^ 9332606886, WhatsApp Anytime Ballia
Ballia Escorts Service Girl ^ 9332606886, WhatsApp Anytime BalliaBallia Escorts Service Girl ^ 9332606886, WhatsApp Anytime Ballia
Ballia Escorts Service Girl ^ 9332606886, WhatsApp Anytime Ballia
 
Abu Dhabi Escorts Service 0508644382 Escorts in Abu Dhabi
Abu Dhabi Escorts Service 0508644382 Escorts in Abu DhabiAbu Dhabi Escorts Service 0508644382 Escorts in Abu Dhabi
Abu Dhabi Escorts Service 0508644382 Escorts in Abu Dhabi
 
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
 
Indian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Indian Escort in Abu DHabi 0508644382 Abu Dhabi EscortsIndian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Indian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
 
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
 
call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7
call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7
call girls in Anand Vihar (delhi) call me [🔝9953056974🔝] escort service 24X7
 
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
best call girls in Hyderabad Finest Escorts Service 📞 9352988975 📞 Available ...
 
Trump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts SweatshirtTrump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts Sweatshirt
 
Best SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency DallasBest SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency Dallas
 

Drupal 8: Entities

  • 1. Drupal 8: EntitiesDrupal 8: Entities Working with entities in Drupal 8 modulesWorking with entities in Drupal 8 modules Drupal Meetup StuttgartDrupal Meetup Stuttgart 06/11/2015
  • 2. 1. What are Entities?1. What are Entities?
  • 3. “ loadable thingies, thatloadable thingies, that can optionally be fieldablecan optionally be fieldable https://www.drupal.org/node/460320 Entities areEntities are
  • 4. Entity types - node, user, ... -> Base fields, like nid, title, author Bundles - article, story, ... -> Bundle fields, like an image All entities aren't equal, they may haveAll entities aren't equal, they may have differentdifferent
  • 5. Entities in Drupal 7 (Core)Entities in Drupal 7 (Core) Nodes Users Taxonomy vocabularies Taxonomy terms Files Comments
  • 6. Entities in Drupal 8Entities in Drupal 8 Entities in Drupal 8 are classes Can be content entities or config entities Extend corresponding base classes class Contact extends ContentEntityBase implements ContactInterface { ... }
  • 7. Entity examples in Drupal 8 (Core)Entity examples in Drupal 8 (Core) Content Entities Configuration entities Aggregator feed / item Block content Comment Message File Menu link Content (aka node) Shortcut Taxonomy term User Action Block Breakpoint Comment type Content type Date format Field Image Style Language Menu Role View ...
  • 8. 2. Working with entities:2. Working with entities: CRUDCRUD
  • 9. CRUD =CRUD = Create Read Update Delete entities, implemented by something called Entity API
  • 10. The problem with D7:The problem with D7: Entity API is incomplete, only the R exists (entity_load) Most missing parts implemented by contrib (entity module) But many developers keep using proprietary D6 functions, still not removed from core: - node_load(), node_save() - user_load(), user_save() - taxonomy_get_term_by_name() - taxonomy_vocabulary_delete() - ...
  • 11. Drupal 8: Entity API in core!Drupal 8: Entity API in core! Streamlines the way of working with entities Easy extendable / testable (OOP) No need for proprietary stuff
  • 12. 3. Read entities (C3. Read entities (CRRUD)UD)
  • 13. Drupal 7: proprietary functionsDrupal 7: proprietary functions // Load a single node $customer = node_load(526); // Load multiple users $users = user_load_multiple(array(77, 83, 121)); // Load a single term $category = taxonomy_term_load(19); Drupal 8: entity managerDrupal 8: entity manager // Load a single node $storage = Drupal::entityManager()->getStorage('node'); $customer = $storage->load(526); // Load multiple users $storage = Drupal::entityManager()->getStorage('user'); $users = $storage->loadMultiple(array(77, 83, 121)); // Load a single term $storage = Drupal::entityManager()->getStorage('taxonomy_term'); $category = $storage->load(19); Better: use Dependency Injection, not static calls!
  • 14. Drupal 8: static callsDrupal 8: static calls // Load a single node $customer = Node::load(526); // Load multiple users $users = User::loadMultiple(array(77, 83, 121)); // Load a single term $category = Term::load(19); Drupal 8: procedural wrappersDrupal 8: procedural wrappers // Load a single node $customer = entity_load('node', 526); // Load multiple users $users = entity_load_multiple('user', array(77, 83, 121)); // Load a single term $category = entity_load('taxonomy_term', 19);
  • 15. 4. Create entities (4. Create entities (CCRUD)RUD)
  • 16. Drupal 7: generic classesDrupal 7: generic classes $node = new stdClass(); $node->type = 'article'; node_object_prepare($node); $node->title = 'Breaking News'; node_save($node); $storage = Drupal::entityManager()->getStorage('node'); $node = $storage->create(array('type' => 'article', 'title' => 'Breaking News')); $node->save(); Drupal 8: entity managerDrupal 8: entity manager $node = Node::create(array('type' => 'article', 'title' => 'Breaking News')); $node->save(); Drupal 8: static callDrupal 8: static call
  • 17. 5. Update entities (CR5. Update entities (CRUUD)D)
  • 18. Drupal 7: proprietary functionsDrupal 7: proprietary functions $node = node_load(331); $node->title = 'Changed title'; node_save($node); Drupal 8: entity managerDrupal 8: entity manager $storage = Drupal::entityManager()->getStorage('node'); $node = $storage->load(526); $node->setTitle('Changed title'); $node->save(); Drupal 8: procedural wrapperDrupal 8: procedural wrapper $node = entity_load('node', 526); $node->setTitle('Changed title'); $node->save();
  • 19. 6. Delete entities (CRU6. Delete entities (CRUDD))
  • 20. Drupal 7: proprietary functionsDrupal 7: proprietary functions node_delete(529); node_delete_multiple(array(22,56,77)); Drupal 8: procedural wrapperDrupal 8: procedural wrapper entity_delete_multiple('node', array(529)); entity_delete_multiple('node', array(22,56,77)); $storage = Drupal::entityManager()->getStorage('node'); $node = $storage->loadMultiple(array(529)); $storage->delete($node); $storage = Drupal::entityManager()->getStorage('node'); $nodes = $storage->loadMultiple(array(22,56,77)); $storage->delete($nodes); Drupal 8: entity managerDrupal 8: entity manager
  • 21. 7. Accessing entities7. Accessing entities
  • 22. Accessing entities in D7Accessing entities in D7 $car = node_load(23); $title = $car->title; $color = $car->field_color['und'][0]['value'] $manufacturer = $car->field_manufacturer['und'][0]['target_id'] ... Or, thanks to Entity Metadata Wrapper (contrib): $car = entity_metadata_wrapper('node', 23); $title = $car->title; $color = $car->field_color->value(); $manufacturer = $car->field_manufacturer->raw(); ... No getter / setter methods, but some lovely arrays:
  • 23. Accessing entities in D8Accessing entities in D8 $nid = $car->id(); $nid = $car->get('nid')->value; $nid = $car->nid->value; $title = $car->label(); $title = $car->getTitle(); $title = $car->get('title')->value; $title = $car->title->value; $created = $car->getCreatedTime(); $created = $car->get('created')->value; $created = $car->created->value; $color = $car->field_color->value; $color = $car->get('field_color')->value; $uid = $car->getOwnerId(); $uid = $car->get('uid')->target_id; $uid = $car->uid->value; $user = $car->getOwner(); $user = $car->get('uid')->entity; Getter / setter methods in core, but ambivalent: Reasonable, or just bad DX ?
  • 24. DrupalnodeEntityNode Object( [values:protected] => Array( [vid] => Array([x-default] => 1) [langcode] => Array ([x-default] => en) [revision_timestamp] => Array([x-default] => 1433958690) [revision_uid] => Array([x-default] => 1) [revision_log] => Array([x-default] => ) [nid] => Array([x-default] => 1) [type] => Array([x-default] => test) [uuid] => Array([x-default] => 46b4af73-616a-494a-8a16-22be8dfe592e) [isDefaultRevision] => Array([x-default] => 1) [title] => Array([x-default] => Breaking News) [uid] => Array([x-default] => 1) [status] => Array([x-default] => 1) [created] => Array([x-default] => 1433958679) [changed] => Array([x-default] => 1433958679) [promote] => Array([x-default] => 1) [sticky] => Array([x-default] => 0) [default_langcode] => Array([x-default] => 1) ) [fields:protected] => Array() [fieldDefinitions:protected] => [languages:protected] => [langcodeKey:protected] => langcode [defaultLangcodeKey:protected] => default_langcode [activeLangcode:protected] => x-default [defaultLangcode:protected] => en [translations:protected] => Array( [x-default] => Array([status] => 1) ) [translationInitialize:protected] => [newRevision:protected] => [isDefaultRevision:protected] => 1 [entityKeys:protected] => Array( [bundle] => test [id] => 1 [revision] => 1 [label] => Breaking News [langcode] => en [uuid] => 46b4af73-616a-494a-8a16-22be8dfe592e [default_langcode] => 1 ) [entityTypeId:protected] => node [enforceIsNew:protected] => [typedData:protected] => [_serviceIds:protected] => Array() ) By the way...By the way... $node->values['title']['x-default'] ? $node->entityKeys['label'] ? Don't even think of it!
  • 25. 8. Entity Queries8. Entity Queries
  • 26. Drupal 7: Entity Field QueryDrupal 7: Entity Field Query $query = new EntityFieldQuery(); $query ->entityCondition('entity_type', 'node') ->entityCondition('bundle', array('product', 'movies')) ->propertyCondition('status', 1) ->fieldCondition('body', 'value', 'discount', 'CONTAINS') ->propertyOrderBy('created', 'DESC'); $result = $query->execute(); if (!empty($result['node'])) { $nodes = node_load_multiple(array_keys($result['node'])) } Useful, but why is this called Entity Field Query? why are there three condition types? what's the result structure?
  • 27. Drupal 8: Entity QueryDrupal 8: Entity Query $storage = Drupal::entityManager()->getStorage('node'); $query = $storage->getQuery(); $query ->Condition('type', array('product', 'movies')) ->Condition('status', 1) ->Condition('body', 'value', 'discount', 'CONTAINS') ->OrderBy('created', 'DESC'); $result = $query->execute(); $nodes = $storage->loadMultiple($result);
  • 28. 9. There's even more...9. There's even more...
  • 29. Create your own customCreate your own custom Entity types Bundles Entity forms Access handlers Storage controllers ...