Table of Contents for
Drupal 8 Module Development

Version ebook / Retour

Cover image for bash Cookbook, 2nd Edition Drupal 8 Module Development by Daniel Sipos Published by Packt Publishing, 2017
  1. Drupal 8 Module Development
  2. Title Page
  3. Copyright
  4. Drupal 8 Module Development
  5. Credits
  6. About the Author
  7. About the Reviewers
  8. www.PacktPub.com
  9. Why subscribe?
  10. Customer Feedback
  11. Table of Contents
  12. Preface
  13. What this book covers
  14. What you need for this book
  15. Who this book is for
  16. Conventions
  17. Reader feedback
  18. Customer support
  19. Downloading the example code
  20. Downloading the color images of this book 
  21. Errata
  22. Piracy
  23. Questions
  24. Developing for Drupal 8
  25. Introducing Drupal (for developers)
  26. Developing for Drupal 8
  27. Technologies that drive Drupal
  28. PHP
  29. Databases and MySQL
  30. The web server
  31. HTML, CSS, and JavaScript
  32. Drupal architecture
  33. Drupal core, modules, and themes
  34. Hooks, plugins, and events
  35. Services and the dependency injection container
  36. From request to response
  37. Drupal's major subsystems
  38. Routing
  39. Entities
  40. Fields
  41. Menus
  42. Views
  43. Forms
  44. Configuration
  45. Plugins
  46. The theme system
  47. Caching
  48. Other subsystems
  49. Tools for developing in Drupal
  50. Version control
  51. Composer
  52. The API site and coding standards
  53. The developer (Devel) module
  54. Drush (the Drupal shell)
  55. Drupal Console
  56. Developer settings
  57. Summary
  58. Creating Your First Module
  59. Creating a module
  60. Your first hook implementation
  61. Route and controller
  62. The route
  63. Route variables
  64. Namespaces
  65. The Controller
  66. Services
  67. What is a service?
  68. The HelloWorldSalutation service
  69. Tagged services
  70. Using services in Drupal 8
  71. Injecting the service into our Controller
  72. The form
  73. Altering forms
  74. Custom submit handlers
  75. Rendering forms
  76. Service dependencies
  77. Blocks
  78. Our first block plugin
  79. Block configuration
  80. Working with links
  81. The URL
  82. The link
  83. Which way to link?
  84. Event Dispatcher and redirects
  85. Redirecting from a Controller
  86. Redirecting from a subscriber
  87. Dispatching events
  88. Summary
  89. Logging and Mailing
  90. Logging
  91. The Drupal 8 logging theory
  92. Our own logger channel
  93. Our own logger
  94. Logging for Hello World
  95. Logging summary
  96. Mail API
  97. The theory of the Mail API
  98. Implementing hook_mail()
  99. Sending emails
  100. Altering someone else's emails
  101. Custom mail plugins
  102. The mail plugin
  103. Using mail plugins
  104. Tokens
  105. The Token API
  106. Using tokens
  107. Defining new tokens
  108. Token summary
  109. Summary
  110. Theming
  111. Business logic versus presentation logic
  112. Twig
  113. Theme hooks
  114. Theme hook suggestions
  115. Render arrays
  116. The structure of a render array
  117. #type
  118. #theme
  119. #markup
  120. The render pipeline
  121. Assets and libraries
  122. Libraries
  123. Attaching libraries
  124. Common theme hooks
  125. Lists
  126. Links
  127. Tables
  128. Attributes
  129. Theming our Hello World module
  130. Summary
  131. Menus and Menu Links
  132. The menu system
  133. Menus
  134. Menu links
  135. Multiple types of menu links
  136. Local tasks
  137. Local actions
  138. Contextual links
  139. MenuLink trees
  140. Menu link tree manipulators
  141. Menu active trail
  142. Rendering menus
  143. Working with menu links
  144. Defining menu links
  145. Working with menu links
  146. Defining local tasks
  147. Defining local actions
  148. Defining contextual links
  149. Summary
  150. Data Modeling and Storage
  151. Different types of data storage
  152. State API
  153. Tempstore
  154. PrivateTempStore
  155. A note about anonymous users
  156. SharedTempStore
  157. Tempstore conclusion
  158. UserData
  159. Configuration
  160. Introduction
  161. What is configuration used for?
  162. Managing configuration
  163. Different types of configuration
  164. Configuration storage
  165. Schema
  166. Overrides
  167. Global overrides
  168. Module overrides
  169. Language overrides
  170. Priority
  171. Interacting with simple configuration
  172. Entities
  173. Content versus configuration entity types
  174. Entity type plugins
  175. Identifiers
  176. Bundles
  177. Database tables
  178. Entity keys
  179. Links
  180. Entity translation
  181. Entity revisions
  182. Configuration export
  183. Handlers
  184. Fields
  185. Configuration entity fields
  186. Content entity fields
  187. Base fields
  188. Configurable fields
  189. Field storage
  190. Entity types summary
  191. TypedData
  192. Why?
  193. What?
  194. The low-level API
  195. DataType plugins
  196. Data definitions
  197. Content entities
  198. TypedData summary
  199. Interacting with the Entity API
  200. Querying and loading entities
  201. Building queries
  202. Loading entities
  203. Reading entities
  204. Manipulating entities
  205. Creating entities
  206. Rendering content entities
  207. Pseudo-fields
  208. Content entity validation
  209. Validation summary
  210. Summary
  211. Your Own Custom Entity and Plugin Types
  212. Custom content entity type
  213. Custom plugin type
  214. Custom configuration entity type
  215. The Importer plugin
  216. Content entity bundles
  217. Drush command
  218. Summary
  219. The Database API
  220. The Schema API
  221. Running queries
  222. Select queries
  223. Handling the result
  224. More complex select queries
  225. Range queries
  226. Pagers
  227. Insert queries
  228. Update queries
  229. Delete queries
  230. Transactions
  231. Query alters
  232. Update hooks
  233. Summary
  234. Custom Fields
  235. Field type
  236. Field widget
  237. Field formatter
  238. Field settings
  239. Using as a base field
  240. Summary
  241. Access Control
  242. Introduction to the Drupal access system
  243. Roles and permissions under the hood
  244. Defining permissions
  245. Checking the user credentials
  246. Route access
  247. Custom route access
  248. Static approach
  249. Service approach
  250. Programmatically checking access on routes
  251. Bonus - dynamic route options for access control
  252. CSRF protection on routes
  253. Altering routes
  254. Entity access
  255. Injecting services into Entity handlers
  256. Entity access hooks
  257. Field access
  258. Entity access in routes
  259. Node access grants
  260. Block access
  261. Summary
  262. Caching
  263. Introduction
  264. Cacheability metadata
  265. Cache tags
  266. Cache contexts
  267. Max-age
  268. Using the cache metadata
  269. Caching in block plugins
  270. Caching access results
  271. Placeholders and lazy building
  272. Lazy builders
  273. Using the Cache API
  274. Creating our own cache bin
  275. Summary
  276. JavaScript and the Ajax API
  277. JavaScript in Drupal
  278. Drupal behaviors
  279. Our library
  280. The JavaScript
  281. Drupal settings
  282. Ajax API
  283. Ajax links
  284. Ajax in forms
  285. States (Form) system
  286. Summary
  287. Internationalization and Languages
  288. Introduction
  289. Language
  290. Content Translation
  291. Configuration Translation
  292. Interface Translation
  293. Internationalization
  294. Content entities and the Translation API
  295. Summary
  296. Batches, Queues, and Cron
  297. Batch powered update hooks
  298. Batch operations
  299. Creating the batch
  300. Batch operations
  301. Cron
  302. Queues
  303. Introduction to the Queue API
  304. Cron based queue
  305. Processing a queue programmatically
  306. Lock API
  307. Summary
  308. Views
  309. Entities in Views
  310. Exposing custom data to Views
  311. Views data
  312. Views fields
  313. Views relationships
  314. Views sorts and filters
  315. Views arguments
  316. Altering Views data
  317. Custom Views field
  318. Field configuration
  319. Custom Views filter
  320. Custom Views argument
  321. Views theming
  322. Views hooks
  323. Summary
  324. Working with Files and Images
  325. The filesystem
  326. Stream wrappers
  327. Managed versus unmanaged files
  328. Using the File and Image fields
  329. Working with managed files
  330. Attaching managed files to entities
  331. Helpful functions for dealing with managed files
  332. Managed file uploads
  333. Managed file form element
  334. Entity CRUD hooks
  335. Managed file usage service
  336. Processing the CSV file
  337. Our own stream wrapper
  338. Working with unmanaged files
  339. Private file system
  340. Images
  341. Image toolkits
  342. Image styles
  343. Rendering images
  344. Summary
  345. Automated Testing
  346. Testing methodologies in Drupal 8
  347. PHPUnit
  348. Registering tests
  349. Unit tests
  350. Mocked dependencies
  351. Kernel tests
  352. TeamCleaner test
  353. CsvImporter test
  354. Functional tests
  355. Configuration for functional tests
  356. Hello World page test
  357. Hello World form test
  358. Functional JavaScript tests
  359. Time test
  360. CsvImporter test
  361. Summary
  362. Drupal 8 Security
  363. Cross-Site Scripting (XSS)
  364. Sanitization methods in Drupal 8
  365. Double escaping
  366. SQL Injection
  367. Cross-Site Request Forgery (CSRF)
  368. Summary

Content entity validation

The last thing we are going to talk about in this chapter is entity validation and how we can make sure that field and entity data as a whole contains valid data. When I say valid, I don't mean whether it complies with the strict TypedData definition but whether, within that, it complies with certain restrictions (constraints) we impose on it.

Drupal 8 uses the Symfony Validator component for applying constraints and then validating entities, fields and any other data against those constraints. I do recommend that you check out the Symfony documentation page on this component to better understand its principles. For now, let's quickly see how it is applied in Drupal 8.

There are three main parts to a validation--a constraint plugin, a validator class and potential violations. The first is mainly responsible for defining what kind of data it can be applied to, the error message it should show, and which validator class is responsible for validating it. If it omits the latter, the validator class name defaults to the name of the constraint class with the word Validator appended to it. The validator, on the other hand, is called by the validation service to validate the constraint and build a list of violations. Finally, the violations are data objects which provide helpful information about what went wrong in the validation things like the error message from the constraint, the offending value, the path to the property that failed. To better understand things, we have to go back to the TypedData and see some simple examples because that is the level at which the validation happens.

So, let's look at the same example I introduced TypedData with:

$definition = DataDefinition::create('string');
$definition->addConstraint('Length', ['max' => 20]);

The data definitions have methods for applying and reading constraints. If you remember, one of the reasons why we need this API is to be able to enrich data with meta information. Constraints are such information. In the preceding example, we are applying a constraint called Length (the plugin ID) with some arbitrary parameters expected by that constraint (in this case a maximum length but also a minimum would work). Having applied this constraint,we are essentially saying that this piece of string data is only valid if it's shorter than 20 characters. We can use this, like so:

/** @var TypedDataInterface $data */
$data = \Drupal::typedDataManager()->create($definition, 'my value that is too long');
$violations = $data->validate();

DataType plugins have a validate() method on them which uses the validation service to validate their underlying data definition against any of the constraints applied to it. The result is an instance of ConstraintViolationList iterator that contains a ConstraintViolationInterface instance for each validation failure. In the preceding example, we should have a violation from which we can get some information like so:

/** @var ConstraintViolationInterface $violation */
foreach ($violations as $violation) {
$message = $violation->getMessage();
$value = $violation->getInvalidValue();
$path = $violation->getPropertyPath();
}

The $message is the error message that comes from the failing constraint, the $value is the actual incorrect value, and the $path is a string representation of the hierarchical path down to the value that has failed. If you remember our license plate example or the content entity fields, TypedData can be nested, which means you can have all sorts of values at different levels. In our previous example, the $path is, however, going to be "" (an empty string) because the data definition has only one level.

Let's revisit our license plate example and see how such a constraint would work there. Imagine we wanted to add a similar constraint to the state code definition:

$state_code_definition = DataDefinition::create('string');
$state_code_definition->addConstraint('Length', array('max' => 2));
// The rest of the set up code we saw earlier.

/** @var Map $plate */
$plate = \Drupal::typedDataManager()->create($plate_definition, ['state' => 'NYC', 'number' => '405-307']);
$violations = $plate->validate();

If you look closely, I instantiated the plate with a state code longer than two characters. Now, if we ask our individual violations for the property path, we get state, because that is what we called the state definition property within the bigger map definition.

Finally, let's see an example of validating constraints on entities. First of all, we can run the validate() method on an entire entity which will then use its TypedData wrapper (EntityAdapter) to run a validation on all the fields on the entity + any of the entity level constraints. The latter can be added via the EntityType plugin definition. For example, the Comment entity type has this bit:

*    constraints = {
* "CommentName" = {}
* }

This means that the constraint plugin ID is CommentName and it takes no parameters (since the braces are empty). We can even add constraints to entity types that do not belong to us by implementing hook_entity_type_alter(), for example:

function my_module_entity_type_alter(array &$entity_types) {
/** @var ContentEntityType $node */
$node = $entity_types['node'];
$node->addConstraint('ConstraintPluginID', ['option']);
}

Going one level below and knowing that content entity fields are built on top of the TypedData API, it follows that all those levels can have constraints. We can add the constraints regularly to the field definitions or in the case of either fields that are not "ours" or configurable fields, we can use hooks to add constraints. Using hook_entity_base_field_info_alter() , we can add constraints to base fields while with hook_entity_bundle_field_info_alter(), we can add constraints to configurable fields (and overridden base fields). Let's see an example of how we can add constraints to the Node ID field:

function my_module_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
if ($entity_type->id() === 'node') {
/** @var BaseFieldDefinition $nid */
$nid = $fields['nid'];
$nid->addPropertyConstraints('value', ['Range' => ['mn' => 5, 'max' => 10]]);
}
}

As you can see, we are still just working with data definitions. One thing to note, however, is that when it comes to base fields and configurable fields (which are lists of items), we also have the addPropertyConstraints() method available. This simply makes sure that whatever constraint you are adding is targeted towards the actual items in the list (specifying which property), rather than the entire list as it would have happened we had used the main addConstraint() API. Another difference with this method is that constraints get wrapped into a ComplexDataConstraint plugin. However, you don't have to worry too much about that, just be aware when you see it.

We can even inspect the constraints found on a data definition object. For example, this is how we can read the constraints found on the Node ID field:

$nid = $node->get('nid');
$constraints = $nid->getConstraints();
$item_constraints = $nid->getItemDefinition()->getConstraints();

Where the getConstraints() method returns an array of constraint plugin instances. Now let’s see, though, how we can validate entities:

$nid = $node->get('nid');
$node_violations = $node->validate();
$nid_list_violations = $nid->validate();
$nid_item_violations = $nid->get(0)->validate();

The entity level validate() method returns an instance of EntityConstraintViolationList which is a more specific version of the ConstraintViolationList we talked about earlier. The latter is, however, returned by the validate() method of the other cases given in the following. But for all, inside we have a collection of ConstraintViolationInterface instances from which we can learn some things.

The entity level validation goes through all the fields and validates them; this means that is where we will get most violations (if that's the case). Next, the list will contain violations of any of the items in the list while the item will contain only the violation on that individual item in the list. The property path is something interesting to observe the following is the result of calling getPropertyPath() on a violation found in all three of the resulting violation lists preceding:

nid.0.value
0.value
value

As you can see, this reflects the TypedData hierarchy. When we validate the entire entity, it gives us a property path all the way down to the value--field name -> delta (position in the list) -> property name. Once we validate the field, we already know what field we are validating so that is omitted. And the same goes for the individual item (we know also the delta of the item).

A word of warning about base fields that can be overridden per bundle such as the Node title field. As I mentioned earlier, the base definition for these fields use an instance of BaseFieldOverride, which allows certain changes to be made to the definition via the UI. In this respect, they are very close to configurable fields. The "problem" with this is that, if we tried to apply a constraint like we just did with the nid to, say, the Node title field, we wouldn't have gotten any violations when validating. This is because the validator performs the validation on the BaseFieldOverride definition rather than the BaseFieldDefinition.

This is no problem, though, as we can use hook_entity_bundle_field_info_alter() and do the same thing as done before which will then apply the constraint to the overridden definition. In doing so, we can also account for the bundle we want this applied to. This is the same way to apply constraints to a configurable field you create in the UI.