Drupal 7 Entity & Entity API

Post on 08-May-2015

1.883 views 11 download

description

http://drupalcity.de/session/drupal-7-development-done-right-leverage-entities

Transcript of Drupal 7 Entity & Entity API

Drupal 7 development done right:

Leverage entities!

Presented by Wolfgang Ziegler

Who I am...

Wolfgang Ziegler // d.o. fagowolfgangziegler.nettwitter.com/the_real_fago

Entity API

So this talk is about the

Drupal 7's entity API

and the Entity API module

http://drupal.org/7http://drupal.org/project/entity

What are entities?

Entities are the foundation for fields, but

Entity != Fieldable Entity

While most entity types are fieldable, not all are.

Drupal's Data

Data

that is integrated into Drupal

Developing with entities

Base your module upon entities (e.g. Search-api)

Store data

Provide new entity types

Extend other entity types

Fields, custom properties

Drupal 7 Entity API

Entities are required to be

Loadable - entity_load()

Identifiable

Drupal 7 – Entity hooks

hook_entity_load(),hook_entity_presave(),hook_entity_insert(), hook_entity_update(), hook_entity_delete(),hook_entity_prepare_view, hook_entity_view().

Drupal 7: Metadata

Entity-info (bundles, view-modes)

Labels (via entity_label())

URIs (via entity_uri())

EntityFieldQuery

API for querying entities

Conditions on entity properties as well as fields

Query for entity properties and fields (in a single storage) at once

Query across multiple entity types (only fields).

Extendable via hook_entity_query_alter().

Entity API module

So far, this all is in Drupal 7.

The Entity API module builds upon that to

ease dealing with any entity type

easy providing new entity type

(optionally fieldable, exportable)

Working with entities...

entity_load(), entity_save(), entity_create(), entity_delete()

entity_view(), entity_access(), entity_label(), entity_uri()

entity_id(), entity_extract_ids()

entity_export(), entity_import()

entity_get_info(), entity_get_property_info()

core

Entity property info

A hook defined by the Entity API module.

Allows modules to describe entity properties (including fields).

Properties have to be described by a set of defined data types ('text', 'date', 'user', ..)

Includes human readable description, 'getter callback', optionally a setter, access permissions.

Property info example // Add meta-data about the basic node properties. $properties = &$info['node']['properties'];

$properties['title'] = array( 'label' => t("Title"), 'description' => t("The title of the node."), 'setter callback' => 'entity_property_verbatim_set', 'schema field' => 'title', 'required' => TRUE, ); $properties['author'] = array( 'label' => t("Author"), 'type' => 'user', 'description' => t("The author of the node."), 'getter callback' => 'entity_metadata_node_get_properties', 'setter callback' => 'entity_metadata_node_set_properties', 'setter permission' => 'administer nodes', 'required' => TRUE, 'schema field' => 'uid', );

Entity metadata wrappers

Some useful wrapper classes that ease dealing with entities and their properties.

$wrapper = entity_metadata_wrapper('node', $node);$wrapper = entity_metadata_wrapper('node', $nid);

$wrapper->author->profile->field_name->value();$wrapper->author->profile->field_name->set('New name');

$wrapper->language('de')->body->summary->value();

$wrapper->author->mail->access('edit') ? TRUE : FALSE;$wrapper->author->roles->optionsList();

$wrapper->field_files[0]->description = 'The first file';$wrapper->save();$node = $wrapper->value();

How to provide a new entity type?

Write your own controller, implement CRUD and hooks.

Make use of the Entity API module

Using the entity API module....

Implement hook_entity_info().

Define your schema in hook_schema().

Best practice: {entity_type}_load(), {entity_type}_create(), {entity_type}_save(), {entity_type}_delete_multiple(), ...

EntityAPIController: What it does

It invokes all CRUD related hooks for you!

Document them (template handbooks)→

Invokes field-attachers for you.

Allows using classes...

MyEntity extends Entity

Eases customizing labels, URIs, display or saving.

$entity->entityType();$entity->identifier();$entity->view();$entity->delete();$entity->save();$entity->label(), $entity->uri(), $entity->entityInfo(), ..

Fields

Entity-info: Define your entity type as fieldable.

Field attachers are called (including 'view')

Add bundles, optionally exportable:

Add a separate entity type for bundles Bundle entity (Profile type, Profile)→

Specify the bundle entity type to be 'bundle of' another entity type (Profile type is bundle of Profile)

Exportable entities

Alternative to ctools exportables

Make use of existing CRUD functionality

Machine-names

Syncs defaults to the database to support hooks

→ provides usual default hook + CRUD hooks allows using the DB for sorting, filtering, ...→

Make it exportable

Specify your entity type as exportable in hook_entity_info() + use EntityAPIControllerExportable

Make use of machine names.

→ specify a 'name' key under entity-keys.

Add entity_exportable_schema_fields() to your schema ('module', 'status').

Import / Export

$export = entity_export($entity_type, $entity);

$entity = entity_import($entity_type, $export);

By default: Export as JSON

Example profile type in code/** * Implements hook_default_profile2_type(). */function recruiter_resume_default_profile2_type() { $items = array(); $items['resume'] = entity_import('profile2_type', '{ "userCategory" : false, "userView" : false, "type" : "resume", "label" : "Resume", "weight" : "0", "data" : { "use_page" : 1}, "rdf_mapping" : [] }'); return $items;}

Module integrations

Very basic entity property info (read-only)

Views integration

Rules integration (events)

Token support for all entity properties via the “Entity tokens” module

Features integration (for exportables)

Add property info!

Get Views integration (specify schema-field)

Get tokens for all properties, via entity tokens.

Obtain support of modules building upon it like

Rules

Search API

Restful Web Services (short: RestWS)

Entity property info – Best practices

Do not provide the ids of related entities:

Wrong: node:uid & node:author

Right: node:author (data type: user)

→ Entity references having a 'schema-field' get Views integration.

Admin UI

Enable the admin UI via hook_entity_info().

Providean entity form andan access callback for entity_access().

Customize it by overriding the controller.

UI suits well for managing configuration.

Entity Form: Best practices

Use form id {entity_type}_form

Put the entity in $form_state[{entity_type}]

Update the entity in $form_state in your submit handlers and rebuild / finish.

Use entity_form_submit_build_entity() to create {entity_type}_form_submit_build_{entity_type}, which submit handlers may re-use.

Entity API docs

→ in code entity.api.php

→ in the handbooks

http://drupal.org/node/878784

→ Learn from examples!

Learn from examples...

Profile2:

Fieldable profile entity

Exportable bundle entity (Profile type)

Admin UI implemented via the Entity API UI

Views / Rules / Features integration via Entity API

Test-module, Field-collection, Organic groups, Rules, Message, Drupal commerce, ....

D7 Development done right?

Work with Drupal's data by building upon entities and fields.

Manage your data

using new entity types

Fields or entity properties

API: Does it work without forms?

Drupal 8

Classes EntityInterface→

basic CRUD, UUID support built in

See g.d.o./node/171554

CMI API for configuration→

Deprecating configuration entities?

Drupal 8

Entity Property API

hook_entity_property_info()

Close the gap between properties and fields

Translation

Access

Validation

Questions?Questions?

Thanks!