Drupal 8 Module Development

Transcription

Drupal 8 Module DevelopmentBuild and customize Drupal 8 modules and extensionsefficientlyDaniel SiposBIRMINGHAM - MUMBAI

Drupal 8 Module DevelopmentCopyright 2017 Packt PublishingAll rights reserved. No part of this book may be reproduced, stored in a retrieval system, ortransmitted in any form or by any means, without the prior written permission of thepublisher, except in the case of brief quotations embedded in critical articles or reviews.Every effort has been made in the preparation of this book to ensure the accuracy of theinformation presented. However, the information contained in this book is sold withoutwarranty, either express or implied. Neither the author, nor Packt Publishing, and itsdealers and distributors will be held liable for any damages caused or alleged to be causeddirectly or indirectly by this book.Packt Publishing has endeavored to provide trademark information about all of thecompanies and products mentioned in this book by the appropriate use of capitals.However, Packt Publishing cannot guarantee the accuracy of this information.First published: October 2017Production reference: 1251017Published by Packt Publishing Ltd.Livery Place35 Livery StreetBirminghamB3 2PB, UK.ISBN 978-1-78216-877-5www.packtpub.com

CreditsAuthorDaniel SiposCopy EditorDhanya BaburajReviewersTodd ZebertTracy Charles SmithProject CoordinatorRitika ManojCommissioning EditorAmarabha BanerjeeProofreaderSafis EditingAcquisition EditorNigel FernandesIndexerRekha NairContent Development EditorAditi GourGraphicsJason MonteiroTechnical EditorDiksha WakodeProduction CoordinatorShantanu Zagade

About the AuthorDaniel Sipos is a senior web developer specializing in Drupal. He has been working withDrupal sites since version 6 and started, like many others, as a site builder. He's a selftaught programmer with many years of experience in working professionally on complexDrupal 7 and 8 projects. In his spare time, he runs webomelette.com, a Drupal websitewhere he writes technical articles, tips, and techniques related to Drupal development.

About the ReviewersTodd Zebert has been involved with Drupal since shortly after the launch of version 6. Heis a full stack web developer, is proficient in a variety of technologies, and is currently alead web developer for Miles. He has also been a technical reviewer for the Packt booksDeveloping with Drush and Drupal 8 Development Cookbook, and the related video seriesDrupal 8 Development Solutions.He's a frequent presenter at conferences on Drupal, JavaScript, and frontend technologies.He has a technology blog at Medium.Todd has a diverse background in technology, including infrastructure, networkengineering, project management, and IT leadership. His experience with web developmentstarted shortly after the release of the original Mosaic graphical web browser, withSHTML/CGI and Perl.Todd is an entrepreneur and is involved with the Los Angeles start-up community. He's abeliever in volunteering, open sourcing, the Maker movement, and contributing back. He'salso an advocate for STEAM (Science, Technology, Engineering, Art, and Math) education.I'd like to thank the Drupal community, especially the Los Angeles Drupal group.Finally, I'd like to thank my teen son with whom I get to share my interest intechnology and science , often while doing Maker-ish things together, withmicrocontrollers and other electronics.

Tracy Charles Smith began working with computers at the age of 10 years. His backgroundincludes network support, web development, customer service, project management, andfinancial management.His entrepreneurial spirit is a key component to his success in interacting with clients andteam members on business and user-experience related technology solutions. In fact, heused that passion to found his own technology-consulting firm called Alpha Geek Tech,LLC. He also served as the technology director for Quiddities Dev. Inc., in Santa Cruz, CA,before moving back to the DC area to join Phase2 in 2010 as a senior developer. Tracy nowworks as a senior project manager at Phase2, supporting growth and support clientsin government and private enterprise. His diverse development background complementshis project management skills.Tracy was also the lead programmer and architect for 12seconds.tv in 2007 (a videomessaging platform), which leveraged Drupal. He also authored Drupal Intranets withOpen Atrium.He earned a BS in computer information systems and business administration fromWingate University.

www.PacktPub.comFor support files and downloads related to your book, please visit www.PacktPub.com. Didyou know that Packt offers eBook versions of every book published, with PDF and ePubfiles available? You can upgrade to the eBook version at www.PacktPub.com and as a printbook customer, you are entitled to a discount on the eBook copy. Get in touch with us atservice@packtpub.com for more details.At www.PacktPub.com, you can also read a collection of free technical articles, sign up for arange of free newsletters and receive exclusive discounts and offers on Packt books andeBooks.https:/ / www. packtpub.com/maptGet the most in-demand software skills with Mapt. Mapt gives you full access to all Packtbooks and video courses, as well as industry-leading tools to help you plan your personaldevelopment and advance your career.Why subscribe?Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Customer FeedbackThanks for purchasing this Packt book. At Packt, quality is at the heart of our editorialprocess. To help us improve, please leave us an honest review on this book's Amazon pageat www.amazon.in/dp/178216877X.If you'd like to join our team of regular reviewers, you can email us atcustomerreviews@packtpub.com. We award our regular reviewers with free eBooks andvideos in exchange for their valuable feedback. Help us be relentless in improving ourproducts!

Table of ContentsPrefaceChapter 1: Developing for Drupal 8Introducing Drupal (for developers)Developing for Drupal 8Technologies that drive DrupalPHPDatabases and MySQLThe web serverHTML, CSS, and JavaScriptDrupal architectureDrupal core, modules, and themesHooks, plugins, and eventsServices and the dependency injection containerFrom request to responseDrupal's major igurationPluginsThe theme systemCachingOther subsystemsTools for developing in DrupalVersion controlComposerThe API site and coding standardsThe developer (Devel) moduleDrush (the Drupal shell)Drupal ConsoleDeveloper settingsSummaryChapter 2: Creating Your First ModuleCreating a moduleYour first hook 81919202121212222222323242425262729

Route and controllerThe routeRoute variablesNamespacesThe ControllerServicesWhat is a service?The HelloWorldSalutation serviceTagged servicesUsing services in Drupal 8Injecting the service into our ControllerThe formAltering formsCustom submit handlersRendering formsService dependenciesBlocksOur first block pluginBlock configurationWorking with linksThe URLThe linkWhich way to link?Event Dispatcher and redirectsRedirecting from a ControllerRedirecting from a subscriberDispatching eventsSummaryChapter 3: Logging and 758595960646768LoggingThe Drupal 8 logging theoryOur own logger channelOur own loggerLogging for Hello WorldLogging summaryMail APIThe theory of the Mail APIImplementing hook mail()Sending emailsAltering someone else's emailsCustom mail plugins[ ii ]697071727375767677788182

The mail pluginUsing mail plugins8385868788909293TokensThe Token APIUsing tokensDefining new tokensToken summarySummaryChapter 4: Theming94Business logic versus presentation logicTwigTheme hooksTheme hook suggestionsRender arraysThe structure of a render array#type#theme#markupThe render pipelineAssets and librariesLibrariesAttaching librariesCommon theme hooksListsLinksTablesAttributesTheming our Hello World moduleSummaryChapter 5: Menus and Menu 12113114119120The menu systemMenusMenu links120121121122122123123124124125Multiple types of menu linksLocal tasksLocal actionsContextual linksMenuLink treesMenu link tree manipulatorsMenu active trail[ iii ]

Rendering menusWorking with menu linksDefining menu linksWorking with menu linksDefining local tasksDefining local actionsDefining contextual linksSummary125128128129130132132136Chapter 6: Data Modeling and StorageDifferent types of data storageState APITempstorePrivateTempStoreA note about anonymous usersSharedTempStoreTempstore conclusionUserDataConfigurationIntroductionWhat is configuration used for?Managing configurationDifferent types of configurationConfiguration storageSchemaOverridesGlobal overridesModule overridesLanguage overridesPriorityInteracting with simple configurationEntitiesContent versus configuration entity typesEntity type pluginsIdentifiersBundlesDatabase tablesEntity keysLinksEntity translationEntity revisionsConfiguration exportHandlers[ iv 168

3183184184186187192193194196197202202Configuration entity fieldsContent entity fieldsBase fieldsConfigurable fieldsField storageEntity types summaryTypedDataWhy?What?The low-level APIDataType pluginsData definitionsContent entitiesTypedData summaryInteracting with the Entity APIQuerying and loading entitiesBuilding queriesLoading entitiesReading entitiesManipulating entitiesCreating entitiesRendering content entitiesPseudo-fieldsContent entity validationValidation summarySummaryChapter 7: Your Own Custom Entity and Plugin TypesCustom content entity typeCustom plugin typeCustom configuration entity typeThe Importer pluginContent entity bundlesDrush commandSummary203204218224236241251256Chapter 8: The Database API257The Schema APIRunning queriesSelect queries258261262263Handling the result[v]

More complex select queriesRange queries264265266269270270271272274277PagersInsert queriesUpdate queriesDelete queriesTransactionsQuery altersUpdate hooksSummaryChapter 9: Custom Fields279Field typeField widgetField formatterField settingsUsing as a base fieldSummary281291299304306308Chapter 10: Access Control309Introduction to the Drupal access systemRoles and permissions under the hoodDefining permissionsChecking the user credentialsRoute accessCustom route accessStatic approachService approachProgrammatically checking access on routesBonus - dynamic route options for access controlCSRF protection on routesAltering routesEntity accessInjecting services into Entity handlersEntity access hooksField accessEntity access in routesNode access grantsBlock accessSummaryChapter 11: 36338339340348350351[ vi ]

IntroductionCacheability metadataCache tagsCache contextsMax-ageUsing the cache metadataPlaceholders and lazy buildingLazy buildersUsing the Cache APICreating our own cache hapter 12: JavaScript and the Ajax API370Caching in block pluginsCaching access resultsJavaScript in DrupalDrupal behaviors371371372373375377377380387389Our libraryThe JavaScriptDrupal settingsAjax APIAjax linksAjax in formsStates (Form) systemSummaryChapter 13: Internationalization and LanguagesIntroductionLanguageContent TranslationConfiguration TranslationInterface TranslationInternationalizationContent entities and the Translation APISummary390391391392392393394398399Chapter 14: Batches, Queues, and Cron401Batch powered update hooksBatch operationsCreating the batchBatch operations402404404406[ vii ]

CronQueuesIntroduction to the Queue APICron based queueProcessing a queue programmaticallyLock APISummaryChapter 15: Views411413413414417419422423Entities in ViewsExposing custom data to ViewsViews dataViews fieldsViews relationshipsViews sorts and filtersViews argumentsAltering Views dataCustom Views fieldField configurationCustom Views filterCustom Views argumentViews themingViews hooksSummaryChapter 16: Working with Files and ImagesThe filesystemStream wrappersManaged versus unmanaged filesUsing the File and Image fieldsWorking with managed filesAttaching managed files to entitiesHelpful functions for dealing with managed filesManaged file uploadsManaged file form elementEntity CRUD hooksManaged file usage serviceProcessing the CSV fileOur own stream wrapperWorking with unmanaged filesPrivate file systemImages[ viii 51453454455457457459460462464465468471481481485

Image toolkitsImage stylesRendering imagesSummary485486487489Chapter 17: Automated Testing490Testing methodologies in Drupal 8PHPUnitRegistering testsUnit testsMocked dependenciesKernel testsTeamCleaner testCsvImporter testFunctional testsConfiguration for functional testsHello World page testHello World form testFunctional JavaScript testsTime testCsvImporter testSummaryChapter 18: Drupal 8 522527529Cross-Site Scripting (XSS)Sanitization methods in Drupal 8Double escapingSQL InjectionCross-Site Request Forgery (CSRF)SummaryIndex529530531532533534535[ ix ]

PrefaceDrupal 8 is a powerful web-based content management system (CMS) that can be used tobuild anything from simple websites to powerful applications. While it is useful out of thebox, it is designed with developers in mind.The purpose of this book is to talk about the most common ways a Drupal 8 website can beextended to provide new functionality. In doing so, the book will cover a number ofextension points, but also illustrate many subsystems and APIs that can help you model,structure, and wire your business requirements.Alongside the obligatory theoretical explanations, it will use a practical, example-basedapproach in order to break down complex topics and make them easier to understand. So,join me on this journey to discover exactly how powerful Drupal 8 actually is.What this book coversChapter 1, Developing for Drupal 8, provides an introduction to module development inDrupal 8. In doing so, it introduces the reader to the various subsystems and outlines therequirements for running a Drupal 8 application.Chapter 2, Creating Your First Module, gets the ball rolling by creating the first Drupal 8module of the book. Its main focus is to explore the most common things moduledevelopers need to know from the get-go.Chapter 3, Logging and Mailing, is about the tools available for doing something every web-based application does and/or should be doing, that is, sending emails and logging events.Chapter 4, Theming, presents the theme system from a module developer's perspective inDrupal 8.Chapter 5, Menus and Menu Links, explores the world of menus in Drupal 8 and shows howto programmatically create and work with menu links.Chapter 6, Data Modeling and Storage, looks at the various types of storage available inDrupal 8, from the state system to configuration and entities.

PrefaceChapter 7, Your Own Custom Entity and Plugin Types, takes a hands-on approach creating acustom configuration and content entity type, as well as custom plugin type to wire up apractical functional example.Chapter 8, The Database API, presents the database abstraction layer and how we can workdirectly with data stored in custom tables.Chapter 9, Custom Fields, exemplifies the creation of the three plugins necessary for creatinga custom field that can be used on a Drupal 8 content entity type.Chapter 10, Access Control, explores the world of access restrictions in Drupal 8, from rolesand permissions to route and entity access checks.Chapter 11, Caching, looks at the various cache mechanisms available for moduledevelopers to improve the performance of their functionality.Chapter 12, JavaScript and the AJAX API, introduces module developers to the specificitiesof writing JavaScript in Drupal 8, as well as the powerful AJAX system, which can be usedto build advanced interactions.Chapter 13, Internationalization and Languages, deals with the practices Drupal 8 moduledevelopers need to observe in order to ensure that the application can be properlytranslated.Chapter 14, Batches, Queues, and Cron, explores the various ways module developers canstructure their data processing tasks in a reliable way.Chapter 15, Views, looks at the various ways module developers can programmaticallyinteract with Views and even expose their own data to them.Chapter 16, Working with Files and Images, explores the various file and image APIs thatallow module developers to store, track, and manage files in Drupal 8.Chapter 17, Automated Testing, explores the various types of automated test moduledevelopers can write for their Drupal 8 applications to ensure stable and resilient code.What you need for this bookReaders don't need much to follow along with this book. A local environment setup capableof installing and running Drupal 8 (preferably with Composer) should suffice.[2]

PrefaceWho this book is forThe primary target of this book is Drupal 7 developers who want to learn how to writemodules and do development in Drupal 8. It is also intended for Drupal site builders whohave basic object-oriented programming skills, as well as PHP programmers without thatmuch Drupal experience.A little bit of Symfony experience is helpful but not mandatory.ConventionsIn this book, you will find a number of text styles that distinguish between different kindsof information. Here are some examples of these styles and an explanation of their meaning.Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Just assignthe names of the layers you want to activate to the admin/reports/dblog environmentvariable."A block of code is set as follows:hello world.logger.channel.hello world:parent: logger.channel basearguments: ['hello world']New terms and important words are shown in bold. Words that you see on the screen, forexample, in menus or dialog boxes, appear in the text like this: "Users can now reach thispage from the module administration page by clicking on the Help link for each individualmodule that has this hook implemented."Warnings or important notes appear in a box like this.Tips and tricks appear like this.[3]

PrefaceReader feedbackFeedback from our readers is always welcome. Let us know what you think about thisbook-what you liked or disliked. Reader feedback is important for us as it helps us developtitles that you will really get the most out of.To send us general feedback, simply e-mail feedback@packtpub.com, and mention thebook's title in the subject of your message.If there is a topic that you have expertise in and you are interested in either writing orcontributing to a book, see our author guide at www.packtpub.com/authors.Customer supportNow that you are the proud owner of a Packt book, we have a number of things to help youto get the most from your purchase.Downloading the example codeYou can download the example code files for this book from your account at http:/ / www.packtpub. com. If you purchased this book elsewhere, you can visit http:/ / www. packtpub.com/ support and register to have the files e-mailed directly to you.You can download the code files by following these steps:1.2.3.4.5.6.7.Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.You can also download the code files by clicking on the Code Files button on the book'swebpage at the Packt Publishing website. This page can be accessed by entering the book'sname in the Search box. Please note that you need to be logged in to your Packt account.[4]

PrefaceOnce the file is downloaded, please make sure that you unzip or extract the folder using thelatest version of:WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for LinuxThe code bundle for the book is also hosted on GitHub at https:/ / github. com/PacktPublishing/ Drupal- 8- Module- Development. We also have other code bundles fromour rich catalog of books and videos available at https:/ / github. com/ PacktPublishing/ .Check them out!Downloading the color images of this bookWe also provide you with a PDF file that has color images of the screenshots/diagrams usedin this book. The color images will help you better understand the changes in the output.You can download this file from https:/ / www. packtpub. com/ sites/ default/ files/downloads/ Drupal8ModuleDevelopment ColorImages. pdf.ErrataAlthough we have taken every care to ensure the accuracy of our content, mistakes dohappen. If you find a mistake in one of our books-maybe a mistake in the text or the codewe would be grateful if you could report this to us. By doing so, you can save other readersfrom frustration and help us improve subsequent versions of this book. If you find anyerrata, please report them by visiting http:/ / www. packtpub. com/ submit- errata, selectingyour book, clicking on the Errata Submission Form link, and entering the details of yourerrata. Once your errata are verified, your submission will be accepted and the errata willbe uploaded to our website or added to any list of existing errata under the Errata section ofthat title.To view the previously submitted errata, go to https:/ / www. packtpub. com/ books/content/ support and enter the name of the book in the search field. The requiredinformation will appear under the Errata section.[5]

PrefacePiracyPiracy of copyrighted material on the Internet is an ongoing problem across all media. AtPackt, we take the protection of our copyright and licenses very seriously. If you comeacross any illegal copies of our works in any form on the Internet, please provide us withthe location address or website name immediately so that we can pursue a remedy.Please contact us at copyright@packtpub.com with a link to the suspected piratedmaterial.We appreciate your help in protecting our authors and our ability to bring you valuablecontent.QuestionsIf you have a problem with any aspect of this book, you can contact usat questions@packtpub.com, and we will do our best to address the problem.[6]

1Developing for Drupal 8Drupal is a web-based Content Management System (CMS). While it is useful out of thebox, it is designed with developers in mind. The purpose of this book is to explain howDrupal can be extended in many ways and for many purposes. To this end, the version wewill use will be the latest one at the time of writing this book--Drupal 8.2. In this book, wewill cover a wide range of development topics. We'll discuss how to create a Drupal 8module, and as we go through the chapters, many concepts and tips that will help youbuild what you need will be introduced. The goal is not only to explain how things workbut also to go through some examples to demonstrate them. Since no book can containeverything, I hope that after reading this book, you'll be able to expand on this knowledgeon your own using the resources I reference and by looking into the Drupal code yourself.As helpful as such a book can be for learning any kind of software development, if youreally want to progress, you will need to apply the knowledge you learned and explore thesource code yourself. Only by doing this you will be able to understand complex systemswith many dependencies and layers.This chapter introduces the terminology, tools, and processes for developing Drupal 8.While subsequent chapters focus on code, this chapter focuses on concepts. We'll talk aboutthe architecture of Drupal and how you can hook into Drupal at strategic places to extend itfor accomplishing new tasks.The following are the major topics we will be covering in this chapter:An introduction to Drupal developmentDrupal 8 architectureThe major subsystemsTools for developing in DrupalBy the end of this chapter, you will understand the architectural aspects of Drupal and beready to start writing code.

Developing for Drupal 8Introducing Drupal (for developers)Out of the box, Drupal performs all of the standard functions of a web-based contentmanagement system:Visitors can view published information on the site; navigate through menus,view listings, and individual pages; and so onUsers can create accounts and leave commentsAdministrators can manage the site configuration and control the permissionslevels of usersEditors can create, preview, and then publish content when it is readyContent can be syndicated to RSS, where feed readers can pick up new articles asthey are publishedWith several built-in themes, even the look and feel of the site can be changedeasilyWith Drupal 8, the scope of what a site builder can do has greatly increased. Coremultilingual capabilities make it much easier to configure the site to use multiple languages,creating content listings a few clicks away out of the box, and content management, ingeneral, has greatly improved.Developing for Drupal 8As fantastic as these features are, they will certainly not satisfy the needs of all users. Tothat end, Drupal's capabilities can be easily extended with modules, themes, andinstallation profiles. Take a look at Drupal's main website, (http:/ / drupal. org), and youwill find thousands of modules that provide new features and thousands of themes thattransform the look and feel of the site.The fact that almost all aspects of Drupal's behavior can be intercepted and transformedthrough the module and theme mechanisms has led many to claim that Drupal isn't just aCMS, but a Content Management Framework (CMF) capable of being re-tooled to specificneeds and functional requirements. This is particularly the case with Drupal 8--the latestversion of Drupal and the focus of this book--as great progress has been made on theextensibility front too.[8]

Developing for Drupal 8Establishing whether Drupal is rightly called a CMS or CMF is beyond our purpose here,but it is certain that Drupal's most tremendous asset is its extensibility. Want to use adirectory server for authentication? There's a Drupal module for that. Want to export datato Comma-Separated Version (CSV) files? There are several modules for that (dependingon what data you want to export). Interested in Facebook support, integration with Twitter,or adding a Share This button? Yup, there are modules for all of these too--all of which areavailable at Drupal.org and provided by developers like you.Want to integrate Drupal with that custom tool you wrote to solve your special businessneeds? There may not be a module for that, but with a little bit of code, you can write yourown. In fact, that is the subject of this book--providing you with the knowledge and tools toachieve your own goals.In summary, the purpose of this book is to get you ramped up (as quickly as possible) forDrupal 8 module development. As we move chapter by chapter, we will cover the APIs andtools that you will use to build custom Drupal sites, and we won't stick to theory. Mostchapters provide working, practically oriented example code designed to show you how toimplement the concepts we talk about. We will follow Drupal coding conventions andutilize Drupal design patterns in an effort to illustrate the correct way to write code withinthe Drupal development context.While I certainly can't write the exact code to meet your needs, my hope is that the codementioned in these chapters can serve as a foundation for your bigger and betterapplications.So let's get started with a few preliminary matters.Technologies that drive DrupalInstalling Drupal 8 in the traditional way is documented both on Drupal.org and in theINSTALL.txt file found inside the /core folder of the installation, so I won't go into ithere. I will, however, mention that a better way of installing Drupal 8, especially fordevelopers, is using the accepted Composer template for Drupal 8 projects found onGitHub (https:/ / github. com/ drupal- composer/ drupal- project). However, theinstructions for setting up your site are well covered there as well.Instead, let's talk a bit about the technologies that power (or are needed by) Drupal 8.[9]

Developing for Drupal 8PHPDrupal is written in the PHP programming language. PHP is a widely supported,multiplatform, and web-centric scripting language. Since Drupal is written in PHP, thisbook will largely feature code written in PHP, albeit with Drupal standard practices beingkept in mind.It is very important to note that the minimum version of PHP required for Drupal 8 to run(and install via Composer) is 5.5.9. Moreover, since the current version of PHP (at the timeof writing this book) is PHP 7, I personally recommend that you run Drupal 8. It's best tostart off right.Regarding the style of PHP, a very important change compared to Drupal 7 is the heavy useof object-oriented code and design patterns. Granted, many procedural style approachesremain throughout the Drupal 8 code base, but the use of a good number of popularexternal libraries (such as Symfony components) has pushed the overall Drupal code to bemore modern. For this reason, it is also quite important that you have at least some basicunderstanding of object-oriented programming (OOP), especially PHP related, if you wantto do Drupal 8 development.Databases and MySQLIn the past, Drupal has supported two databases--MySQL and PostgreSQL. Drupal 7 and 8have moved beyond this. Drupal now uses the powerful PHP Data Objects (PDO) librarythat is standard in PHP 5/7. This library is an abstrac

Drupal sites since version 6 and started, like many others, as a site builder. He's a self-taught programmer with many years of experience in working professionally on complex Drupal 7 and 8 projects. In his spare time, he runs . webomelette.com, a Drupal website where he writes technical articles, tips, and techniques related to Drupal .