LATEST FROM OUR BLOG

Take your daily dose of (only) relevant news, useful tips and tricks and valuable how to's on using the latest web technologies shaping the digital landscape. We're here to do all the necessary information sifting for you, so you don't have to, to provide you with content that will help you anticipate the emerging trends about to influence the web.

Here Is How You Create Drupal 8 Comments Programmatically
Since flexibility’s already one of Drupal’s emblematic features, it was about time they did something about their quite rudimentary commenting system, right? Well, get ready to embrace the upgraded Drupal 8 comments, which are far more than just some basic settings in a node type.   So, What Makes the Drupal 8 Comments far More Tempting?   1. They’re set up as fields That’s right, comments are no longer fieldable, full-featured entities. They’re still entities but set up as fields. What’s in this for you? You get to choose where exactly on the page your comments will get displayed and you’re no longer restricted to add them to content only (now they can practically “show up” anywhere the fields can)   2. Comments have their own fields Can you believe this! Not only that they’re set up as fields in Drupal 8, but you can also add a set of fields to each comment.   3. They’re of several types Now, this is just a big step ahead of the standard, one-type-only comments in Drupal 7!   For instance, now you can add comments to taxonomy terms, to users, blocks, contact messages, content and even to… other comments.   Just imagine: you’re the admin of a social networking site! You can leave private notes to your users, they, as well, can leave their own private suggestions for you, while users can also leave comments on your public-facing website, too.   Here’s another quick example of Drupal 8 commenting system’s flexibility: if you want to add comments to a content type you simply add a field “Comments” on the “Manage Fields” page and voila: there’s your comments field!   Still, when it comes to this new upgrade in Drupal’s commenting system, we must be fair and point out an issue that still needs improvement: in Drupal 8 multiple types of comments don’t come with multiple individual permissions, as well. This means that anyone who’s granted permission to post a certain type of comment can practically post any type of comment on the website.   4. Comments have their own area now  You get to scroll through the “Unapproved Comments” and the “Published Comments” lists.    5. The “Recent Comments” block is in Views  Remember how frustrating it was realizing that you could not edit your “recent comments in” D7? Things have changed now: the “recent comments” block has been moved to “Views” in Drupal 8 and is available by default.   And Here’s How You Can Create Your Comments in Drupal 8 Basically, the whole process comes down to 2 major steps:   You create a comment entity in code.   Then you save it.   Here’s how the code will/should look like:   // To create a new comment entity, we'll need `use` (import) the Comment class. use Drupal\comment\Entity\Comment;   // The function name doesn't matter. Just put the the function body where you need it. function my_modules_function_or_method() {     // First, we need to create an array of field values for the comment.   $values = [       // These values are for the entity that you're creating the comment for, not the comment itself.     'entity_type' => 'node',            // required.     'entity_id'   => 42,                // required.     'field_name'  => 'comment',         // required.       // The user id of the comment's 'author'. Use 0 for the anonymous user.     'uid' => 0,                         // required.       // These values are for the comment itself.     'comment_type' => 'comment',        // required.     'subject' => 'My Awesome Comment',  // required.     'comment_body' => $body,            // optional.       // Whether the comment is 'approved' or not.     'status' => 1,                      // optional. Defaults to 0.   ];     // This will create an actual comment entity out of our field values.   $comment = Comment::create($values);     // Last, we actually need to save the comment to the database.   $comment->save(); }   Now let’s have a closer look at each one of these fields:   entity_type: it’s the entity that you attach your comment to (a node, for instance)   entity_id: it’s the id that you’ll attach the comment to (it would have to be a nid in case it’s a node that you’ll attach it to)   field_name: this field is the one for the entity that you’re attaching your comment to   Practically, what all these 3 first fields do is let Drupal know what entity it should attach your comment to. This whole “flexibility” laid at your feet, that you get to juggle with multiple comment fields of the same entity and the fact that those comments’ fields can use multiple types of comments, themselves, is just part of the upgrades added to the commenting system.   uid: informs Drupal which user wrote a specific comment   comment_type: the type of comment you want to create (you know, who’ve already talked about how in Drupal 8 you have several types of comments to juggle with). The default comment will be just comment   subject: just like a node comes with a title field, so does a comment come with a “subject field” in Drupal 8   comment_body: is provided by default and you can remove it, just like you can remove any other one of the fields   status: if you don’t want, as admin, to be asked to approve each comment before it goes live, set it to 1   field_foodbar: although it does not show in the above example of code, we still wanted to show you that you’re free to add custom fields if you want to. Simply use the field’s machine name and give it a default value.    So, what do you think about Drupal’s new commenting system?   Do you find the improvements made to the way you can create comments to be a big step ahead, contributing to Drupal’s overall flexibility or do you consider that there are many other possible upgrades (feel free to name them) that its developers should have focused on? ... Read more
Adrian Ababei / Nov 16'2016
How to Manage Your Drupal 8 Configuration Workflow with Git: A 4-Step Guide
  Wouldn't you agree that managing configuration is vital in the life-cycle of a multi-person project? Well, its importance used to be, until recently, proportional to its main dreaded feature, that of being a major nuisance for web development teams: highly important configuration settings were missing, leading to major inconsistencies when it came to configuration handling, commits, made by the members of the team, resulting in conflicts etc.   Have no fear, Drupal 8 Configuration Management System Is Here!   That's right, Drupal's latest version comes to relieve your team of all the stress that parallel configuring actions might lead to. Upgraded with tempting configuration management tools, it allows developers to export/import all the configuration settings they will have performed to/from code.   Moreover (and this is the very best part of Drupal 8 configuration management system), Git allows the members of your team to put configuration under version control, thus keeping track of it (the ultimate goal of any configuration management endeavor, after all!).    What does this mean?    1. that you'll have a history of all configuration changes   2. that you can compare different configuration states   Setup   Do you already have a a development version Drupal 8 installed on your system? Is Drush available there, as well?    Well, before you go any further we have a "warning”/piece of advice for you:   Make sure not to put the files/folders that came with Drupal specific setup (e.g. sites/default/settings.php, sites/default/files/, sites/default/files/css/ etc.) into your repository! How to avoid that? Just make a clone of the "example.gitignore" file (that you get with Drupal) and place it in .gitignore, then adjust it  to your website's specific needs, thus keeping the files directory and setting.php unexposed to the risk of getting versioned.   Initiate The New Repository   Once you've downloaded your Drupal 8 version, simply initialize and register a new repository along with it:   $ git init   $ git add .   $ git commit -m "Initial Commit: Drupal 8.x Code base"     Great! Now consider this: Drupal 8 configuration management system only works on distinct instances of the same website! So, what solution do you have? You simply clone it: import the database of the website to be cloned in the other environment!   Next,  add your remote repository clone URL:    $ git remote add origin REMOTE_CLONE_URL   Push the commit up to GitHub:    $ git push -u origin master     ... and voila: you have your new functional Drupal 8 website!     Now let's start “playing” with the Configuration Management System that Drupal 8's developers "spoil" us with, easing our work by giving us full control over all the changes we (along with out teammates) will apply to our site later on during its development process!   Go ahead and export your configuration   After you've set up the needed configuration, it's time to export it. How? Use the command line for exporting the site configuration to a new folder (config/site):    $ mkdir config   $ drush config-export --destination=config/site   Next, commit and push the configuration to the repository.   There, you've just created your own "safe", the one that stores priceless website information!   Practically, you now have a valuable screenshot of how your website looked like when you installed it. From now on, dare and perform any configuration you'd like, knowing that at any time you can just roll back your site to precisely this state: the one right after its installation!      Time To Import Your Configuration   For importing your configuration from the config/site, rely on this "powerful" command:   # Import the configuration from the repository   $ drush config-import --source=config/site     Why powerful? Because it instantly overwrites the current configuration!      It's after you've exported your configuration that you can merge it with those of other members of your web development team:   add and commit the configuration to Git use Git pull, then focus on fixing any commits conflicts that might arise   At this point, we have another warning/helpful piece of advice for you: don't rely exclusively on Git for the configuration's merging part. Be sure to check whether the result of the merge is correct, whether it makes sense!     If everything will have gone smoothly with your configuration's importing process, you can go ahead and push it to the remote repository.      Valuable Pieces of Advice   1. Always export configuration first and pull the configuration changes run by your collaborators secondly! Why? Because Git doesn't recognize the changes will have have applied to your database until you actually export them!   2. Always import first, push secondly! This means that it's always safe to import the configuration and only then to push it to the remote repository, avoiding the risk of breaking the site (in case you're dealing with a broken configuration)   3. Accompany each import with a database dump, thus granting your team a backup in case anything goes wrong   4. Deal with this thought: you can't rely on Git for everything! Don't loosen your vigilance, especially when you're a member of a larger team working on the same project! ... Read more
Adrian Ababei / Nov 14'2016
Not All Content Is King in Drupal 8: Mobile, Global Content Is
  Can you handle all the ... power that Drupal 8 is about to lay in your very hands, whether you're a developer, a marketer/content editor or a user/end-user? Will you take the dare to set yourself free from the desktop and from any regional or language limitations and to step into the... future?     If you answered “No”, then... good luck with implementing your digital “vision”, you'll need it!   But if you've answered “I'm not sure” or “what does this fancy utopia even mean?”, you'll definitely want to read the following true facts about Drupal 8.   Empower yourself with helpful information about what is described as “the world’s leading digital experience platform that helps you manage and deliver web content across channels and devices."     Shifting to a Mobile First Mentality   “If I were to start Drupal from scratch today, I'd build it for mobile experiences first and desktop experience second”, Dries Buytaert.   Need we add more to this suggestive quote?   We're not going to beat around the bush stating the obvious (that users have started to rely more on their mobile devices for... getting themselves informed, entertained or for buying/booking certain goods/services).   Instead, what we'd like to point out to you is precisely those upgrades that the visionary team behind Drupal 8 have upgraded it with:   its was conceived primarily for mobile devices (and only secondarily for desktops), therefore its structurally made to support responsive design it sets itself apart from the (now) rudimentary belief of  “one size fits all” it comes upgraded with responsive image support (pictures adapt automatically to any device's specific viewport size, without affecting the page's loading time) it turns managing content on mobile devices into a highly intuitive process (its admin has been significantly adapted for mobile) it empowers site builders with new responsive themes, mobile-adapted ones, thus enabling them to get... creative and craft great Drupal 8 websites that look appealing on mobile devices       Drupal 8 Encourages You to Go... Global    In other words, Drupal 8 supports your “taking over the world” vision (only as a visionary entrepreneur of the digital era, of course...).   Since, now you should start envisioning user-friendliness as “user friendliness on a global scale”, what Drupal 8 does is that it... empowers you (sorry, we couldn't find a more appropriate word to describe Drupal 8's main... “mission”) with all the cool tools you'll need for going... international:   Content Translation module: it helps you communicate in your users' own languages, therefore to easily translate your site' content Interface Translation module: it helps you, as a site developer, by giving you the chance to... build sites in your own language (you get to actually translate the blocks, the toolbars, the menus etc.) Language module: it... empowers you (there, we did it again!) to determine specific languages (that your site will support) for your target visitors     Usability+Accessibility= A New Winner in the Drupal vs Wordpress Showdown   We didn't find it necessary to add customization to the above formula, for this is already THE feature (along with the related flexibility) that Drupal has become famous for among developers belonging to both teams (the Drupal enthusiasts and the Wordpress fans for life).     Now let's sum it up:    Drupal 8 websites/apps can be accessed anywhere on the globe    Drupal 8 websites/apps can be accessed on practically any type of device      OK, so we've cleared the accessibility issue out!   But what about usability, the ultimate goal that both Drupalers and Wordpress enthusiasts are craving for while their developers are striving to reach?   Let us check this ultimate goal off the list, as well:   Content Editors/Marketers Get More Power Than Ever   That's right, Drupal 8 is not just about easing the developers' work or about putting the user and the end user into the spotlight. It's also about empowering content marketers.   In this respect, here's how Drupal 8 will “lighten” up your work life, if you're a content marketer:   the integrated WYSIWYG editor, easing content authoring the on-page editor better preview uploading images with drag and drop modules (more of them) for monitoring your SEO-oriented activity  easy to integrate YOAST and Google Analytics   But What is in it for Drupal Website Developers?    Still, if Drupal 8 is focused on the end user more than all the previous Drupal versions and if it invests content marketers with so much power, it doesn't mean that... there's nothing in it for website builders, too.    We've kept “the best” for last, so to say...   So, if you're a Drupal website developer (or willing to become one), here's how Drupal 8's own visionary developers have decided to ease your work:   Rest API's PHP7 and we all know that this is a huge step forward, turning Drupal 8 into one of the most dynamic content management platforms out there You get to use it as a data source (you get to post data from the front end and output content as XML or JSON Hypertext Application Language JavaScript Automated Testing Customization is still... king with Drupal 8, too: you get to customize your admin tools, lists, views, determine the way your data gets displayed (and all that without having to write code) More fields for you to better structure your content     Now that Drupal 8 empowers you with accessibility, usability, mobile-first mentality and global-ready vision, all you need to bring in to the table is... your own share of innovation, creativity and... boldness and you can go ahead and craft the digital experiences of the future! ... Read more
Adrian Ababei / Nov 08'2016
Add Google Fonts to your Drupal 8 Theme
Adding Google Fonts to your Drupal 8 theme can be a bit more difficult than with Drupal 7. This is an example of how to install a font for every page of your website. Here is the method previously used to install Google Fonts on every page of the theme using Drupal 7: function MYTHEME_preprocess_html(&$variables) { // this function is deprecated in D8 drupal_add_css('//fonts.googleapis.com/css?family=Roboto+Condensed', array('group' => CSS_THEME)); }   But in Drupal 8 it’s completely different – we need to use the libraries method, which is a bit more complicated. First things first, we need to add a library in the last two lines of the theme.info.yml file. Remember that when adding the theme name you need to use all lower case for it to work properly. name: Test description: Test theme type: theme base theme: theme name core: 8.x libraries: - test/fonts   After that, a library file needs to be created – the library is defined as themeName/libraryName in the .info.yml. file. The library file is named themeName.libraries.yml. This file opens with a declaration of libraryName: fonts: license: name: SIL Open Font License, 1.1 url: https://goo.gl/UpQhAK /> css: theme: //fonts.googleapis.com/css?family=Roboto+Condensed: { type: external } css/myStyles.css: {}   The YML file will work even without a license section but it’s a good idea to mention it as well. The font’s URL has the HTTP: removed so that it’s agnostic to secure-or-not connections at runtime. If everything is done properly you should be able to view the adjusted lines of code. All you need to do now is implement the font into your CSS through a rule in the myStyles.css file located in your css folder.   ... Read more
Adrian Ababei / May 10'2016
Drupal Development and Twig: What Are the Main Benefits for Replacing the PHPTemplate with Twig?
Drupal development is becoming an increasingly popular choice for developers all around the world. This has sparked the interest for upgrades for this technology. Drupal used to work with the PHPTemplate engine which sought to separate the presentation layer from the logic layer. Recently Drupal development took one step further by replacing PHPTemplate with Twig, the latter being more secure and powerful.   Twig & Drupal Development With Drupal 7, text previously submitted by the user needed the check_plain() function in order to prevent the ever-present vulnerability of cross site scripting or XSS. If a theme’s output wasn’t sanitized, it was a huge security risk. Autoescaping was recently accepted into Drupal 8 as well, which made Drupal development much safer. PHP functions are also removed from templates, in line with separation of concerns. Here is the new Drupal development mark-up: Old: <?php print render($content); ?>   New: {{ content }} The new syntax makes Drupal development faster and cleaner, a clear separation between presentation and logic with an added security boost. Twig offers many other benefits including that of inheritance – this has been called one of Twig’s biggest assets.   By integrating Drupal development with Twig, the need to copy and paste the parent theme template files into custom templates is eliminated. Twig limits the amount of template code and files you need to organize within your theme. {% extends "themes/sub_bartik/templates/node.html.twig" %} This is quite similar to PHP’s „include function” – it allows you to create hookable, dynamic templates. But there’s another feature which makes Twig great: Twig blocks Parent file: {# This empty block allows child templates to insert markup into this place in the header without re-writing the entire template. #} {% block header_fields %} {% endblock %} New file: {# Override the header_fields block to put field_image there because this site needs it there. #} {% block header_fields %} {{ content.field_image }} {% endblock %}   With the use of Twig and Twig blocks, Drupal development will become much easier – this also makes Drupal websites much safer and powerful. ... Read more
Adrian Ababei / Oct 23'2015
10 Ways Drupal 8 Will Be More Secure
Security is very hard to bolt on to any software or product after it has been built. Building it into the core of the code helps to avoid mistakes, and thus the upcoming release of Drupal 8 tries to build in more security by default, while still being usable for developers and site builders. This list of 10 security improvements is not exhaustive - some are just a line or two to handle an edge case, and there are others I may have overlooked. I've contributed to a number of these improvements, but they reflect overall the community consensus as well as reactions to problems that required security releases for Drupal core or contributed modules in the past. For each point I've tried to include a link or two, such as the Drupal core change record, a documentation page, or a presentation that provides more information. Some of these may also be possible to back-port to Drupal 7, to benefit you even sooner. A "7.x back-port" link indicates that. For context on why these 10 improvements are important, I looked at past security advisories (SAs) as well as considering the kind of questions we get here at Acquia from companies considering adopting Drupal. In terms of past SAs, cross-site scripting (XSS) is the most commonly found vulnerability in Drupal core and contributed modules and themes. 1. Twig templates used for html generation This is probably first on the list of anyone you ask about Drupal 8 security. This is also one of the most popular features with themers.

 One security gain from this is that it enforces much stricter separation of business logic and presentation – this makes it easier to validate 3rd party themes or delegate pure presentation work. You can't run SQL queries or access the Drupal API from Twig. 


 

In addition, Drupal 8 enables Twig auto-escaping, which means that any string that has not specifically flagged as safe will be escaped using the PHP function htmlspecialchars() (e.g. the same as Drupal 7 check_plain()). Auto-escaping of variables will prevent many XSS vulnerabilities that are accidentally introduced in custom site themes and custom and contributed modules. That fact is why I ranked this as number one. XSS is the most frequent security vulnerability found in Drupal code. We don't have a lot of hard data, but based on past site audits we generally assume that 90% of site-specific vulnerabilities are in the custom theme.
 2. Removed PHP input filter and the use of PHP as a configuration import format OK, maybe this should have been number one. Drupal 8 does not include the PHP input format in core. In addition to encouraging best practices (managing code in a revision control system like git), this means that Drupal no longer makes it trivial to escalate an administrator login to being able to execute arbitrary PHP code or shell commands on the server. 
 For Drupal 7, importing something like a View required importing executable PHP code, and for certain custom block visibility settings, etc. you would need to enter a PHP snippet. These uses of evaluated PHP (exposing possible code execution vulnerabilities) are all gone – see the next point about configuration management.
 Now that we have covered the top two, the rest of the 10 are in rather arbitrary order. 3. Site configuration exportable, manageable as code, and versionable The Configuration Management Initiative (CMI) transformed how Drupal 8 manages things that would have been represented in Drupal 7 as PHP code. Things like Drupal variables or ctools exportables (e.g. exported Views).

 CMI uses YAML as the export and import format and the YAML files can be managed together with your code and checked into a revision control system (like git). 
 Why is this a security enhancement? Well, in addition to removing the use of PHP code as an import format (and hence possible code execution vulnerability), tracking configuration in code makes it much easier to have an auditable history of configuration changes. This will make Drupal more appealing and suitable for enterprises that need strict controls on configuration changes in place. In addition, configuration can be fully tested in development and then exactly replicated to production at the same time as any corresponding code changes (avoiding mistakes during manual configuration).
 Finally, it is possible to completely block configuration changes in production to force deployment of changes as code.
 4. User content entry and filtering improved While the integration of a WYSIWYG editor with Drupal core is a big usability improvement, extra care was taken that to mitigate poor practices that adding a WYSIWYG editor encouraged in past Drupal versions. In particular, users with access to the editor were often granted access to the full html text format, which effectively allowed them to execute XSS attacks on any other site user.

 To encourage the best practice of only allowing the use of the filtered HTML format, the Drupal 8 WYSIWYG editor configuration is integrated with the corresponding text filter. When a button is added to the active configuration, the corresponding HTML tag is added to the allowed list for the text filter.
 Drag a new button from the available to enabled section in the editor configuration: WYSIWYG editor configuration adding underline button The corresponding HTML tag (the U tag) is added to the allowed list: U tag is allowed in the filter An additional security improvement is that the core text filtering supports limiting users to using only images local to the site which helps prevent cross-site request forgery (CSRF) and other attacks or abuses using images. 5. Hardened user session and session ID handling There are three distinct improvements to session and session cookie handling. First, the security of session IDs has been greatly improved against exposure via database backups or SQL injection (7.x back-port ). Previously in Drupal, the session ID is stored and checked directly against the incoming session cookie from the browser. The risk from this is that the value from the database can be used to populate the cookie in the browser and thus assume the session and identity of any user who has a valid session in the database. In Drupal 8, the ID is hashed before storage, which prevents the database value from being used to assume a user's session, but the incoming value from the value is simply hashed in order to verify the value.
 Next, mixed-mode SSL session support was added to core to support sites that, for example, used contributed modules to serve the login page over SSL while other pages unencrypted. You will have to replace the session handling service if you really need this. This encourages serving your entire site over SSL (which is also a search engine ranking boost).

 The final change is that the leading “www.” is no longer stripped from the session cookie domain since that causes the session cookie to be sent to all subdomains (7.x back-port). 6. Automated CSRF token protection in route definitions Links (GET requests) that cause some destructive action or configuration change need to be protected from CSRF, usually with a user-specific token in the query string that is checked before carrying out the action. 

This change improves the developer experience and security by automating a process frequently forgotten or done incorrectly in contributed modules. In addition, centralizing the code makes it easier to audit and provide test coverage. Drupal 8 makes it easy. A developer merely needs to specify that a route (a system path in Drupal 7 terms) require a CSRF token. Here is an example of the YAML route definition for a protected link in Drupal 8 entity. entity.shortcut.link_delete_inline: path: '/admin/config/user-interface/shortcut/link/{shortcut}/delete-inline' defaults: _controller: 'Drupal\shortcut\Controller\ShortcutController::deleteShortcutLinkInline' requirements: _entity_access: 'shortcut.delete' _csrf_token: 'TRUE' Only the one line in the requirements: section needs to be added to protect shortcut deletion from CSRF. 7. Trusted host patterns enforced for requests Many Drupal sites will respond to a page request using an arbitrary host header sent to the correct IP address. This can lead to cache poisoning, bogus site emails, bogus password recovery links, and other problems with security implications. For earlier versions of Drupal, it can be a challenge to correctly configure the webserver for a single site that uses sites/default as its site directory to prevent these host header spoofing attacks. Drupal 8 ships with a simple facility to configure expected host patterns in settings.php and warns you in the site status report if it's not configured. 8. PDO MySQL limited to executing single statements If available, Drupal 8 will set a flag that limits PHP to sending only a single SQL statement at a time when using MySQL. This change would have reduced the severity of SA-CORE-2014-005 (a SQL injection vulnerability that was easily exploited by anonymous users) (7.x back-port)
. Getting this change into Drupal 8 meant I first had to contribute a small upstream change to the PHP language itself, and to the PDO MySQL library that is available in PHP versions 5.5.21 or 5.6.5 and greater. There is also a patch in progress to try to enforce this protection regardless of which specific database driver is being used. 9. Clickjacking protection enabled by default A small change, but Drupal 8 sends the X-Frame-Options: SAMEORIGIN header in all responses by default. This header is respected by most browsers and prevents the site from being served inside an iframe on another domain. This blocks so-called click-jacking attacks (e.g. forms or links on the site being presented in a disguised fashion on an attacker's site inside an iframe), as well as blocking the unauthorized re-use of site content via iframes. (7.x back-port). 10. Core JavaScript API Compatible with CSP Support for inline JavaScript was removed from the #attached property in the Drupal render API. In addition, the Drupal javascript settings variables are now added to the page as JSON data and loaded into a variable instead of being rendered as inline JavaScript. This was the last use of inline JavaScript by Drupal 8 core, and means that site builders can much more easily enable a strict content security policy (CSP) – a new web standard for communicating per-site restrictions to browsers and mitigating XSS and other vulnerabilities. A final note of caution: The substantial code reorganization and refactoring in Drupal 8 as well as the dependence on third party PHP components does present a certain added risk. The code reorganization may have introduced bugs that were missed by the existing core tests. The third party components themselves may have security vulnerabilities that affect Drupal, and at the very least, we need to track and stay up to date with them and fix our integration for any corresponding API changes. In order to try to mitigate the risk, the Drupal Association has been conducting the first Drupal security bug bounty that has been run for any version of Drupal core. This has uncovered several security bugs and means they will be fixed before Drupal 8 is released. - Source: https://goo.gl/i2CCxj ... Read more
Adrian Ababei / Oct 23'2015
Blog Placeholder
At OPTASY we’re big fans of Drupal. While we remain a technology agnostic firm and believe in matching organization needs with the best technology available, we believe Drupal is an excellent platform that addresses a wide range of web requirements. Now, with the recent beta version release of Drupal 8, the future of Drupal is incredibly bright. Drupal 8, which is currently in beta mode and slated for full production release sometime in 2015, represents a large-scale reimagining of the core Drupal application. The result of this grand effort is a much more cohesive, flexible and integrated platform on which to build websites of the future. Some folks have come to us and are already considering the move to Drupal 8 and are interested in becoming early adopters. However, before we get into specifics about Drupal 8, we want to highlight two key reasons we will likely continue to build on Drupal 7 for all of 2015 and into 2016: The true power of Drupal lies in the community modules that are available, and it will be at least 3-6 months until a critical mass have been upgraded and are production ready for Drupal 8. This timeline starts once Drupal 8 is released into production. In community development right now are a set of migration tools that should significantly ease the process of migrating from Drupal 7 to 8 at the appropriate time. This significantly reduces the reason to build on Drupal 8 out of the gate, and the majority of sites to start using 8 are likely to have been migrated from 7. We would not support Drupal 7 if it was not a best-in-class application. That said, in building websites on 7, we have spent much time over the years on activities such as turning off unneeded features, applying a group of our favorite modules to streamline and improve the admin interface, and tieing in an array of symbiotic third-party tools for caching and performance. While this knowledge is great for an agency that works with Drupal constantly, it can be harder for non-expert Drupal users to get up to speed. The inclusion of many strategies we use for Drupal 7 natively into Drupal 8 will be great for getting sites up to speed quickly. We have also written about some of our other Drupal implementation best practices which may be interesting to those looking for a more technical experience with Drupal. Drupal 8 Features We Love 1. Manage your site's content...from your phone. Anyone that’s ever administered a website knows that it’s best done while using a desktop or laptop. Much of the backend functionality simply doesn’t work, or doesn’t support mobile platforms. Enter Drupal 8, which is being built from the ground up with a focus on multi-device support. The core themes available for Drupal 8 will utilize responsive design, on both the front and back-end. Not only will visitors to your site have an optimized viewing experience for every device, your administrators will be able to manage the site from mobile devices as well. 2. Add new features to your live site with ease. Prior versions of Drupal store virtually all configuration settings in the Drupal database, alongside all site content (such as pages, menus, blocks, metadata and users). This approach greatly complicates deploying your updated site (e.g. code with new features) to your live site, as you can’t simply overwrite the live database without erasing your latest content and user activity in the process. In Drupal 7 we use the Features and Strongarm modules to build exportable packages of settings, Drupal 8 now stores these settings in files found in your library directory. This greatly simplifies deploying configuration changes such as new content types, fields or views from development to production. 3. Improved performance capabilities through modernization. As part of the overall transition to the Symfony framework, Drupal 8 offers an alternative to the unique "hook" system for attaching modules to Drupal core. Through the Symfony Event Dispatcher, application components can communicate with one another, allowing the system as a whole to run much more intelligently. What this means for the end user is that unlike the default with prior versions of Drupal, the system does not need to load every enabled module with each page request. And as many core Drupal hooks have been replaced, Drupal as an application is well on its way to potentially replacing hooks altogether in Drupal 9. 4. Integration capabilities significantly improved. Already one of the most flexible platforms when it comes to integrating with third-party applications, Drupal 8 takes the possibilities to an entirely different level. Using the new Rest & Serialization APIs, site builders will be able to output serialized data as JSON and XML from Drupal, almost as easily as they can normal HTML output. 5.  Take your website around the world. Drupal 7 supports multi-lingual functionality, but not at the level that Drupal 8 will. Imagine translating your site’s content to any one of the 110 different supported languages with a few clicks. You’ll be able to not only translate a page’s content for a specific language, but also build views and determine what blocks should appear for that language. Translation updates will also be pushed to the site automatically to make sure your site has the latest dictionary. Why We Love Drupal in General   1. Site management made easy with Drupal content types. One of the keys to getting the most benefit from a CMS lies in the separation of content from design and layout.  The greater extent to which you can isolate these two site components, the more your graphic designers and content authors/editors can be freed to do their jobs without interference from one another.  Drupal bakes this concept into its very core by making it quite easy to create numerous individual content types, each with its own collection of fields and possible field types.  Gone are the days where authors are presented a blank slate for each page via a single rich text area. With Drupal, your designers can easily ensure these fields get styled correctly and displayed in the right orientation, while authors are presented with simple fields to fill out and edit. 2. Scalability and flexibility galore. Drupal is one of the most flexible platforms on the market right now and allows virtually unlimited customization in the front-end, backend, and everything in-between. The key lies in the thousands of excellent off-the-shelf modules available at drupal.org. While some may require customization, they can be added on to core Drupal with relative ease. This ensures your site can grow and change as your organization does the same. 3. System administrator automation via Drush. Freely available for download and immediate use on all Drupal sites, Drush provides an awesome command-driven interface for managing Drupal.  Admin tasks that require many clicks and page refreshes are easily reduced to a single command. For example, we find Drush most useful in the creation of new user accounts (especially if you need to create many at once), generation of system backups, application of core and module updates, and migration of content from other systems. 4. Robust security and overall support options. Software companies typically have dozens, or at most hundreds of developers working on support, bug fixes, new features, integrations. The Drupal community comprises over 180,000 active contributors. This facilitates rapid advancement for Drupal and establishes a very large population of modules and integrations. ... Read more
Adrian Ababei / Feb 24'2015
Blog Placeholder
Wordpress to Drupal 8 migration setup Here’s an example of an existing WordPress site, which has registered users with comments, anonymous comments and an archive of previous postings with metadata (tags) that we will import. We’ll finish with this posting displayed in Drupal 8 version of the blog. The following tables in Wordpress are relevant to the migration: wp_posts (contains blog posts and pages) wp_comments (comments) wp_users (users) wp_terms (categories - taxonomy) We will started writing our migration module using Migration API (migrate) that comes packaged with D8 core. As usual in Drupal 8 module development, we had .info.yml, files, which uses the Symfony 2 YAML to map data types into an XML-like schema for easy migration from one environment to another, and traditional Drupal .module files. The only thing worth noting here is a dependency on the migrate module in our info.yml file. For each Entity migration (users, posts, comments) we created 2 more files: A YAML file containing ID, Source, Destination and Mapping (Process). Put this under MODULE_ROOT/config/install/ A Source Plugin used to fetch/process Wordpress data. Put this underMODULE_ROOT/src/Plugin/migrate/source/ Code breakdown Users Let start understanding things by migrating Users first. Here is the complete user YAML file for this migration. Let’s break it down: In this migrate.migration.users.yml file, ID, Source, Destination and Process (field mapping) are important keys.   id: users # Links this file with wordpress.migrate.yaml label: Wordpress Users migration_groups:   - Wordpress ID key is ‘users’ which has been referred in manifest_wordpress.yml and also in Source Plugin (User.php) as part of Annotation.   source:   plugin: users Source key is referring to Source Plugin (User.php) created by us to fetch Wordpress users data, which we will see shortly in detail.   destination:   plugin: entity:user Destination key is user entity as defined by Migration API.   process:   uid: id   name: user_login   pass: user_pass   mail: user_email   status:     -      plugin: default_value      default_value: 1   created:     -      plugin: callback      callable: strtotime      source: user_registered Process is key to mapping source (Wordpress) and destination (Drupal) fields. Some fields are mapped directly like ‘id’ with ‘sid’ while some fields are pre-processed by Migration API before being assigned to a destination field. For instance, ‘user_registered’ will be processed by PHP function strtotime() before it’s value gets assigned to destination field, because the target Drupal site must recognize those users as registered to associate their previous activity in WordPress with their Drupal activity on the new site. We can even write our own process plugins if required. Now let’s look at Source Plugin (Users.php) which has been used to fetch the Wordpress users data,   <?php /** * @file * Contains \Drupal\migrate_wordpress\Plugin\migrate\source\Users. */ namespace Drupal\migrate_wordpress\Plugin\migrate\source; use Drupal\migrate\Row; use Drupal\migrate\Plugin\SourceEntityInterface; use Drupal\migrate_drupal\Plugin\migrate\source\DrupalSqlBase; /** * Extracts users from Wordpress database. * * @MigrateSource( *   id = "users" * ) */ Remember the id field in the YAML file? The id field tells Drupal that this class should be used to process data for that migration set, taking the results of “users” in WordPress and adding them to a new table in the Drupal database, wp_users.   class Users extends DrupalSqlBase implements SourceEntityInterface {   /**    * {@inheritdoc}    */   public function query() {     return $this->select('wp_users', 'u')       ->fields('u', array_keys($this->userFields()));   } The query() method is used to fetch records from Wordpress database table (wp_users).     /**    * Returns the User fields to be migrated.    *    * @return array    *   Associative array having field name as key and description as value.    */   protected function userFields() {     $fields = array(       'id' => $this->t('User ID'),       'user_login' => $this->t('Username'),       'user_pass' => $this->t('Password'),       'user_email' => $this->t('Email address'),       'user_registered' => $this->t('Created time'),     );     return $fields;   }   /**    * {@inheritdoc}    */   public function fields() {     $fields = $this->userFields();   } userFields() method is called in query() and fields() methods. It contains the list of fields that describe a WordPress user along with their field descriptions.     /**    * {@inheritdoc}    */   public function bundleMigrationRequired() {     return false;   }   /**    * {@inheritdoc}    */   public function entityTypeId() {     return 'users';   }   /**    * {@inheritdoc}    */   public function getIds() {     return array(       'id' => array(         'type' => 'integer',         'alias' => 'u',       ),     );   } As we are also implementing an interface SourceEntityInterface, we need to define 2 more methods namelybundleMigrationRequired() and entityTypeId() to map user-generated content, such as postings and comments, to Drupal. The getIds() method is used to return the key field for this Entity. Posts The Posts Entity migration (YAML, Source Plugin) is quite similar to User Entity migration. There is one additional method prepareRow() defined in post migration source plugin. This method gets called for each row to do an additional processing of the source data.   public function prepareRow(Row $row) { $post_type = $row->getSourceProperty('post_type'); $type = $post_type == 'page' ? 'page' : 'article'; $row->setSourceProperty('type', $type); return parent::prepareRow($row); } In this method, we are first checking the post type of source data and based on that we set the ‘type’ property. As we have two types of posts in Wordpress (Pages, Blogs posts) we want to map them to two content types in Drupal (Basic page, Article). The ‘type’ property is available in the post-migration YAML file Process step, as discussed above, and we have mapped it to the Drupal content type field. Comments The Comments Entity migration is more or less similar to Users and Posts migration. There are some following additions in Comments migration YAML file which are quite interesting to know.   uid: -    plugin: skip_process_on_empty    source: user_id -    plugin: migration    migration: users 'comment_body/value': comment_content 'comment_body/format': 'basic_html' migration_dependencies: required:    - posts    - users Here we are using ‘skip_process_on_empty’ plugin which means skip the process if the source value is empty. As key fields can have different values in source and destination databases so we are using migration plugin to map ‘user_id’ field with ‘uid’ field. This will look for destination id in migration map tables for given source id (user_id). Next, the ‘comment_body’ field is a text field and made up of two fields in Drupal 8, so we must map the Wordpress ‘comment_content’ field to value field and mapping basic html to format field. Next we have defined comment migration dependencies to posts and users which means comments will be migrated once both posts and users are already migrated. Putting it all together Finally you can run the migration using 'migrate-manifest' drush command as below. Make sure to run this command in Drush 7.   drush migrate-manifest manifest_wordpress.yml --legacy-db-url=mysql://{dbuser}:{dbpass}@localhost/{dbname} The manifest_wordpress.yml is a YAML file which contains reference to IDs of each migration (users, posts, comments etc.).   # A Wordpress posts/users/comments migration, with dependencies. - posts - users - comments Finished: WordPress postings shown in Drupal ... Read more
Adrian Ababei / Feb 24'2015