Rearchitecting For Drupal 8

Transcription

Rearchitecting for Drupal 8By frobWelcome to the re-architecting for Drupal 8 talkYou should be able to follow along by visiting the link below.

In case you are wonderingYou are here

Prolog -- You are here in the sessionWhy look at Drupal 8Custom LMS Drupal 7 architectureFeaturesContent strategyModules usedProlog -- Youare here in the sessionCustomdevelopmentWhy look at Drupal 8Considerations Building with Drupal 8Custom LMS Drupal 7 architectureArchitectural differencesFeaturesContentstrategyUI ChangesModules usedModule availabilityCustom derationsDrupalto8Architectural differencesUI ChangesModule availabilitySpecifically What needs to changechange

Hello My Name Is FrankHellois FrankRobertAndersonI ammyanameFather,andTechnologyEnthusiast.Web development since high schoolBeenworkingin Drupalisprofessionallyjust github)shy of 10Onlinemy namefrob (IRC,ford.o,years.On Twitter I am @frobdfasI have worked almost exclusively in the Education nline you can find me as frobI work for Clarity InnovationsIRCgithubdrupal.orgTwitter frobdfasblogwebsiteI work for Clarity Innovations.Inc.

Clarity Innovations is a professional services firm based inPortland, Oregon focused on providing K-12 and highereducation technology consulting to non-profits, schools, andcorporations.Our 25 employees combine leading edge technology anddesign skills with direct experience in the classroom anduniversity.We develop solutions for our clients including strategicconsulting, professional development and content creation,and engineering solutions such as apps, web apps, andwebsites to help improve the process and practice ofteaching and learning.

Why do this?WhyThe big question is D8 or D7, this is a question that I haveto ask myself every time I am asked to do an estimate.How do we pick which version of Drupal to use?Let me GET THIS OUT THE WAY I will not be going overhard numbers for building with one version over the other. Iwill give you the only answer that I can give knowing what Iknow about your project's requirements. IT DEPENDS.

I create with Drupal 7.I want to create with Drupal 8.I want to know the differences betweencreating with Drupal 7 vs 8.I would like to know how I can leverage thenew features of Drupal 8 in complicatedinformation systems.I create with Drupal 7.I want to create with Drupal 8.I want to know the differences between creating with Drupal7 vs 8.I would like to know how I can leverage the new features ofDrupal 8 in complicated information systems.

Lets go from:

To:

Custom LMS ArchitectureLearning Management SystemAn LMS is software that allows for the organization and delivery of courses ortraining programs.LMS ArchitectureNeed to deal with some prerequisite information so we allunderstand the goals of the project that I used as my testbed.What is an LMS? An LMS is a Learning ManagementSystem.It is software that allows for the organization and delivery ofcourses or training programs. If you have usedbuildamodule.com or drupalize.me then you have used aLMS.

Traditional LMSCurriculum or Lesson planUnit or ional LMS is based on a traditional course or lessonplanCurriculum or Lesson planCollection of Units or ModulesCollection of Lesson/Project/Assessment/Mini-lessons

Our custom LMS is structuredModule - MenuSegments - Nodes or Content TypeComponents - Paragraphs ItemsOur custom LMS is structured asModule - MenuSegments - NodesComponents - Paragraphs ItemsLesson plan equivalents are built with select fields on thesegment nodes.

Basic Drupal ArchitectureIn order to make sure we are all on the same page movingforward I need to talk about some basic Drupal Architecture.If this is review for some of you, I am sorry for theunskippable tutorial level.

Basic Drupal Content ArchitectureEntitiesFieldsVariablesBasic Drupal ArchitectureIn order to make sure we are all on the same page movingforward I need to talk about some basic Drupal Architecture.If this is review for some of you, I am sorry for theunskippable tutorial level.Don't worry I will mostly just be talking about Entities, Fields,and Variables.

EntitiesEntities are things in Drupal; things do not have to be nodes.Entities are things in Drupal, starting in drupal 7 we gotcontent entities.In Drupal 6 custom things where typically nodes or totallycustomIn Drupal 7 the entity-field system brought the CCK into corewithout making everything a nodeDrupal 8 has a fully fledged entity api which is derived fromthe capabilities of the contrib entity api module for drupal 7.Users, Taxonomy Terms, and Nodes, are all Entities

Bundles and FieldsA bundle is a collection of fields instanceson an EntityA field instance is a place for complex datain a Entity BundleAnEntity can haveBundles toallow for multiplecollectionsA propertyis simplestoragefor Entitylevelof fields instances on a single type of entity.dataField instances are unique to that bundle.An Entity has properties which span all bundles.created datenode statuswho created are all propertiesA field instance is a place for complex data in a EntityBundleA property is simple storage for Entity level data

PropertiesProperties are linked to an Entity, such as Node. Fields are linked to the Bundle, suchas Content Type.Properties are stored on the entity's table and fields are stored in their own table.Properties are linked to an Entity, such as Node. Fields arelinked to the Bundle, such as Content Type.Properties are stored on the entity's table and fields arestored in their own table.

VariablesVariables are what Drupal 7 provides for configuration --when it isn't a custom table.Variables are what Drupal 7 provides for configuration -when it isn't a custom table.

LMS FeaturesSupport Backwards Design philosophySite FeaturesTraditional LMSCollection of Curriculum or Lesson plansCollection of Unit or ModuleCollection of Lesson/Project/Assessment/Mini-lessonsCurriculum Designer will often use a Backwards DesignphilosophyStarts Standards/Topical they with to teach

Goals of lesson planningEngageExploreExplainElaborateEvaluateUsing the 5 e's as the goals of lesson planningEngageExploreExplainElaborateEvaluate

LMS Lesson GoalsTeachingApplicationThus Goals for Lesson Plan FeaturesAssessmentActivate Prior knowledgeModeling or TeachingPracticeApplicationAssessmentOur custom LMS is structured asmodule - menusegments - nodescomponents - paragraphs items

Drupal 7 Modules UsedModules UsedFrank's list of modern site building toolsI gave a talk on modern Drupal 7 development at a meetupin Portland last year, and I am not going to go into greatdetail here. I wrote a blog post about it and if you would likemore details I suggest you look there.I will go over the modules that this site used (in its corefunctionality), what they do.Later I will go over how they relate to Drupal 8.Remember when building a site that the output that drupalgive us is always a suggestion. The important part of sitebuilding is giving the content team everything they need,you can leave it up to the developers and themers to makesure that the content gets displayed properly.

ParagraphsParagraphs allows us to create collections of fields. Each collection type is its ownbundle and can have its own fields.Paragraphs -- If you are familiar with field collection thenthis module functions very similarly, with the main exceptionof the user being able to pick the bundle or paragraph typewhen creating content.

Entity FormNamed eForm in Drupal 8. Allows the use of the field api to create webform and havethe submissions be entities.Entity Form -- In Drupal 8 this module was renamed toeform. The cool part of this module is that it allows us to usethe field api to create webforms. Unlike the webformmodule, the form submissions are entities. This gives usflexibility use in views or displaying them with multiple viewmodes.

EvaSolves the problem of putting views into entities as pseudo-fields.EVA -- Entity View Attachment. Allows us to embed viewsinto fields. Handy for things like Taxonomy term views oranywhere an ID can be used as an argument in a view.

FlagThis module allow users to flag things. Largest use is probably the "Flag this asinappropriate" functionality.Flags -- This module allow users to flag entities. Largest useis probably the "Flag this as inappropriate" functionality.The last two modules don't have much to do with this siteper-se but they are fantastic modules that will really help asite-builder.

CoffeeCoffee works like Unity for Ubuntu or Spotlight search for Mac, or the Start Menu inWindows. Just start typing and a list of options will be presented. Pick the option andit will take you there.Coffee -- Speed up your Drupal navigation by typing whereyou want to go. Much like unity for Ubuntu or Spotlight forMac or Start for Windows, this module allows us to ziparound our site's admin interface with ease.

SpeedboxesCheck more than one box with a click and drag mechanic.Speedboxes -- Allows us to check multiple checkboxes atthe same time. Super useful for setting up permissions.

A word on BlocksThis is not a block heavy siteBeanIt works mostly as an app with the blocks only really beingused to place active menus on the screen.Bean is an acronym that stands for:This is mainly because there are not many reusable piecesto the site. If it isn't a page level thing then it really isn't aBlock Entities Aren't Nodes.part of this site.This site doesn't use blocks, but when I use blocks I buildthem with BEAN.Bean gives us all the functionality of building content typeswith nodes except with blocks instead.I normally add a content view for beans at/admin/content/blocks and I disable the default drupal blockmanagement stuff, with the exception of block placement.because that is still necessary.But again, this site didn't make heavy use of blocks.

I don't always use blocks, but when I do I use the beanmodule

LMS Content StrategyArguably, the most important part of a site.Content StrategyNow thats out of the way we can talk about the site'scontent strategy.

13 paragraphs types and 1 content typeThree where interactiveText responseCheckbox listDrag and DropIn the end our site had 13 paragraphs item bundles for 1content typeThree where interactiveText responseCheckbox listDrag and Drop

Text response

Checkbox list

Drag and Drop

The rest are multimedia/content.Everything can be combined to form larger whole components.Four where used for custom inter and intra modulenavigationThe rest where videos, image, and text.all can be combined to form larger whole components.

Linking the EntityForm Submission to the Paragraph itemEntityParagraph TypeMachine Nametext responseLinking the EntityForm Submission to the Paragraph item,EntityFormTypeitem hadtext responseeach interactiveparagraphsa corresponding entityform with an entity reference back to the paragraphs itemthat displayed the form. We used the paragraphs item'sbundle machine name to pick the bundle of the EntityFormto display.We put this all together, using Drupal's ingenious renderarray system that doesn't care if it is displaying a form, orcontent, or anything themable, we where able to HULKsmash the entityforms into the paragraphs item displays andsave any users response and know what they whereresponding to and who was responding to it.

EvaluationSharing via Flags on the paragraphs itemsWe also had to allow for self evaluation. Our client wantedusers to be able to share their responses and learn from theresponses of others. So we used flags that let the usersshare their responses, in turn if they share their responsethen they see their peer's responses and then they can edittheir old response and save a new one.Our initial expectation was that we would have to build outall the content in a spreadsheet and at one point I wasbuilding a migration to import all the content from a CSV.Choosing the Paragraphs module gave our content editorsan interface that allowed them to build the content in the siteas we where adding functionality.

Custom DevelopmentCustom DevelopmentThe meat of how we are putting this together is in thehook entity view alter implementation and thehook form alter implementation.

Pass the build to custom functionif (!empty( build['#bundle'])) { bundle build['#bundle'];if (function exists(" component { bundle} alter")) {// We need to pass build in an array in order to trick ca// into passing the build by reference.call user func(" component { bundle} alter", array(& buil}}Pass the build to custom function.Remember we used the bundle type machine names to addthe correct entity form types? We do that withcall user func which calls a function based on the name wegive it. We check beforehand if the function exists, this wayit is extensible without having to modify too much existingcode. So if we want to add another interactive element wecan do so without modifying anything to do with our currentinteractive elements.

Text response callback/*** Implements custom component TYPE alter().*/function component text response alter(& build) {if (isset( build[0]['#entity']) && !empty( build[0]['#entity'Text response callbackmodule load include('inc', 'entityform', 'entityform.admin'In the case of the text response this checks for a valid entity form name 'text submissions';callback and runs this code to include the entity form. component id build[0]['#entity']- item id;Then in the form alter we change the actual form options or entity build[0]['#entity'];the text area label to use the correct text. form get entityform(entityform empty load( entity form naThings get complicated at this point, because ajax. form['field component submission']['#attributes']['class'We have to ajaxify each of the paragraph items. I'm not// . OtherStuff.here because that would just begoing togo into code form['field text response submission']['#attributes']['classboring, and it is better documented elsewhere. form rendered drupal render( form);An interestingthing about saving a response is, only after it build[0][] array(is savedcan we make the paragraphs item sharable. Thenafter it is shared only then can we make show the sharedresponses. All of these things required heavy developmentfor Drupal 7, and will likely also require lots of custom workfor Drupal 8 too.

Considerations Building a LMS with Drupal 8Architectural differencesUI ChangesModule availabilitySpecifically What needs to changeArchitectureCustom DevelopmentConsiderationswith Drupal 8ContentBuildingstrategyArchitectural differencesUI ChangesModule availabilitySpecifically What needs to changeArchitectureCustom DevelopmentContent strategy

General Drupal 8 ConsiderationsSetup the devel moduleIt is now cache rebuildingModulescannotbe disabledGeneralDrupal8 Considerationsdevel kint debugging DO NOT USE KUMO it doesn't workEnableDeveloper Modeon real objectsBewareof onlinesourcesno longer cacheclear nowcache rebuildingNo more module disable, uninstall or dieEnable developer modehttps://www.drupal.org/node/2598914Nice thing is that there is lots of information availablealready for Drupal8 the problem is that there is lots of badinformation available for Drupal 8. Check your sources anddo not expect everything you read to actually work. Evend.o documentation can be out of date. poll module example.

and isn't easy to export and sync and the placement of theblock is configuration and is easy to sync. This can lead toembarrassing deployment gaffs. Where the placement of ablock that doesn't exist is possible. Here is a good articleabout avoiding 8-websiteDisplay ModesContent View ModesIf you usedthe entity view modesmodules or display suiteArchitecturalDifferencesto provide view modes for content types and such, then youshould already be familiar with this. If you don't know whatConfiguration Entitiesview modes are, they are ways for providing different waysto display thesame content. So for a node we could have aSemanticVersioningteaser or a full view mode or a grid view mode. BasicallyBlocksanything that the design called for. These existed for contentin Drupal7 but they required a contrib module such as entityViewModesview modes or the display suite module to configure themNewfieldtypeswithoutcode.Drupal(entity8 gave areference,full fledged UI link,to work with.Form View Modestelephone)All that stuff I said about being able to display content indifferent configurable ways now also applies to forms withDrupal 8. So, as an example, let say you have a verycomplicated user registration form because your clientwants to collect a bunch of information about the user, butnone of it is required. Now you can create a new simplifiedform for adding users. You can do this in the UI in Drupal 8.New field types (entity reference, link, telephone)

Things to google (many have been backported to Drupal 7)ComposersupportThingsto google(many have been backported to Drupal 7)Composer updatesupport (Navbar in Drupal 7)ToolbarToolbar update (Navbar in Drupal 7)ResponsiveImage Styles (Picture ModuleResponsive Image Styles (Picture Module in Drupal 7)inDrupalFileEntities 7)RESTfulapiFileEntitiesExperimental Core ModulesRESTfulapiContent ModerationWorkflowsExperimentalCore ModulesField LayoutContentModerationMigrate Drupal UIetc.Place Blocks - outside inSwitching to semver should allow for smaller backwardcompatible changes.Testing infrastructure should ensure backward compatiblechanges are backward compatible. The DA infrastructureteam has made this a reality.

UI ChangesGood News! Not much has changed significantly in the UI. I guess that could be badnew too.This is going to be brief, mainly because the UI changes areminimal.

OperationsNew Drop down thingy for selecting what we are doing to a thing.One change is Operations now go in a drop down with themaybe most common one first? Really I don't know how thatwas chosen so if someone here does know please tell meafterward.

Form Display SettingsMultiple entity form settings on the Manage form display page, this includes fieldwidget settings.Another change you will find between D7 and D8 I havealready hinted at with the Form View. If you have a alternatenode form then you will find the option for editing that formview in "Manage Form Display" section. This also meansthat controls for the form widgets are configured on the formview display settings and not the "Manage Fields" page.Mange Fields is now entirely about the field and its storage.

Good news about learning curvesGood news, there are fewer changes for site builders whoare coming from Drupal 7 to worry about. Bad news is forsomeone coming from not Drupal the perceived Drupallearning curve could be intimidating.

Module AvailabilityModule AvailabilityLets acknowledge the elephant in the room.

module works well enough for this experiment, but if thiswhere a full client project we would have to explore someoptions.Find an alternativeCustom Entities are an optionComment moduleContact module extrasRelation moduleBig Didn'tproblembring this module up in the modules used because wedidn't use it, butthis issupporteda really cool module.This moduleEntityFormis noton Drupal8has the ability to supplant the functionality of flag andFindan alternativeorganic groups. It adds the concept of entity endpointswhichCustomallow Entityus to make fieldable relations between entities.In the example of this LMS that entity would have all theComment modulefields for the response, an endpoint for the paragraphs item(renamedfor Drupal 8), and an endpointContactparagraphmodulerevisionextrasfor the user.moduleIRelationhave used thismodule for saving user state in js apps andforkeepingof users completionfor resourcesFundthetrackdevelopmentof astatusstablereleaseincustom Professional Development portals.Fund the development of a stable releaseWhile I do encourage finding alternatives, at this state inDrupal 8 development I would encourage us to choose thefinal option because frankly aside from the comment modulenone of the above options are any more stable than eformand more importantly Drupal 8 needs more stability incontrib.

Second problemParagraphs doesn't want me to referenceparagraphsIt is possible, but requires use of theEXPERIMENTAL field widget.In thiscase the problem wasn't theSecondproblemParagraphsdoesn'twantme toreference paragraphsmodule butmyownunfamiliarityand overItconfidence.is possible, but Therequiresuse of theEXPERIMENTALanswerwasstaring mefieldinwidget. The main reason this is EXPERIMENTAL is that thethe face.modules is not mean to be used to reuseparagraphscontent, that is more of a function of blocks. I spent moretime on this than I would have liked, due to some of Drupal8's UI changes that I didn't fully understand. But it turned outto be a non-problem.In this case the problem wasn't the module but my ownunfamiliarity and over confidence. The answer was staringme in the face.

So we do have an elephant, but it is just a baby elephant.

What needs to change?not muchSpecifically What needs to changeThis site works more like a an app than a traditional site,this means we have slightly different expectations whenchoosing a Framework.Not MuchDrupal was chosen for its scaleability, strong user centric orpermissions based content model, high quality contribspace, and familiarity. As I said before I have been doingdrupal professionally for close to 10 years, so I am veryfamiliar with the project, community, and workflow. However,I am constantly looking into other technology and I havebuilt things with other tech when Drupal isn't the bestchoice, so this isn't a statement coming from the island.Drupal 8 has lots of new Features but the biggest advanceshave been in underlying architecture (with the content/configentity system) and development workflow (with the switch toSemantic Versioning).

Architecture & Content StrategyMostly the sameSame FeaturesSame ModulesSame ArchitectureSame StrategyArchitecturally the site remains the sameThe site has the same features and the same modules areavailable to provide us with the same architecture andcontent strategy.It won't always be like this. But if you put the work intomaking sure you have a good content strategy in the firstplace it will be less likely that you will have to completely rearchitect a site when you move platforms. This is whycontent strategy is important.

Custom DevelopmentBiggest ChangesThe largest change is the addition of developing a stablerelease for whatever we use for the response saving.

Custom DevelopmentThis is where the largest changes where made.Custom developmentThis is where the largest changes where made, but maybenot where it was expected.

Not MuchWe still use hook entity view alterWe still use hook form alterIn Drupal 7 we accomplished the HULK SMASH part, wherewe smash the form from the entity form into the display ofthe paragraphs item, with a hook entity view alterimplementation coupled with a hook form alterimplementation. In Drupal 8 with its Object OrientedArchitecture I was able to accomplish it in the exact sameway.

"But Wait" you say, "Drupal 8 is OOP we aren't supposed toput stuff into the .module file anymore. That is just there fordecoration!"Oh no, the joy of modifying aspects of the program withhooks is not gone in D8. Hooks are good things, and eventhough Drupal is want to change things with new versionand add modern development practices to Drupal, Drupalalso isn't going to ditch what is likely the most flexiblepattern of php development just because it stepped in someOOP.

Okay,reallylots to makeThe Object OrientedArchitectureis designedcommon things easier.For example.But all good!When building this with Drupal 7, we had to reimplementparts of the form builder from the entity forms module inorder to display entity forms programatically. This was likelydue to the incomplete nature of the entity api in Drupal 7.In Drupal 8 the entity api is far more flushed out. We still useEntity Field Queries to get the EntityForm Submission forthe current user and the current paragraph revision, but thistime Drupal has an api for creating the empty EntityFormsubmission object if the user has never submitted. And ithas an interface for building forms for Entities, new or old.Thus we can get a form for a new entity in the same way weget the form for the old entity, with all the right fields filled in.

Drupal 8 version:// This creates a new eform submission. eform submission \Drupal::entityTypeManager()- getStorage('eform submission')- create(['type' 'multiple choice question']);// This loads an existing eform submission. submitted eform \Drupal::entityTypeManager()- getStorage('eform submission')- load(2);// Either way we build the form with a call to the entity.form bu form \Drupal::service('entity.form builder')- getForm( submitted eform);// Then we appendrenderarray.To build aitnew toentity,thethis couldbe a node, build[] form;eform submission, or comment, We user theDrupal::entityTypeManager class and call the create methodor to load an existing one we use the same class with theload method and the entity id.Then we user the entity form builder service to build theform for the entity. I tested this with nodes as well. It is thesame generic interface for all content entities.

No more Drupal 7 non-existent entity apiDrupal 8 has intelligent use of OOP thatmakes site building easierOver 100 lines of code is reduced to under10

No more Drupal 7 non-existent entity apiDrupal 8 has intelligent use of OOP that makes site buildingeasierOver 100 lines of code is reduced to under 10Mind Blown

Why look at Drupal 8Custom LMS Drupal 7 architectureConsiderations Building a with Drupal 8Architectural differencesUI ChangesModule availabilitySpecifically What needs to changeConclusion -- Achievement unlocked

When are sprints?April 24-27: Sprint Lounge at Baltimore Convention CenterApril 28: Sprint Day - General Sprints, Mentored Core Sprint, First-Time SprinterWorkshop at Baltimore Convention CenterWe also provide a 24-hour Sprinter Lounge that opens on April 24th at 7:00pm andwill close on Thursday, April 27th at midnight. The Sprinter Lounge will be located atthe Hilton Baltimore (401 West Pratt Street) in room Peale A-C.are sprintsBased on communityWhenfeedbackand input from the Sprint Leads, we understand theApril 24-27: Sprint Lounge at Baltimore Convention Centerneed for 'shorter sprints with greater support', and as a result will not be hostingApril 28: Sprint Day - General Sprints, Mentored CoreExtendedWeekendthis DrupalCon.Sprint, First-TimeSprinter SprintsWorkshop atat BaltimoreConvention CenterWe also provide a 24-hour Sprinter Lounge that opens onApril 24th at 7:00pm and will close on Thursday, April 27that midnight. The Sprinter Lounge will be located at theHilton Baltimore (401 West Pratt Street) in room Peale A-C.

Don't forget to give me feedbacknode/17242Help us get better.

Drupal 8 has a fully fledged entity api which is derived from the capabilities of the contrib entity api module for drupal 7. Users, Taxonomy Terms, and Nodes, are all Entities . Entity Form Entity Form -- In Drupal 8 this module was renamed to eform. The cool part of this module is that it allows us to use