5 * Documentation landing page and topics, plus core library hooks.
10 * Welcome to the Drupal API Documentation!
12 * This site is an API reference for Drupal, generated from comments embedded
13 * in the source code. More in-depth documentation can be found at
14 * https://www.drupal.org/developing/api.
16 * Here are some topics to help you get started developing with Drupal.
18 * @section essentials Essential background concepts
20 * - @link oo_conventions Object-oriented conventions used in Drupal @endlink
21 * - @link extending Extending and altering Drupal @endlink
22 * - @link best_practices Security and best practices @endlink
23 * - @link info_types Types of information in Drupal @endlink
25 * @section interface User interface
27 * - @link menu Menu entries, local tasks, and other links @endlink
28 * - @link routing Routing API and page controllers @endlink
29 * - @link form_api Forms @endlink
30 * - @link block_api Blocks @endlink
31 * - @link ajax Ajax @endlink
33 * @section store_retrieve Storing and retrieving data
35 * - @link entity_api Entities @endlink
36 * - @link field Fields @endlink
37 * - @link config_api Configuration API @endlink
38 * - @link state_api State API @endlink
39 * - @link views_overview Views @endlink
40 * - @link database Database abstraction layer @endlink
42 * @section other_essentials Other essential APIs
44 * - @link plugin_api Plugins @endlink
45 * - @link container Services and the Dependency Injection Container @endlink
46 * - @link events Events @endlink
47 * - @link i18n Internationalization @endlink
48 * - @link cache Caching @endlink
49 * - @link utility Utility classes and functions @endlink
50 * - @link user_api User accounts, permissions, and roles @endlink
51 * - @link theme_render Render API @endlink
52 * - @link themeable Theme system @endlink
53 * - @link update_api Update API @endlink
54 * - @link migration Migration @endlink
56 * @section additional Additional topics
58 * - @link batch Batch API @endlink
59 * - @link queue Queue API @endlink
60 * - @link typed_data Typed Data @endlink
61 * - @link testing Automated tests @endlink
62 * - @link php_assert PHP Runtime Assert Statements @endlink
63 * - @link third_party Integrating third-party applications @endlink
65 * @section more_info Further information
67 * - @link https://api.drupal.org/api/drupal/groups/8 All topics @endlink
68 * - @link https://www.drupal.org/project/examples Examples project (sample modules) @endlink
69 * - @link https://www.drupal.org/list-changes API change notices @endlink
70 * - @link https://www.drupal.org/developing/api/8 Drupal 8 API longer references @endlink
74 * @defgroup third_party REST and Application Integration
76 * Integrating third-party applications using REST and related operations.
78 * @section sec_overview Overview of web services
79 * Web services make it possible for applications and web sites to read and
80 * update information from other web sites. There are several standard
81 * techniques for providing web services, including:
82 * - SOAP: http://wikipedia.org/wiki/SOAP
83 * - XML-RPC: http://wikipedia.org/wiki/XML-RPC
84 * - REST: http://wikipedia.org/wiki/Representational_state_transfer
85 * Drupal sites can both provide web services and integrate third-party web
88 * @section sec_rest_overview Overview of REST
89 * The REST technique uses basic HTTP requests to obtain and update data, where
90 * each web service defines a specific API (HTTP GET and/or POST parameters and
91 * returned response) for its HTTP requests. REST requests are separated into
92 * several types, known as methods, including:
93 * - GET: Requests to obtain data.
94 * - POST: Requests to update or create data.
95 * - PUT: Requests to update or create data (limited support, currently unused
96 * by entity resources).
97 * - PATCH: Requests to update a subset of data, such as one field.
98 * - DELETE: Requests to delete data.
99 * The Drupal Core REST module provides support for GET, POST, PATCH, and DELETE
100 * quests on entities, GET requests on the database log from the Database
101 * Logging module, and a plugin framework for providing REST support for other
102 * data and other methods.
104 * REST requests can be authenticated. The Drupal Core Basic Auth module
105 * provides authentication using the HTTP Basic protocol; the contributed module
106 * OAuth (https://www.drupal.org/project/oauth) implements the OAuth
107 * authentication protocol. You can also use cookie-based authentication, which
108 * would require users to be logged into the Drupal site while using the
109 * application on the third-party site that is using the REST service.
111 * @section sec_rest Enabling REST for entities and the log
112 * Here are the steps to take to use the REST operations provided by Drupal
114 * - Enable the REST module, plus Basic Auth (or another authentication method)
116 * - Node entity support is configured by default. If you would like to support
117 * other types of entities, you can copy
118 * core/modules/rest/config/install/rest.settings.yml to your sync
119 * configuration directory, appropriately modified for other entity types,
120 * and import it. Support for GET on the log from the Database Logging module
121 * can also be enabled in this way; in this case, the 'entity:node' line
122 * in the configuration would be replaced by the appropriate plugin ID,
124 * - Set up permissions to allow the desired REST operations for a role, and set
125 * up one or more user accounts to perform the operations.
126 * - To perform a REST operation, send a request to either the canonical URL
127 * for an entity (such as node/12345 for a node), or if the entity does not
128 * have a canonical URL, a URL like entity/(type)/(ID). The URL for a log
129 * entry is dblog/(ID). The request must have the following properties:
130 * - The request method must be set to the REST method you are using (POST,
132 * - The content type for the data you send, or the accept type for the
133 * data you are receiving, must be set to 'application/hal+json'.
134 * - If you are sending data, it must be JSON-encoded.
135 * - You'll also need to make sure the authentication information is sent
136 * with the request, unless you have allowed access to anonymous users.
138 * For more detailed information on setting up REST, see
139 * https://www.drupal.org/documentation/modules/rest.
141 * @section sec_plugins Defining new REST plugins
142 * The REST framework in the REST module has support built in for entities, but
143 * it is also an extensible plugin-based system. REST plugins implement
144 * interface \Drupal\rest\Plugin\ResourceInterface, and generally extend base
145 * class \Drupal\rest\Plugin\ResourceBase. They are annotated with
146 * \Drupal\rest\Annotation\RestResource annotation, and must be in plugin
147 * namespace subdirectory Plugin\rest\resource. For more information on how to
148 * create plugins, see the @link plugin_api Plugin API topic. @endlink
150 * If you create a new REST plugin, you will also need to enable it by
151 * providing default configuration or configuration import, as outlined in
152 * @ref sec_rest above.
154 * @section sec_integrate Integrating data from other sites into Drupal
155 * If you want to integrate data from other web sites into Drupal, here are
157 * - There are contributed modules available for integrating many third-party
158 * sites into Drupal. Search on https://www.drupal.org/project/project_module
159 * - If there is not an existing module, you will need to find documentation on
160 * the specific web services API for the site you are trying to integrate.
161 * - There are several classes and functions that are useful for interacting
163 * - You should make requests using the 'http_client' service, which
164 * implements \GuzzleHttp\ClientInterface. See the
165 * @link container Services topic @endlink for more information on
166 * services. If you cannot use dependency injection to retrieve this
167 * service, the \Drupal::httpClient() method is available. A good example
168 * of how to use this service can be found in
169 * \Drupal\aggregator\Plugin\aggregator\fetcher\DefaultFetcher
170 * - \Drupal\Component\Serialization\Json (JSON encoding and decoding).
171 * - PHP has functions and classes for parsing XML; see
172 * http://php.net/manual/refs.xml.php
177 * @defgroup state_api State API
179 * Information about the State API.
181 * The State API is one of several methods in Drupal for storing information.
182 * See the @link info_types Information types topic @endlink for an
183 * overview of the different types of information.
185 * The basic entry point into the State API is \Drupal::state(), which returns
186 * an object of class \Drupal\Core\State\StateInterface. This class has
187 * methods for storing and retrieving state information; each piece of state
188 * information is associated with a string-valued key. Example:
190 * // Get the state class.
191 * $state = \Drupal::state();
192 * // Find out when cron was last run; the key is 'system.cron_last'.
193 * $time = $state->get('system.cron_last');
194 * // Set the cron run time to the current request time.
195 * $state->set('system.cron_last', REQUEST_TIME);
198 * For more on the State API, see https://www.drupal.org/developing/api/8/state
203 * @defgroup config_api Configuration API
205 * Information about the Configuration API.
207 * The Configuration API is one of several methods in Drupal for storing
208 * information. See the @link info_types Information types topic @endlink for
209 * an overview of the different types of information. The sections below have
210 * more information about the configuration API; see
211 * https://www.drupal.org/developing/api/8/configuration for more details.
213 * @section sec_storage Configuration storage
214 * In Drupal, there is a concept of the "active" configuration, which is the
215 * configuration that is currently in use for a site. The storage used for the
216 * active configuration is configurable: it could be in the database, in files
217 * in a particular directory, or in other storage backends; the default storage
218 * is in the database. Module developers must use the configuration API to
219 * access the active configuration, rather than being concerned about the
220 * details of where and how it is stored.
222 * Configuration is divided into individual objects, each of which has a
223 * unique name or key. Some modules will have only one configuration object,
224 * typically called 'mymodule.settings'; some modules will have many. Within
225 * a configuration object, configuration settings have data types (integer,
226 * string, Boolean, etc.) and settings can also exist in a nested hierarchy,
227 * known as a "mapping".
229 * Configuration can also be overridden on a global, per-language, or
230 * per-module basis. See https://www.drupal.org/node/1928898 for more
233 * @section sec_yaml Configuration YAML files
234 * Whether or not configuration files are being used for the active
235 * configuration storage on a particular site, configuration files are always
237 * - Defining the default configuration for an extension (module, theme, or
238 * profile), which is imported to the active storage when the extension is
239 * enabled. These configuration items are located in the config/install
240 * sub-directory of the extension. Note that changes to this configuration
241 * after a module or theme is already enabled have no effect; to make a
242 * configuration change after a module or theme is enabled, you would need to
243 * uninstall/reinstall or use a hook_update_N() function.
244 * - Defining optional configuration for a module or theme. Optional
245 * configuration items are located in the config/optional sub-directory of the
246 * extension. These configuration items have dependencies that are not
247 * explicit dependencies of the extension, so they are only installed if all
248 * dependencies are met. For example, in the scenario that module A defines a
249 * dependency which requires module B, but module A is installed first and
250 * module B some time later, then module A's config/optional directory will be
251 * scanned at that time for newly met dependencies, and the configuration will
252 * be installed then. If module B is never installed, the configuration item
253 * will not be installed either.
254 * - Exporting and importing configuration.
256 * The file storage format for configuration information in Drupal is
257 * @link http://wikipedia.org/wiki/YAML YAML files. @endlink Configuration is
258 * divided into files, each containing one configuration object. The file name
259 * for a configuration object is equal to the unique name of the configuration,
260 * with a '.yml' extension. The default configuration files for each module are
261 * placed in the config/install directory under the top-level module directory,
262 * so look there in most Core modules for examples.
264 * @section sec_schema Configuration schema and translation
265 * Each configuration file has a specific structure, which is expressed as a
266 * YAML-based configuration schema. The configuration schema details the
267 * structure of the configuration, its data types, and which of its values need
268 * to be translatable. Each module needs to define its configuration schema in
269 * files in the config/schema directory under the top-level module directory, so
270 * look there in most Core modules for examples.
272 * Configuration can be internationalized; see the
273 * @link i18n Internationalization topic @endlink for more information. Data
274 * types label, text, and date_format in configuration schema are translatable;
275 * string is non-translatable text (the 'translatable' property on a schema
276 * data type definition indicates that it is translatable).
278 * @section sec_simple Simple configuration
279 * The simple configuration API should be used for information that will always
280 * have exactly one copy or version. For instance, if your module has a
281 * setting that is either on or off, then this is only defined once, and it
282 * would be a Boolean-valued simple configuration setting.
284 * The first task in using the simple configuration API is to define the
285 * configuration file structure, file name, and schema of your settings (see
286 * @ref sec_yaml above). Once you have done that, you can retrieve the active
287 * configuration object that corresponds to configuration file mymodule.foo.yml
290 * $config = \Drupal::config('mymodule.foo');
293 * This will be an object of class \Drupal\Core\Config\Config, which has methods
294 * for getting configuration information. For instance, if your YAML file
295 * structure looks like this:
302 * you can make calls such as:
304 * // Get a single value.
305 * $enabled = $config->get('enabled');
306 * // Get an associative array.
307 * $bar = $config->get('bar');
308 * // Get one element of the array.
309 * $bar_baz = $config->get('bar.baz');
312 * The Config object that was obtained and used in the previous examples does
313 * not allow you to change configuration. If you want to change configuration,
314 * you will instead need to get the Config object by making a call to
315 * getEditable() on the config factory:
317 * $config =\Drupal::service('config.factory')->getEditable('mymodule.foo');
320 * Individual configuration values can be changed or added using the set()
321 * method and saved using the save() method:
323 * // Set a scalar value.
324 * $config->set('enabled', 1);
325 * // Save the configuration.
329 * Configuration values can also be unset using the clear() method, which is
332 * $config->clear('bar.boo')->save();
333 * $config_data = $config->get('bar');
335 * In this example $config_data would return an array with one key - 'baz' -
336 * because 'boo' was unset.
338 * @section sec_entity Configuration entities
339 * In contrast to the simple configuration settings described in the previous
340 * section, if your module allows users to create zero or more items (where
341 * "items" are things like content type definitions, view definitions, and the
342 * like), then you need to define a configuration entity type to store your
343 * configuration. Creating an entity type, loading entities, and querying them
344 * are outlined in the @link entity_api Entity API topic. @endlink Here are a
345 * few additional steps and notes specific to configuration entities:
346 * - For examples, look for classes that implement
347 * \Drupal\Core\Config\Entity\ConfigEntityInterface -- one good example is
348 * the \Drupal\user\Entity\Role entity type.
349 * - In the entity type annotation, you will need to define a 'config_prefix'
350 * string. When Drupal stores a configuration item, it will be given a name
351 * composed of your module name, your chosen config prefix, and the ID of
352 * the individual item, separated by '.'. For example, in the Role entity,
353 * the config prefix is 'role', so one configuration item might be named
354 * user.role.anonymous, with configuration file user.role.anonymous.yml.
355 * - You will need to define the schema for your configuration in your
356 * modulename.schema.yml file, with an entry for 'modulename.config_prefix.*'.
357 * For example, for the Role entity, the file user.schema.yml has an entry
358 * user.role.*; see @ref sec_yaml above for more information.
359 * - Your module can provide default/optional configuration entities in YAML
360 * files; see @ref sec_yaml above for more information.
361 * - Some configuration entities have dependencies on other configuration
362 * entities, and module developers need to consider this so that configuration
363 * can be imported, uninstalled, and synchronized in the right order. For
364 * example, a field display configuration entity would need to depend on
365 * field configuration, which depends on field and bundle configuration.
366 * Configuration entity classes expose dependencies by overriding the
367 * \Drupal\Core\Config\Entity\ConfigEntityInterface::calculateDependencies()
369 * - On routes for paths starting with '/admin' or otherwise designated as
370 * administration paths (such as node editing when it is set as an admin
371 * operation), if they have configuration entity placeholders, configuration
372 * entities are normally loaded in their original language, without
373 * translations or other overrides. This is usually desirable, because most
374 * admin paths are for editing configuration, and you need that to be in the
375 * source language and to lack possibly dynamic overrides. If for some reason
376 * you need to have your configuration entity loaded in the currently-selected
377 * language on an admin path (for instance, if you go to
378 * example.com/es/admin/your_path and you need the entity to be in Spanish),
379 * then you can add a 'with_config_overrides' parameter option to your route.
380 * The same applies if you need to load the entity with overrides (or
381 * translated) on an admin path like '/node/add/article' (when configured to
382 * be an admin path). Here's an example using the configurable_language config
386 * path: '/admin/mypath/{configurable_language}'
388 * _controller: '\Drupal\mymodule\MyController::myMethod'
391 * configurable_language:
392 * type: entity:configurable_language
393 * with_config_overrides: TRUE
395 * With the route defined this way, the $configurable_language parameter to
396 * your controller method will come in translated to the current language.
397 * Without the parameter options section, it would be in the original
398 * language, untranslated.
406 * @defgroup cache Cache API
408 * Information about the Drupal Cache API
410 * @section basics Basics
412 * Note: If not specified, all of the methods mentioned here belong to
413 * \Drupal\Core\Cache\CacheBackendInterface.
415 * The Cache API is used to store data that takes a long time to compute.
416 * Caching can either be permanent or valid only for a certain timespan, and
417 * the cache can contain any type of data.
419 * To use the Cache API:
420 * - Request a cache object through \Drupal::cache() or by injecting a cache
422 * - Define a Cache ID (cid) value for your data. A cid is a string, which must
423 * contain enough information to uniquely identify the data. For example, if
424 * your data contains translated strings, then your cid value must include the
425 * interface text language selected for page.
426 * - Call the get() method to attempt a cache read, to see if the cache already
427 * contains your data.
428 * - If your data is not already in the cache, compute it and add it to the
429 * cache using the set() method. The third argument of set() can be used to
430 * control the lifetime of your cache item.
434 * $cid = 'mymodule_example:' . \Drupal::languageManager()->getCurrentLanguage()->getId();
437 * if ($cache = \Drupal::cache()->get($cid)) {
438 * $data = $cache->data;
441 * $data = my_module_complicated_calculation();
442 * \Drupal::cache()->set($cid, $data);
446 * Note the use of $data and $cache->data in the above example. Calls to
447 * \Drupal::cache()->get() return a record that contains the information stored
448 * by \Drupal::cache()->set() in the data property as well as additional meta
449 * information about the cached data. In order to make use of the cached data
450 * you can access it via $cache->data.
452 * @section bins Cache bins
454 * Cache storage is separated into "bins", each containing various cache items.
455 * Each bin can be configured separately; see @ref configuration.
457 * When you request a cache object, you can specify the bin name in your call to
458 * \Drupal::cache(). Alternatively, you can request a bin by getting service
459 * "cache.nameofbin" from the container. The default bin is called "default", with
460 * service name "cache.default", it is used to store common and frequently used
463 * Other common cache bins are the following:
464 * - bootstrap: Data needed from the beginning to the end of most requests,
465 * that has a very strict limit on variations and is invalidated rarely.
466 * - render: Contains cached HTML strings like cached pages and blocks, can
467 * grow to large size.
468 * - data: Contains data that can vary by path or similar context.
469 * - discovery: Contains cached discovery data for things such as plugins,
470 * views_data, or YAML discovered data such as library info.
472 * A module can define a cache bin by defining a service in its
473 * modulename.services.yml file as follows (substituting the desired name for
477 * class: Drupal\Core\Cache\CacheBackendInterface
479 * - { name: cache.bin }
480 * factory: cache_factory:get
481 * arguments: [nameofbin]
483 * See the @link container Services topic @endlink for more on defining
486 * @section delete Deletion
488 * There are two ways to remove an item from the cache:
489 * - Deletion (using delete(), deleteMultiple() or deleteAll()) permanently
490 * removes the item from the cache.
491 * - Invalidation (using invalidate(), invalidateMultiple() or invalidateAll())
492 * is a "soft" delete that only marks items as "invalid", meaning "not fresh"
493 * or "not fresh enough". Invalid items are not usually returned from the
494 * cache, so in most ways they behave as if they have been deleted. However,
495 * it is possible to retrieve invalid items, if they have not yet been
496 * permanently removed by the garbage collector, by passing TRUE as the second
497 * argument for get($cid, $allow_invalid).
499 * Use deletion if a cache item is no longer useful; for instance, if the item
500 * contains references to data that has been deleted. Use invalidation if the
501 * cached item may still be useful to some callers until it has been updated
502 * with fresh data. The fact that it was fresh a short while ago may often be
505 * Invalidation is particularly useful to protect against stampedes. Rather than
506 * having multiple concurrent requests updating the same cache item when it
507 * expires or is deleted, there can be one request updating the cache, while the
508 * other requests can proceed using the stale value. As soon as the cache item
509 * has been updated, all future requests will use the updated value.
511 * @section tags Cache Tags
513 * The fourth argument of the set() method can be used to specify cache tags,
514 * which are used to identify which data is included in each cache item. A cache
515 * item can have multiple cache tags (an array of cache tags), and each cache
516 * tag is a string. The convention is to generate cache tags of the form
517 * [prefix]:[suffix]. Usually, you'll want to associate the cache tags of
518 * entities, or entity listings. You won't have to manually construct cache tags
519 * for them — just get their cache tags via
520 * \Drupal\Core\Cache\CacheableDependencyInterface::getCacheTags() and
521 * \Drupal\Core\Entity\EntityTypeInterface::getListCacheTags().
522 * Data that has been tagged can be invalidated as a group: no matter the Cache
523 * ID (cid) of the cache item, no matter in which cache bin a cache item lives;
524 * as long as it is tagged with a certain cache tag, it will be invalidated.
526 * Because of that, cache tags are a solution to the cache invalidation problem:
527 * - For caching to be effective, each cache item must only be invalidated when
528 * absolutely necessary. (i.e. maximizing the cache hit ratio.)
529 * - For caching to be correct, each cache item that depends on a certain thing
530 * must be invalidated whenever that certain thing is modified.
532 * A typical scenario: a user has modified a node that appears in two views,
533 * three blocks and on twelve pages. Without cache tags, we couldn't possibly
534 * know which cache items to invalidate, so we'd have to invalidate everything:
535 * we had to sacrifice effectiveness to achieve correctness. With cache tags, we
540 * // A cache item with nodes, users, and some custom module data.
547 * \Drupal::cache()->set($cid, $data, CacheBackendInterface::CACHE_PERMANENT, $tags);
549 * // Invalidate all cache items with certain tags.
550 * \Drupal\Core\Cache\Cache::invalidateTags(array('user:1'));
553 * Drupal is a content management system, so naturally you want changes to your
554 * content to be reflected everywhere, immediately. That's why we made sure that
555 * every entity type in Drupal 8 automatically has support for cache tags: when
556 * you save an entity, you can be sure that the cache items that have the
557 * corresponding cache tags will be invalidated.
558 * This also is the case when you define your own entity types: you'll get the
559 * exact same cache tag invalidation as any of the built-in entity types, with
560 * the ability to override any of the default behavior if needed.
561 * See \Drupal\Core\Cache\CacheableDepenencyInterface::getCacheTags(),
562 * \Drupal\Core\Entity\EntityTypeInterface::getListCacheTags(),
563 * \Drupal\Core\Entity\Entity::invalidateTagsOnSave() and
564 * \Drupal\Core\Entity\Entity::invalidateTagsOnDelete().
566 * @section context Cache contexts
568 * Some computed data depends on contextual data, such as the user roles of the
569 * logged-in user who is viewing a page, the language the page is being rendered
570 * in, the theme being used, etc. When caching the output of such a calculation,
571 * you must cache each variation separately, along with information about which
572 * variation of the contextual data was used in the calculatation. The next time
573 * the computed data is needed, if the context matches that for an existing
574 * cached data set, the cached data can be reused; if no context matches, a new
575 * data set can be calculated and cached for later use.
577 * Cache contexts are services tagged with 'cache.context', whose classes
578 * implement \Drupal\Core\Cache\Context\CacheContextInterface. See
579 * https://www.drupal.org/developing/api/8/cache/contexts for more information
580 * on cache contexts, including a list of the contexts that exist in Drupal
581 * core, and information on how to define your own contexts. See the
582 * @link container Services and the Dependency Injection Container @endlink
583 * topic for more information about services.
585 * Typically, the cache context is specified as part of the #cache property
586 * of a render array; see the Caching section of the
587 * @link theme_render Render API overview topic @endlink for details.
589 * @section configuration Configuration
591 * By default cached data is stored in the database. This can be configured
592 * though so that all cached data, or that of an individual cache bin, uses a
593 * different cache backend, such as APCu or Memcache, for storage.
595 * In a settings.php file, you can override the service used for a particular
596 * cache bin. For example, if your service implementation of
597 * \Drupal\Core\Cache\CacheBackendInterface was called cache.custom, the
598 * following line would make Drupal use it for the 'cache_render' bin:
600 * $settings['cache']['bins']['render'] = 'cache.custom';
603 * Additionally, you can register your cache implementation to be used by
604 * default for all cache bins with:
606 * $settings['cache']['default'] = 'cache.custom';
609 * Finally, you can chain multiple cache backends together, see
610 * \Drupal\Core\Cache\ChainedFastBackend and \Drupal\Core\Cache\BackendChain.
612 * @see https://www.drupal.org/node/1884796
617 * @defgroup user_api User accounts, permissions, and roles
619 * API for user accounts, access checking, roles, and permissions.
621 * @section sec_overview Overview and terminology
622 * Drupal's permission system is based on the concepts of accounts, roles,
625 * Users (site visitors) have accounts, which include a user name, an email
626 * address, a password (or some other means of authentication), and possibly
627 * other fields (if defined on the site). Anonymous users have an implicit
628 * account that does not have a real user name or any account information.
630 * Each user account is assigned one or more roles. The anonymous user account
631 * automatically has the anonymous user role; real user accounts
632 * automatically have the authenticated user role, plus any roles defined on
633 * the site that they have been assigned.
635 * Each role, including the special anonymous and authenticated user roles, is
636 * granted one or more named permissions, which allow them to perform certain
637 * tasks or view certain content on the site. It is possible to designate a
638 * role to be the "administrator" role; if this is set up, this role is
639 * automatically granted all available permissions whenever a module is
640 * enabled that defines permissions.
642 * All code in Drupal that allows users to perform tasks or view content must
643 * check that the current user has the correct permission before allowing the
644 * action. In the standard case, access checking consists of answering the
645 * question "Does the current user have permission 'foo'?", and allowing or
646 * denying access based on the answer. Note that access checking should nearly
647 * always be done at the permission level, not by checking for a particular role
648 * or user ID, so that site administrators can set up user accounts and roles
649 * appropriately for their particular sites.
651 * @section sec_define Defining permissions
652 * Modules define permissions via a $module.permissions.yml file. See
653 * \Drupal\user\PermissionHandler for documentation of permissions.yml files.
655 * @section sec_access Access permission checking
656 * Depending on the situation, there are several methods for ensuring that
657 * access checks are done properly in Drupal:
658 * - Routes: When you register a route, include a 'requirements' section that
659 * either gives the machine name of the permission that is needed to visit the
660 * URL of the route, or tells Drupal to use an access check method or service
661 * to check access. See the @link menu Routing topic @endlink for more
663 * - Entities: Access for various entity operations is designated either with
664 * simple permissions or access control handler classes in the entity
665 * annotation. See the @link entity_api Entity API topic @endlink for more
667 * - Other code: There is a 'current_user' service, which can be injected into
668 * classes to provide access to the current user account (see the
669 * @link container Services and Dependency Injection topic @endlink for more
670 * information on dependency injection). In code that cannot use dependency
671 * injection, you can access this service and retrieve the current user
672 * account object by calling \Drupal::currentUser(). Once you have a user
673 * object for the current user (implementing \Drupal\user\UserInterface), you
674 * can call inherited method
675 * \Drupal\Core\Session\AccountInterface::hasPermission() to check
676 * permissions, or pass this object into other functions/methods.
677 * - Forms: Each element of a form array can have a Boolean '#access' property,
678 * which determines whether that element is visible and/or usable. This is a
679 * common need in forms, so the current user service (described above) is
680 * injected into the form base class as method
681 * \Drupal\Core\Form\FormBase::currentUser().
683 * @section sec_entities User and role objects
684 * User objects in Drupal are entity items, implementing
685 * \Drupal\user\UserInterface. Role objects in Drupal are also entity items,
686 * implementing \Drupal\user\RoleInterface. See the
687 * @link entity_api Entity API topic @endlink for more information about
688 * entities in general (including how to load, create, modify, and query them).
690 * Roles often need to be manipulated in automated test code, such as to add
691 * permissions to them. Here's an example:
693 * $role = \Drupal\user\Entity\Role::load('authenticated');
694 * $role->grantPermission('access comments');
698 * Other important interfaces:
699 * - \Drupal\Core\Session\AccountInterface: The part of UserInterface that
700 * deals with access checking. In writing code that checks access, your
701 * method parameters should use this interface, not UserInterface.
702 * - \Drupal\Core\Session\AccountProxyInterface: The interface for the
703 * current_user service (described above).
708 * @defgroup container Services and Dependency Injection Container
710 * Overview of the Dependency Injection Container and Services.
712 * @section sec_overview Overview of container, injection, and services
713 * The Services and Dependency Injection Container concepts have been adopted by
714 * Drupal from the @link http://symfony.com/ Symfony framework. @endlink A
715 * "service" (such as accessing the database, sending email, or translating user
716 * interface text) is defined (given a name and an interface or at least a
717 * class that defines the methods that may be called), and a default class is
718 * designated to provide the service. These two steps must be done together, and
719 * can be done by Drupal Core or a module. Other modules can then define
720 * alternative classes to provide the same services, overriding the default
721 * classes. Classes and functions that need to use the service should always
722 * instantiate the class via the dependency injection container (also known
723 * simply as the "container"), rather than instantiating a particular service
724 * provider class directly, so that they get the correct class (default or
727 * See https://www.drupal.org/node/2133171 for more detailed information on
728 * services and the dependency injection container.
730 * @section sec_discover Discovering existing services
731 * Drupal core defines many core services in the core.services.yml file (in the
732 * top-level core directory). Some Drupal Core modules and contributed modules
733 * also define services in modulename.services.yml files. API reference sites
734 * (such as https://api.drupal.org) generate lists of all existing services from
735 * these files. Look for the Services link in the API Navigation block.
736 * Alternatively you can look through the individual files manually.
738 * A typical service definition in a *.services.yml file looks like this:
740 * path.alias_manager:
741 * class: Drupal\Core\Path\AliasManager
742 * arguments: ['@path.crud', '@path.alias_whitelist', '@language_manager']
744 * Some services use other services as factories; a typical service definition
748 * class: Drupal\Core\Cache\CacheBackendInterface
750 * - { name: cache.bin }
751 * factory: cache_factory:get
752 * arguments: [entity]
755 * The first line of a service definition gives the unique machine name of the
756 * service. This is often prefixed by the module name if provided by a module;
757 * however, by convention some service names are prefixed by a group name
758 * instead, such as cache.* for cache bins and plugin.manager.* for plugin
761 * The class line either gives the default class that provides the service, or
762 * if the service uses a factory class, the interface for the service. If the
763 * class depends on other services, the arguments line lists the machine
764 * names of the dependencies (preceded by '@'); objects for each of these
765 * services are instantiated from the container and passed to the class
766 * constructor when the service class is instantiated. Other arguments can also
767 * be passed in; see the section at https://www.drupal.org/node/2133171 for more
768 * detailed information.
770 * Services using factories can be defined as shown in the above example, if the
771 * factory is itself a service. The factory can also be a class; details of how
772 * to use service factories can be found in the section at
773 * https://www.drupal.org/node/2133171.
775 * @section sec_container Accessing a service through the container
776 * As noted above, if you need to use a service in your code, you should always
777 * instantiate the service class via a call to the container, using the machine
778 * name of the service, so that the default class can be overridden. There are
779 * several ways to make sure this happens:
780 * - For service-providing classes, see other sections of this documentation
781 * describing how to pass services as arguments to the constructor.
782 * - Plugin classes, controllers, and similar classes have create() or
783 * createInstance() methods that are used to create an instance of the class.
784 * These methods come from different interfaces, and have different
785 * arguments, but they all include an argument $container of type
786 * \Symfony\Component\DependencyInjection\ContainerInterface.
787 * If you are defining one of these classes, in the create() or
788 * createInstance() method, call $container->get('myservice.name') to
789 * instantiate a service. The results of these calls are generally passed to
790 * the class constructor and saved as member variables in the class.
791 * - For functions and class methods that do not have access to either of
792 * the above methods of dependency injection, you can use service location to
793 * access services, via a call to the global \Drupal class. This class has
794 * special methods for accessing commonly-used services, or you can call a
795 * generic method to access any service. Examples:
797 * // Retrieve the entity.manager service object (special method exists).
798 * $manager = \Drupal::entityManager();
799 * // Retrieve the service object for machine name 'foo.bar'.
800 * $foobar = \Drupal::service('foo.bar');
803 * As a note, you should always use dependency injection (via service arguments
804 * or create()/createInstance() methods) if possible to instantiate services,
805 * rather than service location (via the \Drupal class), because:
806 * - Dependency injection facilitates writing unit tests, since the container
807 * argument can be mocked and the create() method can be bypassed by using
808 * the class constructor. If you use the \Drupal class, unit tests are much
809 * harder to write and your code has more dependencies.
810 * - Having the service interfaces on the class constructor and member variables
811 * is useful for IDE auto-complete and self-documentation.
813 * @section sec_define Defining a service
814 * If your module needs to define a new service, here are the steps:
815 * - Choose a unique machine name for your service. Typically, this should
816 * start with your module name. Example: mymodule.myservice.
817 * - Create a PHP interface to define what your service does.
818 * - Create a default class implementing your interface that provides your
819 * service. If your class needs to use existing services (such as database
820 * access), be sure to make these services arguments to your class
821 * constructor, and save them in member variables. Also, if the needed
822 * services are provided by other modules and not Drupal Core, you'll want
823 * these modules to be dependencies of your module.
824 * - Add an entry to a modulename.services.yml file for the service. See
825 * @ref sec_discover above, or existing *.services.yml files in Core, for the
826 * syntax; it will start with your machine name, refer to your default class,
827 * and list the services that need to be passed into your constructor.
829 * Services can also be defined dynamically, as in the
830 * \Drupal\Core\CoreServiceProvider class, but this is less common for modules.
832 * @section sec_tags Service tags
833 * Some services have tags, which are defined in the service definition. See
834 * @link service_tag Service Tags @endlink for usage.
836 * @section sec_injection Overriding the default service class
837 * Modules can override the default classes used for services. Here are the
839 * - Define a class in the top-level namespace for your module
840 * (Drupal\my_module), whose name is the camel-case version of your module's
841 * machine name followed by "ServiceProvider" (for example, if your module
842 * machine name is my_module, the class must be named
843 * MyModuleServiceProvider).
844 * - The class needs to implement
845 * \Drupal\Core\DependencyInjection\ServiceModifierInterface, which is
846 * typically done by extending
847 * \Drupal\Core\DependencyInjection\ServiceProviderBase.
848 * - The class needs to contain one method: alter(). This method does the
849 * actual work of telling Drupal to use your class instead of the default.
852 * public function alter(ContainerBuilder $container) {
853 * // Override the language_manager class with a new class.
854 * $definition = $container->getDefinition('language_manager');
855 * $definition->setClass('Drupal\my_module\MyLanguageManager');
858 * Note that $container here is an instance of
859 * \Drupal\Core\DependencyInjection\ContainerBuilder.
861 * @see https://www.drupal.org/node/2133171
862 * @see core.services.yml
864 * @see \Symfony\Component\DependencyInjection\ContainerInterface
871 * @defgroup listing_page_service Page header for Services page
873 * Introduction to services
875 * A "service" (such as accessing the database, sending email, or translating
876 * user interface text) can be defined by a module or Drupal core. Defining a
877 * service means giving it a name and designating a default class to provide the
878 * service; ideally, there should also be an interface that defines the methods
879 * that may be called. Services are collected into the Dependency Injection
880 * Container, and can be overridden to use different classes or different
881 * instantiation by modules. See the
882 * @link container Services and Dependency Injection Container topic @endlink
885 * Some services have tags, which are defined in the service definition. Tags
886 * are used to define a group of related services, or to specify some aspect of
887 * how the service behaves. See the
888 * @link service_tag Service Tags topic @endlink for more information.
897 * @defgroup typed_data Typed Data API
899 * API for describing data based on a set of available data types.
901 * PHP has data types, such as int, string, float, array, etc., and it is an
902 * object-oriented language that lets you define classes and interfaces.
903 * However, in some cases, it is useful to be able to define an abstract
904 * type (as in an interface, free of implementation details), that still has
905 * properties (which an interface cannot) as well as meta-data. The Typed Data
906 * API provides this abstraction.
908 * @section sec_overview Overview
909 * Each data type in the Typed Data API is a plugin class (annotation class
910 * example: \Drupal\Core\TypedData\Annotation\DataType); these plugins are
911 * managed by the typed_data_manager service (by default
912 * \Drupal\Core\TypedData\TypedDataManager). Each data object encapsulates a
913 * single piece of data, provides access to the metadata, and provides
914 * validation capability. Also, the typed data plugins have a shorthand
915 * for easily accessing data values, described in @ref sec_tree.
917 * The metadata of a data object is defined by an object based on a class called
918 * the definition class (see \Drupal\Core\TypedData\DataDefinitionInterface).
919 * The class used can vary by data type and can be specified in the data type's
920 * plugin definition, while the default is set in the $definition_class property
921 * of the annotation class. The default class is
922 * \Drupal\Core\TypedData\DataDefinition. For data types provided by a plugin
923 * deriver, the plugin deriver can set the definition_class property too.
924 * The metadata object provides information about the data, such as the data
925 * type, whether it is translatable, the names of its properties (for complex
926 * types), and who can access it.
928 * See https://www.drupal.org/node/1794140 for more information about the Typed
931 * @section sec_varieties Varieties of typed data
932 * There are three kinds of typed data: primitive, complex, and list.
934 * @subsection sub_primitive Primitive data types
935 * Primitive data types wrap PHP data types and also serve as building blocks
936 * for complex and list typed data. Each primitive data type has an interface
937 * that extends \Drupal\Core\TypedData\PrimitiveInterface, with getValue()
938 * and setValue() methods for accessing the data value, and a default plugin
939 * implementation. Here's a list:
940 * - \Drupal\Core\TypedData\Type\IntegerInterface: Plugin ID integer,
941 * corresponds to PHP type int.
942 * - \Drupal\Core\TypedData\Type\StringInterface: Plugin ID string,
943 * corresponds to PHP type string.
944 * - \Drupal\Core\TypedData\Type\FloatInterface: Plugin ID float,
945 * corresponds to PHP type float.
946 * - \Drupal\Core\TypedData\Type\BooleanInterface: Plugin ID bool,
947 * corresponds to PHP type bool.
948 * - \Drupal\Core\TypedData\Type\BinaryInterface: Plugin ID binary,
949 * corresponds to a PHP file resource.
950 * - \Drupal\Core\TypedData\Type\UriInterface: Plugin ID uri.
952 * @subsection sec_complex Complex data
953 * Complex data types, with interface
954 * \Drupal\Core\TypedData\ComplexDataInterface, represent data with named
955 * properties; the properties can be accessed with get() and set() methods.
956 * The value of each property is itself a typed data object, which can be
957 * primitive, complex, or list data.
959 * The base type for most complex data is the
960 * \Drupal\Core\TypedData\Plugin\DataType\Map class, which represents an
961 * associative array. Map provides its own definition class in the annotation,
962 * \Drupal\Core\TypedData\MapDataDefinition, and most complex data classes
963 * extend this class. The getValue() and setValue() methods on the Map class
964 * enforce the data definition and its property structure.
966 * The Drupal Field API uses complex typed data for its field items, with
967 * definition class \Drupal\Core\Field\TypedData\FieldItemDataDefinition.
969 * @section sec_list Lists
970 * List data types, with interface \Drupal\Core\TypedData\ListInterface,
971 * represent data that is an ordered list of typed data, all of the same type.
972 * More precisely, the plugins in the list must have the same base plugin ID;
973 * however, some types (for example field items and entities) are provided by
974 * plugin derivatives and the sub IDs can be different.
976 * @section sec_tree Tree handling
977 * Typed data allows you to use shorthand to get data values nested in the
978 * implicit tree structure of the data. For example, to get the value from
979 * an entity field item, the Entity Field API allows you to call:
981 * $value = $entity->fieldName->propertyName;
983 * This is really shorthand for:
985 * $field_item_list = $entity->get('fieldName');
986 * $field_item = $field_item_list->get(0);
987 * $property = $field_item->get('propertyName');
988 * $value = $property->getValue();
991 * - $property, $field_item, and $field_item_list are all typed data objects,
992 * while $value is a raw PHP value.
993 * - You can call $property->getParent() to get $field_item,
994 * $field_item->getParent() to get $field_item_list, or
995 * $field_item_list->getParent() to get $typed_entity ($entity wrapped in a
996 * typed data object). $typed_entity->getParent() is NULL.
997 * - For all of these ->getRoot() returns $typed_entity.
998 * - The langcode property is on $field_item_list, but you can access it
999 * on $property as well, so that all items will report the same langcode.
1000 * - When the value of $property is changed by calling $property->setValue(),
1001 * $property->onChange() will fire, which in turn calls the parent object's
1002 * onChange() method and so on. This allows parent objects to react upon
1003 * changes of contained properties or list items.
1005 * @section sec_defining Defining data types
1006 * To define a new data type:
1007 * - Create a class that implements one of the Typed Data interfaces.
1008 * Typically, you will want to extend one of the classes listed in the
1009 * sections above as a starting point.
1010 * - Make your class into a DataType plugin. To do that, put it in namespace
1011 * \Drupal\yourmodule\Plugin\DataType (where "yourmodule" is your module's
1012 * short name), and add annotation of type
1013 * \Drupal\Core\TypedData\Annotation\DataType to the documentation header.
1014 * See the @link plugin_api Plugin API topic @endlink and the
1015 * @link annotation Annotations topic @endlink for more information.
1017 * @section sec_using Using data types
1018 * The data types of the Typed Data API can be used in several ways, once they
1019 * have been defined:
1020 * - In the Field API, data types can be used as the class in the property
1021 * definition of the field. See the @link field Field API topic @endlink for
1023 * - In configuration schema files, you can use the unique ID ('id' annotation)
1024 * from any DataType plugin class as the 'type' value for an entry. See the
1025 * @link config_api Confuration API topic @endlink for more information.
1026 * - If you need to create a typed data object in code, first get the
1027 * typed_data_manager service from the container or by calling
1028 * \Drupal::typedDataManager(). Then pass the plugin ID to
1029 * $manager::createDataDefinition() to create an appropriate data definition
1030 * object. Then pass the data definition object and the value of the data to
1031 * $manager::create() to create a typed data object.
1039 * @defgroup testing Automated tests
1041 * Overview of PHPUnit tests and Simpletest tests.
1043 * The Drupal project has embraced a philosophy of using automated tests,
1044 * consisting of both unit tests (which test the functionality of classes at a
1045 * low level) and functional tests (which test the functionality of Drupal
1046 * systems at a higher level, usually involving web output). The goal is to
1047 * have test coverage for all or most of the components and features, and to
1048 * run the automated tests before any code is changed or added, to make sure
1049 * it doesn't break any existing functionality (regression testing).
1051 * In order to implement this philosophy, developers need to do the following:
1052 * - When making a patch to fix a bug, make sure that the bug fix patch includes
1053 * a test that fails without the code change and passes with the code change.
1054 * This helps reviewers understand what the bug is, demonstrates that the code
1055 * actually fixes the bug, and ensures the bug will not reappear due to later
1057 * - When making a patch to implement a new feature, include new unit and/or
1058 * functional tests in the patch. This serves to both demonstrate that the
1059 * code actually works, and ensure that later changes do not break the new
1062 * @section write_unit Writing PHPUnit tests for classes
1063 * PHPUnit tests for classes are written using the industry-standard PHPUnit
1064 * framework. Use a PHPUnit test to test functionality of a class if the Drupal
1065 * environment (database, settings, etc.) and web browser are not needed for the
1066 * test, or if the Drupal environment can be replaced by a "mock" object. To
1067 * write a PHPUnit test:
1068 * - Define a class that extends \Drupal\Tests\UnitTestCase.
1069 * - The class name needs to end in the word Test.
1070 * - The namespace must be a subspace/subdirectory of \Drupal\yourmodule\Tests,
1071 * where yourmodule is your module's machine name.
1072 * - The test class file must be named and placed under the
1073 * yourmodule/tests/src/Unit directory, according to the PSR-4 standard.
1074 * - Your test class needs a phpDoc comment block with a description and
1075 * a @group annotation, which gives information about the test.
1076 * - Add test cases by adding method names that start with 'test' and have no
1077 * arguments, for example testYourTestCase(). Each one should test a logical
1078 * subset of the functionality.
1079 * For more details, see:
1080 * - https://www.drupal.org/phpunit for full documentation on how to write
1081 * PHPUnit tests for Drupal.
1082 * - http://phpunit.de for general information on the PHPUnit framework.
1083 * - @link oo_conventions Object-oriented programming topic @endlink for more
1084 * on PSR-4, namespaces, and where to place classes.
1086 * @section write_functional Writing functional tests
1087 * Functional tests are written using a Drupal-specific framework that is, for
1088 * historical reasons, known as "Simpletest". Use a Simpletest test to test the
1089 * functionality of sub-system of Drupal, if the functionality depends on the
1090 * Drupal database and settings, or to test the web output of Drupal. To
1091 * write a Simpletest test:
1092 * - For functional tests of the web output of Drupal, define a class that
1093 * extends \Drupal\simpletest\WebTestBase, which contains an internal web
1094 * browser and defines many helpful test assertion methods that you can use
1095 * in your tests. You can specify modules to be enabled by defining a
1096 * $modules member variable -- keep in mind that by default, WebTestBase uses
1097 * a "testing" install profile, with a minimal set of modules enabled.
1098 * - For functional tests that do not test web output, define a class that
1099 * extends \Drupal\KernelTests\KernelTestBase. This class is much faster
1100 * than WebTestBase, because instead of making a full install of Drupal, it
1101 * uses an in-memory pseudo-installation (similar to what the installer and
1102 * update scripts use). To use this test class, you will need to create the
1103 * database tables you need and install needed modules manually.
1104 * - The namespace must be a subspace/subdirectory of \Drupal\yourmodule\Tests,
1105 * where yourmodule is your module's machine name.
1106 * - The test class file must be named and placed under the yourmodule/src/Tests
1107 * directory, according to the PSR-4 standard.
1108 * - Your test class needs a phpDoc comment block with a description and
1109 * a @group annotation, which gives information about the test.
1110 * - You may also override the default setUp() method, which can set be used to
1111 * set up content types and similar procedures.
1112 * - In some cases, you may need to write a test module to support your test;
1113 * put such modules under the yourmodule/tests/modules directory.
1114 * - Add test cases by adding method names that start with 'test' and have no
1115 * arguments, for example testYourTestCase(). Each one should test a logical
1116 * subset of the functionality. Each method runs in a new, isolated test
1117 * environment, so it can only rely on the setUp() method, not what has
1118 * been set up by other test methods.
1119 * For more details, see:
1120 * - https://www.drupal.org/simpletest for full documentation on how to write
1121 * functional tests for Drupal.
1122 * - @link oo_conventions Object-oriented programming topic @endlink for more
1123 * on PSR-4, namespaces, and where to place classes.
1125 * @section write_functional_phpunit Write functional PHP tests (phpunit)
1126 * Functional tests extend the BrowserTestBase base class, and use PHPUnit as
1127 * their underlying framework. They use a simulated browser, in which the test
1128 * can click links, visit URLs, post to forms, etc. To write a functional test:
1129 * - Extend \Drupal\Tests\BrowserTestBase.
1130 * - Place the test in the yourmodule/tests/src/Functional/ directory and use
1131 * the \Drupal\Tests\yourmodule\Functional namespace.
1132 * - Add a @group annotation. For example, if the test is for a Drupal 6
1133 * migration process, the group core uses is migrate_drupal_6. Use yourmodule
1134 * as the group name if the test does not belong to another larger group.
1135 * - You may also override the default setUp() method, which can be used to set
1136 * up content types and similar procedures. Don't forget to call the parent
1138 * - In some cases, you may need to write a test module to support your test;
1139 * put such modules under the yourmodule/tests/modules directory.
1140 * - Add test cases by adding method names that start with 'test' and have no
1141 * arguments, for example testYourTestCase(). Each one should test a logical
1142 * subset of the functionality. Each method runs in a new, isolated test
1143 * environment, so it can only rely on the setUp() method, not what has
1144 * been set up by other test methods.
1145 * For more details, see:
1146 * - https://www.drupal.org/docs/8/phpunit/phpunit-browser-test-tutorial for
1147 * a full tutorial on how to write functional PHPUnit tests for Drupal.
1148 * - https://www.drupal.org/phpunit for the full documentation on how to write
1149 * PHPUnit tests for Drupal.
1151 * @section write_jsfunctional_phpunit Write functional JavaScript tests (phpunit)
1152 * To write a functional test that relies on JavaScript:
1153 * - Extend \Drupal\FunctionalJavaScriptTests\JavascriptTestBase.
1154 * - Place the test into the yourmodule/tests/src/FunctionalJavascript/
1155 * directory and use the \Drupal\Tests\yourmodule\FunctionalJavascript
1157 * - Add a @group annotation. Use yourmodule as the group name if the test does
1158 * not belong to another larger group.
1159 * - Set up PhantomJS; see http://phantomjs.org/download.html.
1160 * - To run tests, see core/tests/README.md.
1161 * - When clicking a link/button with Ajax behavior attached, keep in mind that
1162 * the underlying browser might take time to deliver changes to the HTML. Use
1163 * $this->assertSession()->assertWaitOnAjaxRequest() to wait for the Ajax
1164 * request to finish.
1165 * For more details, see:
1166 * - https://www.drupal.org/docs/8/phpunit/phpunit-javascript-testing-tutorial
1167 * for a full tutorial on how to write PHPUnit JavaScript tests for Drupal.
1168 * - https://www.drupal.org/phpunit for the full documentation on how to write
1169 * PHPUnit tests for Drupal.
1171 * @section running Running tests
1172 * You can run both Simpletest and PHPUnit tests by enabling the core Testing
1173 * module (core/modules/simpletest). Once that module is enabled, tests can be
1174 * run using the core/scripts/run-tests.sh script, using
1175 * @link https://www.drupal.org/project/drush Drush @endlink, or from the
1176 * Testing module user interface.
1178 * PHPUnit tests can also be run from the command line, using the PHPUnit
1179 * framework. See https://www.drupal.org/node/2116263 for more information.
1184 * @defgroup php_assert PHP Runtime Assert Statements
1186 * Use of the assert() statement in Drupal.
1188 * Unit tests also use the term "assertion" to refer to test conditions, so to
1189 * avoid confusion the term "runtime assertion" will be used for the assert()
1190 * statement throughout the documentation.
1192 * A runtime assertion is a statement that is expected to always be true at
1193 * the point in the code it appears at. They are tested using PHP's internal
1194 * @link http://php.net/assert assert() @endlink statement. If an
1195 * assertion is ever FALSE it indicates an error in the code or in module or
1196 * theme configuration files. User-provided configuration files should be
1197 * verified with standard control structures at all times, not just checked in
1198 * development environments with assert() statements on.
1200 * When runtime assertions fail in PHP 7 an \AssertionError is thrown.
1201 * Drupal uses an assertion callback to do the same in PHP 5.x so that unit
1202 * tests involving runtime assertions will work uniformly across both versions.
1204 * The Drupal project primarily uses runtime assertions to enforce the
1205 * expectations of the API by failing when incorrect calls are made by code
1206 * under development. While PHP type hinting does this for objects and arrays,
1207 * runtime assertions do this for scalars (strings, integers, floats, etc.) and
1208 * complex data structures such as cache and render arrays. They ensure that
1209 * methods' return values are the documented datatypes. They also verify that
1210 * objects have been properly configured and set up by the service container.
1211 * Runtime assertions are checked throughout development. They supplement unit
1212 * tests by checking scenarios that do not have unit tests written for them,
1213 * and by testing the API calls made by all the code in the system.
1215 * When using assert() keep the following in mind:
1216 * - Runtime assertions are disabled by default in production and enabled in
1217 * development, so they can't be used as control structures. Use exceptions
1218 * for errors that can occur in production no matter how unlikely they are.
1219 * - Assert() functions in a buggy manner prior to PHP 7. If you do not use a
1220 * string for the first argument of the statement but instead use a function
1221 * call or expression then that code will be evaluated even when runtime
1222 * assertions are turned off. To avoid this you must use a string as the
1223 * first argument, and assert will pass this string to the eval() statement.
1224 * - Since runtime assertion strings are parsed by eval() use caution when
1225 * using them to work with data that may be unsanitized.
1227 * See https://www.drupal.org/node/2492225 for more information on runtime
1233 * @defgroup info_types Information types
1235 * Types of information in Drupal.
1237 * Drupal has several distinct types of information, each with its own methods
1238 * for storage and retrieval:
1239 * - Content: Information meant to be displayed on your site: articles, basic
1240 * pages, images, files, custom blocks, etc. Content is stored and accessed
1241 * using @link entity_api Entities @endlink.
1242 * - Session: Information about individual users' interactions with the site,
1243 * such as whether they are logged in. This is really "state" information, but
1244 * it is not stored the same way so it's a separate type here. Session
1245 * information is available from the Request object. The session implements
1246 * \Symfony\Component\HttpFoundation\Session\SessionInterface.
1247 * - State: Information of a temporary nature, generally machine-generated and
1248 * not human-edited, about the current state of your site. Examples: the time
1249 * when Cron was last run, whether node access permissions need rebuilding,
1250 * etc. See @link state_api the State API topic @endlink for more information.
1251 * - Configuration: Information about your site that is generally (or at least
1252 * can be) human-edited, but is not Content, and is meant to be relatively
1253 * permanent. Examples: the name of your site, the content types and views
1254 * you have defined, etc. See
1255 * @link config_api the Configuration API topic @endlink for more information.
1263 * @defgroup extending Extending and altering Drupal
1265 * Overview of extensions and alteration methods for Drupal.
1267 * @section sec_types Types of extensions
1268 * Drupal's core behavior can be extended and altered via these three basic
1269 * types of extensions:
1270 * - Themes: Themes alter the appearance of Drupal sites. They can include
1271 * template files, which alter the HTML markup and other raw output of the
1272 * site; CSS files, which alter the styling applied to the HTML; and
1273 * JavaScript, Flash, images, and other files. For more information, see the
1274 * @link theme_render Theme system and render API topic @endlink and
1275 * https://www.drupal.org/docs/8/theming
1276 * - Modules: Modules add to or alter the behavior and functionality of Drupal,
1277 * by using one or more of the methods listed below. For more information
1278 * about creating modules, see https://www.drupal.org/developing/modules/8
1279 * - Installation profiles: Installation profiles can be used to
1280 * create distributions, which are complete specific-purpose packages of
1281 * Drupal including additional modules, themes, and data. For more
1282 * information, see https://www.drupal.org/developing/distributions.
1284 * @section sec_alter Alteration methods for modules
1285 * Here is a list of the ways that modules can alter or extend Drupal's core
1286 * behavior, or the behavior of other modules:
1287 * - Hooks: Specially-named functions that a module defines, which are
1288 * discovered and called at specific times, usually to alter behavior or data.
1289 * See the @link hooks Hooks topic @endlink for more information.
1290 * - Plugins: Classes that a module defines, which are discovered and
1291 * instantiated at specific times to add functionality. See the
1292 * @link plugin_api Plugin API topic @endlink for more information.
1293 * - Entities: Special plugins that define entity types for storing new types
1294 * of content or configuration in Drupal. See the
1295 * @link entity_api Entity API topic @endlink for more information.
1296 * - Services: Classes that perform basic operations within Drupal, such as
1297 * accessing the database and sending email. See the
1298 * @link container Dependency Injection Container and Services topic @endlink
1299 * for more information.
1300 * - Routing: Providing or altering "routes", which are URLs that Drupal
1301 * responds to, or altering routing behavior with event listener classes.
1302 * See the @link menu Routing and menu topic @endlink for more information.
1303 * - Events: Modules can register as event subscribers; when an event is
1304 * dispatched, a method is called on each registered subscriber, allowing each
1305 * one to react. See the @link events Events topic @endlink for more
1308 * @section sec_sample *.info.yml files
1309 * Extensions must each be located in a directory whose name matches the short
1310 * name (or machine name) of the extension, and this directory must contain a
1311 * file named machine_name.info.yml (where machine_name is the machine name of
1312 * the extension). See \Drupal\Core\Extension\InfoParserInterface::parse() for
1313 * documentation of the format of .info.yml files.
1318 * @defgroup plugin_api Plugin API
1320 * Using the Plugin API
1322 * @section sec_overview Overview and terminology
1324 * The basic idea of plugins is to allow a particular module or subsystem of
1325 * Drupal to provide functionality in an extensible, object-oriented way. The
1326 * controlling module or subsystem defines the basic framework (interface) for
1327 * the functionality, and other modules can create plugins (implementing the
1328 * interface) with particular behaviors. The controlling module instantiates
1329 * existing plugins as needed, and calls methods to invoke their functionality.
1330 * Examples of functionality in Drupal Core that use plugins include: the block
1331 * system (block types are plugins), the entity/field system (entity types,
1332 * field types, field formatters, and field widgets are plugins), the image
1333 * manipulation system (image effects and image toolkits are plugins), and the
1334 * search system (search page types are plugins).
1336 * Plugins are grouped into plugin types, each generally defined by an
1337 * interface. Each plugin type is managed by a plugin manager service, which
1338 * uses a plugin discovery method to discover provided plugins of that type and
1339 * instantiate them using a plugin factory.
1341 * Some plugin types make use of the following concepts or components:
1342 * - Plugin derivatives: Allows a single plugin class to present itself as
1343 * multiple plugins. Example: the Menu module provides a block for each
1344 * defined menu via a block plugin derivative.
1345 * - Plugin mapping: Allows a plugin class to map a configuration string to an
1346 * instance, and have the plugin automatically instantiated without writing
1348 * - Plugin collections: Provide a way to lazily instantiate a set of plugin
1349 * instances from a single plugin definition.
1351 * There are several things a module developer may need to do with plugins:
1352 * - Define a completely new plugin type: see @ref sec_define below.
1353 * - Create a plugin of an existing plugin type: see @ref sec_create below.
1354 * - Perform tasks that involve plugins: see @ref sec_use below.
1356 * See https://www.drupal.org/developing/api/8/plugins for more detailed
1357 * documentation on the plugin system. There are also topics for a few
1358 * of the many existing types of plugins:
1359 * - @link block_api Block API @endlink
1360 * - @link entity_api Entity API @endlink
1361 * - @link field Various types of field-related plugins @endlink
1362 * - @link views_plugins Views plugins @endlink (has links to topics covering
1363 * various specific types of Views plugins).
1364 * - @link search Search page plugins @endlink
1366 * @section sec_define Defining a new plugin type
1367 * To define a new plugin type:
1368 * - Define an interface for the plugin. This describes the common set of
1369 * behavior, and the methods you will call on each plugin class that is
1370 * instantiated. Usually this interface will extend one or more of the
1371 * following interfaces:
1372 * - \Drupal\Component\Plugin\PluginInspectionInterface
1373 * - \Drupal\Component\Plugin\ConfigurablePluginInterface
1374 * - \Drupal\Component\Plugin\ContextAwarePluginInterface
1375 * - \Drupal\Core\Plugin\PluginFormInterface
1376 * - \Drupal\Core\Executable\ExecutableInterface
1377 * - (optional) Create a base class that provides a partial implementation of
1378 * the interface, for the convenience of developers wishing to create plugins
1379 * of your type. The base class usually extends
1380 * \Drupal\Core\Plugin\PluginBase, or one of the base classes that extends
1382 * - Choose a method for plugin discovery, and define classes as necessary.
1383 * See @ref sub_discovery below.
1384 * - Create a plugin manager/factory class and service, which will discover and
1385 * instantiate plugins. See @ref sub_manager below.
1386 * - Use the plugin manager to instantiate plugins. Call methods on your plugin
1387 * interface to perform the tasks of your plugin type.
1388 * - (optional) If appropriate, define a plugin collection. See @ref
1389 * sub_collection below for more information.
1391 * @subsection sub_discovery Plugin discovery
1392 * Plugin discovery is the process your plugin manager uses to discover the
1393 * individual plugins of your type that have been defined by your module and
1394 * other modules. Plugin discovery methods are classes that implement
1395 * \Drupal\Component\Plugin\Discovery\DiscoveryInterface. Most plugin types use
1396 * one of the following discovery mechanisms:
1397 * - Annotation: Plugin classes are annotated and placed in a defined namespace
1398 * subdirectory. Most Drupal Core plugins use this method of discovery.
1399 * - Hook: Plugin modules need to implement a hook to tell the manager about
1401 * - YAML: Plugins are listed in YAML files. Drupal Core uses this method for
1402 * discovering local tasks and local actions. This is mainly useful if all
1403 * plugins use the same class, so it is kind of like a global derivative.
1404 * - Static: Plugin classes are registered within the plugin manager class
1405 * itself. Static discovery is only useful if modules cannot define new
1406 * plugins of this type (if the list of available plugins is static).
1408 * It is also possible to define your own custom discovery mechanism or mix
1409 * methods together. And there are many more details, such as annotation
1410 * decorators, that apply to some of the discovery methods. See
1411 * https://www.drupal.org/developing/api/8/plugins for more details.
1413 * The remainder of this documentation will assume Annotation-based discovery,
1414 * since this is the most common method.
1416 * @subsection sub_manager Defining a plugin manager class and service
1417 * To define an annotation-based plugin manager:
1418 * - Choose a namespace subdirectory for your plugin. For example, search page
1419 * plugins go in directory Plugin/Search under the module namespace.
1420 * - Define an annotation class for your plugin type. This class should extend
1421 * \Drupal\Component\Annotation\Plugin, and for most plugin types, it should
1422 * contain member variables corresponding to the annotations plugins will
1423 * need to provide. All plugins have at least $id: a unique string
1425 * - Define an alter hook for altering the discovered plugin definitions. You
1426 * should document the hook in a *.api.php file.
1427 * - Define a plugin manager class. This class should implement
1428 * \Drupal\Component\Plugin\PluginManagerInterface; most plugin managers do
1429 * this by extending \Drupal\Core\Plugin\DefaultPluginManager. If you do
1430 * extend the default plugin manager, the only method you will probably need
1431 * to define is the class constructor, which will need to call the parent
1432 * constructor to provide information about the annotation class and plugin
1433 * namespace for discovery, set up the alter hook, and possibly set up
1434 * caching. See classes that extend DefaultPluginManager for examples.
1435 * - Define a service for your plugin manager. See the
1436 * @link container Services topic for more information. @endlink Your service
1437 * definition should look something like this, referencing your manager
1438 * class and the parent (default) plugin manager service to inherit
1439 * constructor arguments:
1441 * plugin.manager.mymodule:
1442 * class: Drupal\mymodule\MyPluginManager
1443 * parent: default_plugin_manager
1445 * - If your plugin is configurable, you will also need to define the
1446 * configuration schema and possibly a configuration entity type. See the
1447 * @link config_api Configuration API topic @endlink for more information.
1449 * @subsection sub_collection Defining a plugin collection
1450 * Some configurable plugin types allow administrators to create zero or more
1451 * instances of each plugin, each with its own configuration. For example,
1452 * a single block plugin can be configured several times, to display in
1453 * different regions of a theme, with different visibility settings, a
1454 * different title, or other plugin-specific settings. To make this possible,
1455 * a plugin type can make use of what's known as a plugin collection.
1457 * A plugin collection is a class that extends
1458 * \Drupal\Component\Plugin\LazyPluginCollection or one of its subclasses; there
1459 * are several examples in Drupal Core. If your plugin type uses a plugin
1460 * collection, it will usually also have a configuration entity, and the entity
1461 * class should implement
1462 * \Drupal\Core\Entity\EntityWithPluginCollectionInterface. Again, there are
1463 * several examples in Drupal Core; see also the @link config_api Configuration
1464 * API topic @endlink for more information about configuration entities.
1466 * @section sec_create Creating a plugin of an existing type
1467 * Assuming the plugin type uses annotation-based discovery, in order to create
1468 * a plugin of an existing type, you will be creating a class. This class must:
1469 * - Implement the plugin interface, so that it has the required methods
1470 * defined. Usually, you'll want to extend the plugin base class, if one has
1472 * - Have the right annotation in its documentation header. See the
1473 * @link annotation Annotation topic @endlink for more information about
1475 * - Be in the right plugin namespace, in order to be discovered.
1476 * Often, the easiest way to make sure this happens is to find an existing
1477 * example of a working plugin class of the desired type, and copy it into your
1478 * module as a starting point.
1480 * You can also create a plugin derivative, which allows your plugin class
1481 * to present itself to the user interface as multiple plugins. To do this,
1482 * in addition to the plugin class, you'll need to create a separate plugin
1483 * derivative class implementing
1484 * \Drupal\Component\Plugin\Derivative\DerivativeInterface. The classes
1485 * \Drupal\system\Plugin\Block\SystemMenuBlock (plugin class) and
1486 * \Drupal\system\Plugin\Derivative\SystemMenuBlock (derivative class) are a
1487 * good example to look at.
1489 * @section sec_use Performing tasks involving plugins
1490 * Here are the steps to follow to perform a task that involves plugins:
1491 * - Locate the machine name of the plugin manager service, and instantiate the
1492 * service. See the @link container Services topic @endlink for more
1493 * information on how to do this.
1494 * - On the plugin manager class, use methods like getDefinition(),
1495 * getDefinitions(), or other methods specific to particular plugin managers
1496 * to retrieve information about either specific plugins or the entire list of
1498 * - Call the createInstance() method on the plugin manager to instantiate
1499 * individual plugin objects.
1500 * - Call methods on the plugin objects to perform the desired tasks.
1507 * @defgroup oo_conventions Objected-oriented programming conventions
1509 * PSR-4, namespaces, class naming, and other conventions.
1511 * A lot of the PHP code in Drupal is object oriented (OO), making use of
1512 * @link http://php.net/manual/language.oop5.php PHP classes, interfaces, and traits @endlink
1513 * (which are loosely referred to as "classes" in the rest of this topic). The
1514 * following conventions and standards apply to this version of Drupal:
1515 * - Each class must be in its own file.
1516 * - Classes must be namespaced. If a module defines a class, the namespace
1517 * must start with \Drupal\module_name. If it is defined by Drupal Core for
1518 * use across many modules, the namespace should be \Drupal\Core or
1519 * \Drupal\Component, with the exception of the global class \Drupal. See
1520 * https://www.drupal.org/node/1353118 for more about namespaces.
1521 * - In order for the PSR-4-based class auto-loader to find the class, it must
1522 * be located in a directory corresponding to the namespace. For
1523 * module-defined classes, if the namespace is \Drupal\module_name\foo\bar,
1524 * then the class goes under the main module directory in directory
1525 * src/foo/bar. For Drupal-wide classes, if the namespace is
1526 * \Drupal\Core\foo\bar, then it goes in directory
1527 * core/lib/Drupal/Core/foo/bar. See https://www.drupal.org/node/2156625 for
1528 * more information about PSR-4.
1529 * - Some classes have annotations added to their documentation headers. See
1530 * the @link annotation Annotation topic @endlink for more information.
1531 * - Standard plugin discovery requires particular namespaces and annotation
1532 * for most plugin classes. See the
1533 * @link plugin_api Plugin API topic @endlink for more information.
1534 * - There are project-wide coding standards for OO code, including naming:
1535 * https://www.drupal.org/node/608152
1536 * - Documentation standards for classes are covered on:
1537 * https://www.drupal.org/coding-standards/docs#classes
1542 * @defgroup listing_page_class Page header for Classes page
1544 * Introduction to classes
1546 * A lot of the PHP code in Drupal is object oriented (OO), making use of
1547 * @link http://php.net/manual/language.oop5.php PHP classes, interfaces, and traits. @endlink
1549 * @link oo_conventions Objected-oriented programming conventions @endlink
1550 * for more information.
1552 * @see oo_conventions
1558 * @defgroup listing_page_namespace Page header for Namespaces page
1560 * Introduction to namespaces
1562 * PHP classes, interfaces, and traits in Drupal are
1563 * @link http://php.net/manual/en/language.namespaces.rationale.php namespaced. @endlink
1565 * @link oo_conventions Objected-oriented programming conventions @endlink
1566 * for more information.
1568 * @see oo_conventions
1574 * @defgroup best_practices Best practices for developers
1576 * Overview of standards and best practices for developers
1578 * Ideally, all code that is included in Drupal Core and contributed modules,
1579 * themes, and distributions will be secure, internationalized, maintainable,
1580 * and efficient. In order to facilitate this, the Drupal community has
1581 * developed a set of guidelines and standards for developers to follow. Most of
1582 * these standards can be found under
1583 * @link https://www.drupal.org/developing/best-practices Best practices on Drupal.org @endlink
1585 * Standards and best practices that developers should be aware of include:
1586 * - Security: https://www.drupal.org/writing-secure-code and the
1587 * @link sanitization Sanitization functions topic @endlink
1588 * - Coding standards: https://www.drupal.org/coding-standards
1589 * and https://www.drupal.org/coding-standards/docs
1590 * - Accessibility: https://www.drupal.org/node/1637990 (modules) and
1591 * https://www.drupal.org/node/464472 (themes)
1592 * - Usability: https://www.drupal.org/ui-standards
1593 * - Internationalization: @link i18n Internationalization topic @endlink
1594 * - Automated testing: @link testing Automated tests topic @endlink
1599 * @defgroup utility Utility classes and functions
1601 * Overview of utility classes and functions for developers.
1603 * Drupal provides developers with a variety of utility functions that make it
1604 * easier and more efficient to perform tasks that are either really common,
1605 * tedious, or difficult. Utility functions help to reduce code duplication and
1606 * should be used in place of one-off code whenever possible.
1613 * @see transliteration
1619 * @defgroup hooks Hooks
1621 * Define functions that alter the behavior of Drupal core.
1623 * One way for modules to alter the core behavior of Drupal (or another module)
1624 * is to use hooks. Hooks are specially-named functions that a module defines
1625 * (this is known as "implementing the hook"), which are discovered and called
1626 * at specific times to alter or add to the base behavior or data (this is
1627 * known as "invoking the hook"). Each hook has a name (example:
1628 * hook_batch_alter()), a defined set of parameters, and a defined return value.
1629 * Your modules can implement hooks that are defined by Drupal core or other
1630 * modules that they interact with. Your modules can also define their own
1631 * hooks, in order to let other modules interact with them.
1633 * To implement a hook:
1634 * - Locate the documentation for the hook. Hooks are documented in *.api.php
1635 * files, by defining functions whose name starts with "hook_" (these
1636 * files and their functions are never loaded by Drupal -- they exist solely
1637 * for documentation). The function should have a documentation header, as
1638 * well as a sample function body. For example, in the core file
1639 * system.api.php, you can find hooks such as hook_batch_alter(). Also, if
1640 * you are viewing this documentation on an API reference site, the Core
1641 * hooks will be listed in this topic.
1642 * - Copy the function to your module's .module file.
1643 * - Change the name of the function, substituting your module's short name
1644 * (name of the module's directory, and .info.yml file without the extension)
1645 * for the "hook" part of the sample function name. For instance, to implement
1646 * hook_batch_alter(), you would rename it to my_module_batch_alter().
1647 * - Edit the documentation for the function (normally, your implementation
1648 * should just have one line saying "Implements hook_batch_alter().").
1649 * - Edit the body of the function, substituting in what you need your module
1653 * - Choose a unique name for your hook. It should start with "hook_", followed
1654 * by your module's short name.
1655 * - Provide documentation in a *.api.php file in your module's main
1656 * directory. See the "implementing" section above for details of what this
1657 * should contain (parameters, return value, and sample function body).
1658 * - Invoke the hook in your module's code.
1660 * To invoke a hook, use methods on
1661 * \Drupal\Core\Extension\ModuleHandlerInterface such as alter(), invoke(),
1662 * and invokeAll(). You can obtain a module handler by calling
1663 * \Drupal::moduleHandler(), or getting the 'module_handler' service on an
1664 * injected container.
1669 * @see \Drupal\Core\Extension\ModuleHandlerInterface
1670 * @see \Drupal::moduleHandler()
1676 * @defgroup callbacks Callbacks
1678 * Callback function signatures.
1680 * Drupal's API sometimes uses callback functions to allow you to define how
1681 * some type of processing happens. A callback is a function with a defined
1682 * signature, which you define in a module. Then you pass the function name as
1683 * a parameter to a Drupal API function or return it as part of a hook
1684 * implementation return value, and your function is called at an appropriate
1685 * time. For instance, when setting up batch processing you might need to
1686 * provide a callback function for each processing step and/or a callback for
1687 * when processing is finished; you would do that by defining these functions
1688 * and passing their names into the batch setup function.
1690 * Callback function signatures, like hook definitions, are described by
1691 * creating and documenting dummy functions in a *.api.php file; normally, the
1692 * dummy callback function's name should start with "callback_", and you should
1693 * document the parameters and return value and provide a sample function body.
1694 * Then your API documentation can refer to this callback function in its
1695 * documentation. A user of your API can usually name their callback function
1696 * anything they want, although a standard name would be to replace "callback_"
1697 * with the module name.
1706 * @defgroup form_api Form generation
1708 * Describes how to generate and manipulate forms and process form submissions.
1710 * Drupal provides a Form API in order to achieve consistency in its form
1711 * processing and presentation, while simplifying code and reducing the amount
1712 * of HTML that must be explicitly generated by a module.
1714 * @section generating_forms Creating forms
1715 * Forms are defined as classes that implement the
1716 * \Drupal\Core\Form\FormInterface and are built using the
1717 * \Drupal\Core\Form\FormBuilder class. Drupal provides a couple of utility
1718 * classes that can be extended as a starting point for most basic forms, the
1719 * most commonly used of which is \Drupal\Core\Form\FormBase. FormBuilder
1720 * handles the low level processing of forms such as rendering the necessary
1721 * HTML, initial processing of incoming $_POST data, and delegating to your
1722 * implementation of FormInterface for validation and processing of submitted
1725 * Here is an example of a Form class:
1727 * namespace Drupal\mymodule\Form;
1729 * use Drupal\Core\Form\FormBase;
1730 * use Drupal\Core\Form\FormStateInterface;
1732 * class ExampleForm extends FormBase {
1733 * public function getFormId() {
1734 * // Unique ID of the form.
1735 * return 'example_form';
1738 * public function buildForm(array $form, FormStateInterface $form_state) {
1739 * // Create a $form API array.
1740 * $form['phone_number'] = array(
1742 * '#title' => $this->t('Your phone number'),
1744 * $form['save'] = array(
1745 * '#type' => 'submit',
1746 * '#value' => $this->t('Save'),
1751 * public function validateForm(array &$form, FormStateInterface $form_state) {
1752 * // Validate submitted form data.
1755 * public function submitForm(array &$form, FormStateInterface $form_state) {
1756 * // Handle submitted form data.
1761 * @section retrieving_forms Retrieving and displaying forms
1762 * \Drupal::formBuilder()->getForm() should be used to handle retrieving,
1763 * processing, and displaying a rendered HTML form. Given the ExampleForm
1765 * \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\ExampleForm') would
1766 * return the rendered HTML of the form defined by ExampleForm::buildForm(), or
1767 * call the validateForm() and submitForm(), methods depending on the current
1770 * The argument to \Drupal::formBuilder()->getForm() is the name of a class that
1771 * implements FormInterface. Any additional arguments passed to the getForm()
1772 * method will be passed along as additional arguments to the
1773 * ExampleForm::buildForm() method.
1777 * $extra = '612-123-4567';
1778 * $form = \Drupal::formBuilder()->getForm('Drupal\mymodule\Form\ExampleForm', $extra);
1780 * public function buildForm(array $form, FormStateInterface $form_state, $extra = NULL)
1781 * $form['phone_number'] = array(
1783 * '#title' => $this->t('Your phone number'),
1784 * '#value' => $extra,
1790 * Alternatively, forms can be built directly via the routing system which will
1791 * take care of calling \Drupal::formBuilder()->getForm(). The following example
1792 * demonstrates the use of a routing.yml file to display a form at the given
1797 * path: '/example-form'
1799 * _title: 'Example form'
1800 * _form: '\Drupal\mymodule\Form\ExampleForm'
1803 * The $form argument to form-related functions is a specialized render array
1804 * containing the elements and properties of the form. For more about render
1805 * arrays, see the @link theme_render Render API topic. @endlink For more
1806 * detailed explanations of the Form API workflow, see the
1807 * @link https://www.drupal.org/node/2117411 Form API documentation section. @endlink
1808 * In addition, there is a set of Form API tutorials in the
1809 * @link https://www.drupal.org/project/examples Examples for Developers project. @endlink
1811 * In the form builder, validation, submission, and other form methods,
1812 * $form_state is the primary influence on the processing of the form and is
1813 * passed to most methods, so they can use it to communicate with the form
1814 * system and each other. $form_state is an object that implements
1815 * \Drupal\Core\Form\FormStateInterface.
1820 * @defgroup queue Queue operations
1822 * Queue items to allow later processing.
1824 * The queue system allows placing items in a queue and processing them later.
1825 * The system tries to ensure that only one consumer can process an item.
1827 * Before a queue can be used it needs to be created by
1828 * Drupal\Core\Queue\QueueInterface::createQueue().
1830 * Items can be added to the queue by passing an arbitrary data object to
1831 * Drupal\Core\Queue\QueueInterface::createItem().
1833 * To process an item, call Drupal\Core\Queue\QueueInterface::claimItem() and
1834 * specify how long you want to have a lease for working on that item.
1835 * When finished processing, the item needs to be deleted by calling
1836 * Drupal\Core\Queue\QueueInterface::deleteItem(). If the consumer dies, the
1837 * item will be made available again by the Drupal\Core\Queue\QueueInterface
1838 * implementation once the lease expires. Another consumer will then be able to
1839 * receive it when calling Drupal\Core\Queue\QueueInterface::claimItem().
1840 * Due to this, the processing code should be aware that an item might be handed
1841 * over for processing more than once.
1843 * The $item object used by the Drupal\Core\Queue\QueueInterface can contain
1844 * arbitrary metadata depending on the implementation. Systems using the
1845 * interface should only rely on the data property which will contain the
1846 * information passed to Drupal\Core\Queue\QueueInterface::createItem().
1847 * The full queue item returned by Drupal\Core\Queue\QueueInterface::claimItem()
1848 * needs to be passed to Drupal\Core\Queue\QueueInterface::deleteItem() once
1849 * processing is completed.
1851 * There are two kinds of queue backends available: reliable, which preserves
1852 * the order of messages and guarantees that every item will be executed at
1853 * least once. The non-reliable kind only does a best effort to preserve order
1854 * in messages and to execute them at least once but there is a small chance
1855 * that some items get lost. For example, some distributed back-ends like
1856 * Amazon SQS will be managing jobs for a large set of producers and consumers
1857 * where a strict FIFO ordering will likely not be preserved. Another example
1858 * would be an in-memory queue backend which might lose items if it crashes.
1859 * However, such a backend would be able to deal with significantly more writes
1860 * than a reliable queue and for many tasks this is more important. See
1861 * aggregator_cron() for an example of how to effectively use a non-reliable
1862 * queue. Another example is doing Twitter statistics -- the small possibility
1863 * of losing a few items is insignificant next to power of the queue being able
1864 * to keep up with writes. As described in the processing section, regardless
1865 * of the queue being reliable or not, the processing code should be aware that
1866 * an item might be handed over for processing more than once (because the
1867 * processing code might time out before it finishes).
1872 * @defgroup annotation Annotations
1874 * Annotations for class discovery and metadata description.
1876 * The Drupal plugin system has a set of reusable components that developers
1877 * can use, override, and extend in their modules. Most of the plugins use
1878 * annotations, which let classes register themselves as plugins and describe
1879 * their metadata. (Annotations can also be used for other purposes, though
1880 * at the moment, Drupal only uses them for the plugin system.)
1882 * To annotate a class as a plugin, add code similar to the following to the
1883 * end of the documentation block immediately preceding the class declaration:
1885 * * @ContentEntityType(
1887 * * label = @Translation("Comment"),
1889 * * base_table = "comment"
1893 * Note that you must use double quotes; single quotes will not work in
1896 * Some annotation types, which extend the "@ PluginID" annotation class, have
1897 * only a single 'id' key in their annotation. For these, it is possible to use
1898 * a shorthand annotation. For example:
1900 * * @ViewsArea("entity")
1909 * The available annotation classes are listed in this topic, and can be
1910 * identified when you are looking at the Drupal source code by having
1911 * "@ Annotation" in their documentation blocks (without the space after @). To
1912 * find examples of annotation for a particular annotation class, such as
1913 * EntityType, look for class files that have an @ annotation section using the
1916 * @see plugin_translatable
1917 * @see plugin_context
1928 * Perform periodic actions.
1930 * Modules that require some commands to be executed periodically can
1931 * implement hook_cron(). The engine will then call the hook whenever a cron
1932 * run happens, as defined by the administrator. Typical tasks managed by
1933 * hook_cron() are database maintenance, backups, recalculation of settings
1934 * or parameters, automated mailing, and retrieving remote data.
1936 * Short-running or non-resource-intensive tasks can be executed directly in
1937 * the hook_cron() implementation.
1939 * Long-running tasks and tasks that could time out, such as retrieving remote
1940 * data, sending email, and intensive file tasks, should use the queue API
1941 * instead of executing the tasks directly. To do this, first define one or
1942 * more queues via a \Drupal\Core\Annotation\QueueWorker plugin. Then, add items
1943 * that need to be processed to the defined queues.
1945 function hook_cron() {
1946 // Short-running operation example, not using a queue:
1947 // Delete all expired records since the last cron run.
1948 $expires = \Drupal::state()->get('mymodule.last_check', 0);
1949 \Drupal::database()->delete('mymodule_table')
1950 ->condition('expires', $expires, '>=')
1952 \Drupal::state()->set('mymodule.last_check', REQUEST_TIME);
1954 // Long-running operation example, leveraging a queue:
1955 // Queue news feeds for updates once their refresh interval has elapsed.
1956 $queue = \Drupal::queue('aggregator_feeds');
1957 $ids = \Drupal::entityManager()->getStorage('aggregator_feed')->getFeedIdsToRefresh();
1958 foreach (Feed::loadMultiple($ids) as $feed) {
1959 if ($queue->createItem($feed)) {
1960 // Add timestamp to avoid queueing item more than once.
1961 $feed->setQueuedTime(REQUEST_TIME);
1965 $ids = \Drupal::entityQuery('aggregator_feed')
1966 ->condition('queued', REQUEST_TIME - (3600 * 6), '<')
1969 $feeds = Feed::loadMultiple($ids);
1970 foreach ($feeds as $feed) {
1971 $feed->setQueuedTime(0);
1978 * Alter available data types for typed data wrappers.
1980 * @param array $data_types
1981 * An array of data type information.
1983 * @see hook_data_type_info()
1985 function hook_data_type_info_alter(&$data_types) {
1986 $data_types['email']['class'] = '\Drupal\mymodule\Type\Email';
1990 * Alter cron queue information before cron runs.
1992 * Called by \Drupal\Core\Cron to allow modules to alter cron queue settings
1993 * before any jobs are processesed.
1995 * @param array $queues
1996 * An array of cron queue information.
1998 * @see \Drupal\Core\QueueWorker\QueueWorkerInterface
1999 * @see \Drupal\Core\Annotation\QueueWorker
2000 * @see \Drupal\Core\Cron
2002 function hook_queue_info_alter(&$queues) {
2003 // This site has many feeds so let's spend 90 seconds on each cron run
2004 // updating feeds instead of the default 60.
2005 $queues['aggregator_feeds']['cron']['time'] = 90;
2009 * Alter an email message created with MailManagerInterface->mail().
2011 * hook_mail_alter() allows modification of email messages created and sent
2012 * with MailManagerInterface->mail(). Usage examples include adding and/or
2013 * changing message text, message fields, and message headers.
2015 * Email messages sent using functions other than MailManagerInterface->mail()
2016 * will not invoke hook_mail_alter(). For example, a contributed module directly
2017 * calling the MailInterface->mail() or PHP mail() function will not invoke
2018 * this hook. All core modules use MailManagerInterface->mail() for messaging,
2019 * it is best practice but not mandatory in contributed modules.
2022 * An array containing the message data. Keys in this array include:
2024 * The MailManagerInterface->mail() id of the message. Look at module source
2025 * code or MailManagerInterface->mail() for possible id values.
2027 * The address or addresses the message will be sent to. The
2028 * formatting of this string must comply with RFC 2822.
2030 * The address the message will be marked as being from, which is
2031 * either a custom address or the site-wide default email address.
2033 * Subject of the email to be sent. This must not contain any newline
2034 * characters, or the email may not be sent properly.
2036 * An array of strings or objects that implement
2037 * \Drupal\Component\Render\MarkupInterface containing the message text. The
2038 * message body is created by concatenating the individual array strings
2039 * into a single text string using "\n\n" as a separator.
2041 * Associative array containing mail headers, such as From, Sender,
2042 * MIME-Version, Content-Type, etc.
2044 * An array of optional parameters supplied by the caller of
2045 * MailManagerInterface->mail() that is used to build the message before
2046 * hook_mail_alter() is invoked.
2048 * The language object used to build the message before hook_mail_alter()
2051 * Set to FALSE to abort sending this email message.
2053 * @see \Drupal\Core\Mail\MailManagerInterface::mail()
2055 function hook_mail_alter(&$message) {
2056 if ($message['id'] == 'modulename_messagekey') {
2057 if (!example_notifications_optin($message['to'], $message['id'])) {
2058 // If the recipient has opted to not receive such messages, cancel
2060 $message['send'] = FALSE;
2063 $message['body'][] = "--\nMail sent out from " . \Drupal::config('system.site')->get('name');
2068 * Prepares a message based on parameters;
2070 * This hook is called from MailManagerInterface->mail(). Note that hook_mail(),
2071 * unlike hook_mail_alter(), is only called on the $module argument to
2072 * MailManagerInterface->mail(), not all modules.
2075 * An identifier of the mail.
2077 * An array to be filled in. Elements in this array include:
2078 * - id: An ID to identify the mail sent. Look at module source code or
2079 * MailManagerInterface->mail() for possible id values.
2080 * - to: The address or addresses the message will be sent to. The
2081 * formatting of this string must comply with RFC 2822.
2082 * - subject: Subject of the email to be sent. This must not contain any
2083 * newline characters, or the mail may not be sent properly.
2084 * MailManagerInterface->mail() sets this to an empty
2085 * string when the hook is invoked.
2086 * - body: An array of lines containing the message to be sent. Drupal will
2087 * format the correct line endings for you. MailManagerInterface->mail()
2088 * sets this to an empty array when the hook is invoked. The array may
2089 * contain either strings or objects implementing
2090 * \Drupal\Component\Render\MarkupInterface.
2091 * - from: The address the message will be marked as being from, which is
2092 * set by MailManagerInterface->mail() to either a custom address or the
2093 * site-wide default email address when the hook is invoked.
2094 * - headers: Associative array containing mail headers, such as From,
2095 * Sender, MIME-Version, Content-Type, etc.
2096 * MailManagerInterface->mail() pre-fills several headers in this array.
2098 * An array of parameters supplied by the caller of
2099 * MailManagerInterface->mail().
2101 * @see \Drupal\Core\Mail\MailManagerInterface::mail()
2103 function hook_mail($key, &$message, $params) {
2104 $account = $params['account'];
2105 $context = $params['context'];
2107 '%site_name' => \Drupal::config('system.site')->get('name'),
2108 '%username' => $account->getDisplayName(),
2110 if ($context['hook'] == 'taxonomy') {
2111 $entity = $params['entity'];
2112 $vocabulary = Vocabulary::load($entity->id());
2114 '%term_name' => $entity->name,
2115 '%term_description' => $entity->description,
2116 '%term_id' => $entity->id(),
2117 '%vocabulary_name' => $vocabulary->label(),
2118 '%vocabulary_description' => $vocabulary->getDescription(),
2119 '%vocabulary_id' => $vocabulary->id(),
2123 // Node-based variable translation is only available if we have a node.
2124 if (isset($params['node'])) {
2125 /** @var \Drupal\node\NodeInterface $node */
2126 $node = $params['node'];
2128 '%uid' => $node->getOwnerId(),
2129 '%url' => $node->url('canonical', ['absolute' => TRUE]),
2130 '%node_type' => node_get_type_label($node),
2131 '%title' => $node->getTitle(),
2132 '%teaser' => $node->teaser,
2133 '%body' => $node->body,
2136 $subject = strtr($context['subject'], $variables);
2137 $body = strtr($context['message'], $variables);
2138 $message['subject'] .= str_replace(["\r", "\n"], '', $subject);
2139 $message['body'][] = MailFormatHelper::htmlToText($body);
2143 * Alter the list of mail backend plugin definitions.
2145 * @param array $info
2146 * The mail backend plugin definitions to be altered.
2148 * @see \Drupal\Core\Annotation\Mail
2149 * @see \Drupal\Core\Mail\MailManager
2151 function hook_mail_backend_info_alter(&$info) {
2152 unset($info['test_mail_collector']);
2156 * Alter the default country list.
2159 * The associative array of countries keyed by two-letter country code.
2161 * @see \Drupal\Core\Locale\CountryManager::getList()
2163 function hook_countries_alter(&$countries) {
2164 // Elbonia is now independent, so add it to the country list.
2165 $countries['EB'] = 'Elbonia';
2169 * Alter display variant plugin definitions.
2171 * @param array $definitions
2172 * The array of display variant definitions, keyed by plugin ID.
2174 * @see \Drupal\Core\Display\VariantManager
2175 * @see \Drupal\Core\Display\Annotation\DisplayVariant
2177 function hook_display_variant_plugin_alter(array &$definitions) {
2178 $definitions['full_page']['admin_label'] = t('Block layout');
2182 * Allow modules to alter layout plugin definitions.
2184 * @param \Drupal\Core\Layout\LayoutDefinition[] $definitions
2185 * The array of layout definitions, keyed by plugin ID.
2187 function hook_layout_alter(&$definitions) {
2189 unset($definitions['twocol']);
2193 * Flush all persistent and static caches.
2195 * This hook asks your module to clear all of its static caches,
2196 * in order to ensure a clean environment for subsequently
2197 * invoked data rebuilds.
2199 * Do NOT use this hook for rebuilding information. Only use it to flush custom
2202 * Static caches using drupal_static() do not need to be reset manually.
2203 * However, all other static variables that do not use drupal_static() must be
2206 * This hook is invoked by drupal_flush_all_caches(). It runs before module data
2207 * is updated and before hook_rebuild().
2209 * @see drupal_flush_all_caches()
2210 * @see hook_rebuild()
2212 function hook_cache_flush() {
2213 if (defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'update') {
2214 _update_cache_clear();
2219 * Rebuild data based upon refreshed caches.
2221 * This hook allows your module to rebuild its data based on the latest/current
2222 * module data. It runs after hook_cache_flush() and after all module data has
2225 * This hook is only invoked after the system has been completely cleared;
2226 * i.e., all previously cached data is known to be gone and every API in the
2227 * system is known to return current information, so your module can safely rely
2228 * on all available data to rebuild its own.
2230 * @see hook_cache_flush()
2231 * @see drupal_flush_all_caches()
2233 function hook_rebuild() {
2234 $themes = \Drupal::service('theme_handler')->listInfo();
2235 foreach ($themes as $theme) {
2236 _block_rehash($theme->getName());
2241 * Alter the configuration synchronization steps.
2243 * @param array $sync_steps
2244 * A one-dimensional array of \Drupal\Core\Config\ConfigImporter method names
2245 * or callables that are invoked to complete the import, in the order that
2246 * they will be processed. Each callable item defined in $sync_steps should
2247 * either be a global function or a public static method. The callable should
2248 * accept a $context array by reference. For example:
2250 * function _additional_configuration_step(&$context) {
2252 * // If finished set $context['finished'] = 1.
2255 * For more information on creating batches, see the
2256 * @link batch Batch operations @endlink documentation.
2258 * @see callback_batch_operation()
2259 * @see \Drupal\Core\Config\ConfigImporter::initialize()
2261 function hook_config_import_steps_alter(&$sync_steps, \Drupal\Core\Config\ConfigImporter $config_importer) {
2262 $deletes = $config_importer->getUnprocessedConfiguration('delete');
2263 if (isset($deletes['field.storage.node.body'])) {
2264 $sync_steps[] = '_additional_configuration_step';
2269 * Alter config typed data definitions.
2271 * For example you can alter the typed data types representing each
2272 * configuration schema type to change default labels or form element renderers
2273 * used for configuration translation.
2275 * If implementations of this hook add or remove configuration schema a
2276 * ConfigSchemaAlterException will be thrown. Keep in mind that there are tools
2277 * that may use the configuration schema for static analysis of configuration
2278 * files, like the string extractor for the localization system. Such systems
2279 * won't work with dynamically defined configuration schemas.
2281 * For adding new data types use configuration schema YAML files instead.
2283 * @param $definitions
2284 * Associative array of configuration type definitions keyed by schema type
2285 * names. The elements are themselves array with information about the type.
2287 * @see \Drupal\Core\Config\TypedConfigManager
2288 * @see \Drupal\Core\Config\Schema\ConfigSchemaAlterException
2290 function hook_config_schema_info_alter(&$definitions) {
2291 // Enhance the text and date type definitions with classes to generate proper
2292 // form elements in ConfigTranslationFormBase. Other translatable types will
2293 // appear as a one line textfield.
2294 $definitions['text']['form_element_class'] = '\Drupal\config_translation\FormElement\Textarea';
2295 $definitions['date_format']['form_element_class'] = '\Drupal\config_translation\FormElement\DateFormat';
2299 * Alter validation constraint plugin definitions.
2301 * @param array[] $definitions
2302 * The array of validation constraint definitions, keyed by plugin ID.
2304 * @see \Drupal\Core\Validation\ConstraintManager
2305 * @see \Drupal\Core\Validation\Annotation\Constraint
2307 function hook_validation_constraint_alter(array &$definitions) {
2308 $definitions['Null']['class'] = '\Drupal\mymodule\Validator\Constraints\MyClass';
2312 * @} End of "addtogroup hooks".
2316 * @defgroup ajax Ajax API
2318 * Overview for Drupal's Ajax API.
2320 * @section sec_overview Overview of Ajax
2321 * Ajax is the process of dynamically updating parts of a page's HTML based on
2322 * data from the server. When a specified event takes place, a PHP callback is
2323 * triggered, which performs server-side logic and may return updated markup or
2324 * JavaScript commands to run. After the return, the browser runs the JavaScript
2325 * or updates the markup on the fly, with no full page refresh necessary.
2327 * Many different events can trigger Ajax responses, including:
2328 * - Clicking a button
2330 * - Moving the mouse
2332 * @section sec_framework Ajax responses in forms
2333 * Forms that use the Drupal Form API (see the
2334 * @link form_api Form API topic @endlink for more information about forms) can
2335 * trigger AJAX responses. Here is an outline of the steps:
2336 * - Add property '#ajax' to a form element in your form array, to trigger an
2338 * - Write an Ajax callback to process the input and respond.
2339 * See sections below for details on these two steps.
2341 * @subsection sub_form Adding Ajax triggers to a form
2342 * As an example of adding Ajax triggers to a form, consider editing a date
2343 * format, where the user is provided with a sample of the generated date output
2344 * as they type. To accomplish this, typing in the text field should trigger an
2345 * Ajax response. This is done in the text field form array element
2346 * in \Drupal\config_translation\FormElement\DateFormat::getFormElement():
2349 * 'callback' => 'Drupal\config_translation\FormElement\DateFormat::ajaxSample',
2350 * 'event' => 'keyup',
2351 * 'progress' => array(
2352 * 'type' => 'throbber',
2353 * 'message' => NULL,
2358 * As you can see from this example, the #ajax property for a form element is
2359 * an array. Here are the details of its elements, all of which are optional:
2360 * - callback: The callback to invoke to handle the server side of the
2361 * Ajax event. More information on callbacks is below in @ref sub_callback.
2362 * - wrapper: The HTML 'id' attribute of the area where the content returned by
2363 * the callback should be placed. Note that callbacks have a choice of
2364 * returning content or JavaScript commands; 'wrapper' is used for content
2366 * - method: The jQuery method for placing the new content (used with
2367 * 'wrapper'). Valid options are 'replaceWith' (default), 'append', 'prepend',
2368 * 'before', 'after', or 'html'. See
2369 * http://api.jquery.com/category/manipulation/ for more information on these
2371 * - effect: The jQuery effect to use when placing the new HTML (used with
2372 * 'wrapper'). Valid options are 'none' (default), 'slide', or 'fade'.
2373 * - speed: The effect speed to use (used with 'effect' and 'wrapper'). Valid
2374 * options are 'slow' (default), 'fast', or the number of milliseconds the
2375 * effect should run.
2376 * - event: The JavaScript event to respond to. This is selected automatically
2377 * for the type of form element; provide a value to override the default.
2378 * - prevent: A JavaScript event to prevent when the event is triggered. For
2379 * example, if you use event 'mousedown' on a button, you might want to
2380 * prevent 'click' events from also being triggered.
2381 * - progress: An array indicating how to show Ajax processing progress. Can
2382 * contain one or more of these elements:
2383 * - type: Type of indicator: 'throbber' (default) or 'bar'.
2384 * - message: Translated message to display.
2385 * - url: For a bar progress indicator, URL path for determining progress.
2386 * - interval: For a bar progress indicator, how often to update it.
2387 * - url: A \Drupal\Core\Url to which to submit the Ajax request. If omitted,
2388 * defaults to either the same URL as the form or link destination is for
2389 * someone with JavaScript disabled, or a slightly modified version (e.g.,
2390 * with a query parameter added, removed, or changed) of that URL if
2391 * necessary to support Drupal's content negotiation. It is recommended to
2392 * omit this key and use Drupal's content negotiation rather than using
2393 * substantially different URLs between Ajax and non-Ajax.
2395 * @subsection sub_callback Setting up a callback to process Ajax
2396 * Once you have set up your form to trigger an Ajax response (see @ref sub_form
2397 * above), you need to write some PHP code to process the response. If you use
2398 * 'path' in your Ajax set-up, your route controller will be triggered with only
2399 * the information you provide in the URL. If you use 'callback', your callback
2400 * method is a function, which will receive the $form and $form_state from the
2401 * triggering form. You can use $form_state to get information about the
2402 * data the user has entered into the form. For instance, in the above example
2403 * for the date format preview,
2404 * \Drupal\config_translation\FormElement\DateFormat\ajaxSample() does this to
2405 * get the format string entered by the user:
2407 * $format_value = \Drupal\Component\Utility\NestedArray::getValue(
2408 * $form_state->getValues(),
2409 * $form_state->getTriggeringElement()['#array_parents']);
2412 * Once you have processed the input, you have your choice of returning HTML
2413 * markup or a set of Ajax commands. If you choose to return HTML markup, you
2414 * can return it as a string or a renderable array, and it will be placed in
2415 * the defined 'wrapper' element (see documentation above in @ref sub_form).
2416 * In addition, any messages returned by drupal_get_messages(), themed as in
2417 * status-messages.html.twig, will be prepended.
2419 * To return commands, you need to set up an object of class
2420 * \Drupal\Core\Ajax\AjaxResponse, and then use its addCommand() method to add
2421 * individual commands to it. In the date format preview example, the format
2422 * output is calculated, and then it is returned as replacement markup for a div
2425 * $response = new AjaxResponse();
2426 * $response->addCommand(new ReplaceCommand(
2427 * '#edit-date-format-suffix',
2428 * '<small id="edit-date-format-suffix">' . $format . '</small>'));
2432 * The individual commands that you can return implement interface
2433 * \Drupal\Core\Ajax\CommandInterface. Available commands provide the ability
2434 * to pop up alerts, manipulate text and markup in various ways, redirect
2435 * to a new URL, and the generic \Drupal\Core\Ajax\InvokeCommand, which
2436 * invokes an arbitrary jQuery command.
2438 * As noted above, status messages are prepended automatically if you use the
2439 * 'wrapper' method and return HTML markup. This is not the case if you return
2440 * commands, but if you would like to show status messages, you can add
2442 * array('#type' => 'status_messages')
2444 * to a render array, use drupal_render() to render it, and add a command to
2445 * place the messages in an appropriate location.
2447 * @section sec_other Other methods for triggering Ajax
2448 * Here are some additional methods you can use to trigger Ajax responses in
2450 * - Add class 'use-ajax' to a link. The link will be loaded using an Ajax
2451 * call. When using this method, the href of the link can contain '/nojs/' as
2452 * part of the path. When the Ajax JavaScript processes the page, it will
2453 * convert this to '/ajax/'. The server is then able to easily tell if this
2454 * request was made through an actual Ajax request or in a degraded state, and
2455 * respond appropriately.
2456 * - Add class 'use-ajax-submit' to a submit button in a form. The form will
2457 * then be submitted via Ajax to the path specified in the #action. Like the
2458 * ajax-submit class on links, this path will have '/nojs/' replaced with
2459 * '/ajax/' so that the submit handler can tell if the form was submitted in a
2460 * degraded state or not.
2461 * - Add property '#autocomplete_route_name' to a text field in a form. The
2462 * route controller for this route must return an array of options for
2463 * autocomplete, as a \Symfony\Component\HttpFoundation\JsonResponse object.
2464 * See the @link menu Routing topic @endlink for more information about
2469 * @} End of "defgroup ajax".
2473 * @defgroup service_tag Service Tags
2475 * Service tags overview
2477 * Some services have tags, which are defined in the service definition. Tags
2478 * are used to define a group of related services, or to specify some aspect of
2479 * how the service behaves. Typically, if you tag a service, your service class
2480 * must also implement a corresponding interface. Some common examples:
2481 * - access_check: Indicates a route access checking service; see the
2482 * @link menu Menu and routing system topic @endlink for more information.
2483 * - cache.bin: Indicates a cache bin service; see the
2484 * @link cache Cache topic @endlink for more information.
2485 * - event_subscriber: Indicates an event subscriber service. Event subscribers
2486 * can be used for dynamic routing and route altering; see the
2487 * @link menu Menu and routing system topic @endlink for more information.
2488 * They can also be used for other purposes; see
2489 * http://symfony.com/doc/current/cookbook/doctrine/event_listeners_subscribers.html
2490 * for more information.
2491 * - needs_destruction: Indicates that a destruct() method needs to be called
2492 * at the end of a request to finalize operations, if this service was
2493 * instantiated. Services should implement \Drupal\Core\DestructableInterface
2495 * - context_provider: Indicates a block context provider, used for example
2496 * by block conditions. It has to implement
2497 * \Drupal\Core\Plugin\Context\ContextProviderInterface.
2498 * - http_client_middleware: Indicates that the service provides a guzzle
2500 * https://guzzle.readthedocs.org/en/latest/handlers-and-middleware.html for
2503 * Creating a tag for a service does not do anything on its own, but tags
2504 * can be discovered or queried in a compiler pass when the container is built,
2505 * and a corresponding action can be taken. See
2506 * \Drupal\Core\Render\MainContent\MainContentRenderersPass for an example of
2507 * finding tagged services.
2509 * See @link container Services and Dependency Injection Container @endlink for
2510 * information on services and the dependency injection container.
2516 * @defgroup events Events
2518 * Overview of event dispatch and subscribing
2520 * @section sec_intro Introduction and terminology
2521 * Events are part of the Symfony framework: they allow for different components
2522 * of the system to interact and communicate with each other. Each event has a
2523 * unique string name. One system component dispatches the event at an
2524 * appropriate time; many events are dispatched by Drupal core and the Symfony
2525 * framework in every request. Other system components can register as event
2526 * subscribers; when an event is dispatched, a method is called on each
2527 * registered subscriber, allowing each one to react. For more on the general
2528 * concept of events, see
2529 * http://symfony.com/doc/current/components/event_dispatcher/introduction.html
2531 * @section sec_dispatch Dispatching events
2532 * To dispatch an event, call the
2533 * \Symfony\Component\EventDispatcher\EventDispatchInterface::dispatch() method
2534 * on the 'event_dispatcher' service (see the
2535 * @link container Services topic @endlink for more information about how to
2536 * interact with services). The first argument is the unique event name, which
2537 * you should normally define as a constant in a separate static class (see
2538 * \Symfony\Component\HttpKernel\KernelEvents and
2539 * \Drupal\Core\Config\ConfigEvents for examples). The second argument is a
2540 * \Symfony\Component\EventDispatcher\Event object; normally you will need to
2541 * extend this class, so that your event class can provide data to the event
2544 * @section sec_subscribe Registering event subscribers
2545 * Here are the steps to register an event subscriber:
2546 * - Define a service in your module, tagged with 'event_subscriber' (see the
2547 * @link container Services topic @endlink for instructions).
2548 * - Define a class for your subscriber service that implements
2549 * \Symfony\Component\EventDispatcher\EventSubscriberInterface
2550 * - In your class, the getSubscribedEvents method returns a list of the events
2551 * this class is subscribed to, and which methods on the class should be
2552 * called for each one. Example:
2554 * public static function getSubscribedEvents() {
2555 * // Subscribe to kernel terminate with priority 100.
2556 * $events[KernelEvents::TERMINATE][] = array('onTerminate', 100);
2557 * // Subscribe to kernel request with default priority of 0.
2558 * $events[KernelEvents::REQUEST][] = array('onRequest');
2562 * - Write the methods that respond to the events; each one receives the
2563 * event object provided in the dispatch as its one argument. In the above
2564 * example, you would need to write onTerminate() and onRequest() methods.
2566 * Note that in your getSubscribedEvents() method, you can optionally set the
2567 * priority of your event subscriber (see terminate example above). Event
2568 * subscribers with higher priority numbers get executed first; the default
2569 * priority is zero. If two event subscribers for the same event have the same
2570 * priority, the one defined in a module with a lower module weight will fire
2571 * first. Subscribers defined in the same services file are fired in
2572 * definition order. If order matters defining a priority is strongly advised
2573 * instead of relying on these two tie breaker rules as they might change in a