Feed aggregator

ThinkShout: The Hidden Power of Documentation

Planet Drupal -

Anyone who works on team-based projects knows how handy good project documentation is, and how frustrating it can be when that documentation is out of date, incomplete, or just not there. But there are other benefits to good documentation aside from convenience, and a solid system for writing and maintaining documentation is the key.

Defining Documentation

Before we begin, we should be clear about what we mean when we say ‘Project Documentation’ (Docs for short). We’re referring to the information for team members (developers, designers, project managers, and engineers) who join a project at some point after initial development has begun, or even long after a project is complete, such as a maintenance team. This is different than User/Tech docs (how things work on a site), and Code docs (Comments, README files, etc.).

Good docs allow these team members to get up to speed on a project with a minimum of questions for existing or previous team members. In an ideal world, docs alone would suffice in getting someone set up and working on new features, bugfixes, or other project tasks.

Additional Benefits

The convenience of good docs is apparent to anyone who joins a project after it has begun, but consider some of the other benefits:

  • Junior developers will be able to reference docs, instilling confidence.
  • A team member leaving your company will not cause as much of a ‘knowledge drain’.
  • Consistent docs allow any team member to quickly jump in and out of projects as needed, providing project managers with additional flexibility in resource allocation.
  • Long-dormant projects can be resurrected quickly, even if none of the original team members are available.
  • Figuring out where a project’s code is, how to install it locally, how to make/commit changes to production, and tracking down the original wireframes, designs, and planning docs can take days if the original team members are not available. Good docs can cut this time to under an hour, or even minutes in some cases.
  • Docs that accompany open-source projects are especially useful in saving the end-user AND the maintainer’s time.
Location, Location, Location

Having your docs in one place, or in the same place on every project is the first step in making them easy to find - after all, what good are the docs if nobody can find them? ThinkShout uses GitHub for all of its projects, so we take advantage of the fact that every project on GitHub has a free Wiki. A link in the README.md to the wiki means everyone can find the docs in seconds.

A Solid Foundation

The keys to good docs are consistency, accuracy, and completeness:

Consistency

For our Wiki, we have a template we use for every project’s docs, so we don’t have to search for the information among 40 different documentation styles. Your project’s needs may differ, but this should be a good starting point (this is in Markdown):

## Current Status (Site Type / Status. Drupal, WordPress, under development, maintenance, etc...) ## Site Build Info * [Wireframes](URL) * [Budget](URL) * [Implementation overview](URL) * [Migration Spreadsheet](URL) * [Style Guide](URL) ## Build Team * Name (Team Lead) * Name (Back-end) * Name (Front-end) * Name (PM) * Name (Design/UX) ## Hosting * [Dev](URL) * [Test](URL) * [Live](URL) ## Issue Tracking [Redbooth Tasks](URL) ## Deploying Code Note: it is a good practice to run backups before deploying. `cd ~/projects/PROJECTAME;git pull;./scripts/deploy.sh` ## Installation Notes Clone into `projects` folder, install to `~/Sites/`: cd ~/projects git clone [email protected]:thinkshout/PROJECTNAME.git cd PROJECTNAME composer update ./scripts/build.sh ~/Sites/PROJECTNAME root root PROJECTNAME Download db and files from [production](production backup URL) Install the db by opening Sequel Pro, deleting the PROJECTNAME db, adding a new PROJECTNAME db, and importing the live db, then truncating all of the cache_* tables. Install the files by unzipping the file download and copying them to `~/Sites/PROJECTNAME/sites/default/files`, then run: chmod -R 777 ~/Sites/PROJECTNAME/sites/default/files drush cc all drush fra -y Log in: drush uli Disable cache and JS/CSS file aggregation at http://PROJECTNAME.dev/admin/config/development/performance ## Front-end Setup Theme directory is at: `~/Sites/PROJECTNAME/profiles/PROJECTNAME/themes/custom/PROJECTNAME` To get Sass running, `cd` to that directory and run `bundle` Thereafter, you only need to run `rake serve` from the theme directory. Accuracy

The nice thing about having your docs in a wiki is that everyone in your organization can edit them if they discover they are out of date. When a new team member is added to a project, encourage them to work from the docs and see how far they can get without asking for clarification or dealing with an unexpected error. And make sure they update the docs to reflect their experience - the only time docs are ‘done’ is when anyone can use them reliably every time. If you have to ask what something means, it’s likely that the next person will need to know that too - so update the docs!

Completeness

Every project has its quirks and exceptions to the standard procedures - usually for good reason. Good docs will not only note exceptions to standard procedures, but also explain why. In addition, sometimes a ‘Phase 2’ project will require additional information. Make note of these major updates with details such as planning info, principals, dates, and an overview of what was accomplished.

Sometimes a developer will run across coding environment issues that hold them up - this is quite common for the complex front-end setups needed to compile SASS into CSS. Front-end developers sometimes take these setups for granted, but documenting that install process can mean that your back-end developer can handle small CSS changes without assistance:

To get Sass running, `cd` to that directory and run `bundle` Thereafter, you only need to run `rake serve` from the theme directory. NOTE: If you get a 'not found' error after running `bundle`, run `gem install bundler`, then `bundle install`. Part of Your Process

Finally, it’s not enough to have all of these wonderful docs in place and forgotten - they have to be a part of your project setup and launch checklist, and it needs to a part of every project, big or small.

Consistent, accurate, and complete project documentation will save time, make your code easier to maintain, improve team confidence, and do a great service to every developer who comes to your project after it’s finished. Docs Rocks!

Matt Glaman: Explore Drupal Commerce 2 with Commerce Demo!

Planet Drupal -

When we talk about , the biggest we questions we get are not about features, but when you can start building with it. Well, the answer is and has been now! Drupal Commerce 2 has been in alpha . What does this mean? In alpha we might have some schema changes, requiring a reinstall of your site. Luckily Drupal 8 has that fancy new configuration management system to export your site, right?

But what about products! That's data you lose on each reinstall. Luckily, we have in core and has been kicked off for Drupal 8. Generally speaking, most e-commerce sites have some sort of CSV or other file format containing product information. You can use Migrate to import that data and begin building your Drupal Commerce 2 site.

Imperceivable?! Nay! See the . This provides a T-Shirt product type with some and color attributes. It also imports sample products from a CSV. The CSV mimics the flat format you might receive from am ERP, you hopefully you can re-use it!

Here's how you can add it to your Drupal site using composer.

"repositories": [ { "type": "vcs", "url": "https://github.com/mglaman/commerce_demo" } ],

Otherwise, download it from GitHub: https://github.com/mglaman/commerce_demo/archive/master.zip

What's next? This module will showcase the new flexibility and control you have over your Drupal Commerce site, with best practices in mind.

Drupal @ Penn State: The low-down on DrupalcampPA July 30/31 in Pittsburgh!

Planet Drupal -

DrupalcampPA is July 30 and 31st in Pittsburgh PA and Yinz-all should come! We just announced our full schedule with keynotes, giveaways, and more. Some quick highlights of why you should come! Submissions this year tried to take the stance of “getting off the island” by having more and more presentations about topics that plug into or are affiliated with Drupal without just being about Drupal.

Daniel Pocock: Let's Encrypt torpedoes cost and maintenance issues for Free RTC

Planet Drupal -

Many people have now heard of the EFF-backed free certificate authority Let's Encrypt. Not only is it free of charge, it has also introduced a fully automated mechanism for certificate renewals, eliminating a tedious chore that has imposed upon busy sysadmins everywhere for many years.

These two benefits - elimination of cost and elimination of annual maintenance effort - imply that server operators can now deploy certificates for far more services than they would have previously.

The TLS chapter of the RTC Quick Start Guide has been updated with details about Let's Encrypt so anybody installing SIP or XMPP can use Let's Encrypt from the outset.

For example, somebody hosting basic Drupal or Wordpress sites for family, friends and small community organizations can now offer them all full HTTPS encryption, WebRTC, SIP and XMPP without having to explain annual renewal fees or worry about losing time in their evenings and weekends renewing certificates manually.

Even people who were willing to pay for a single certificate for their main web site may have snubbed their nose at the expense and ongoing effort of having certificates for their SMTP mail server, IMAP server, VPN gateway, SIP proxy, XMPP server, WebSocket and TURN servers too. Now they can all have certificates.

Early efforts at SIP were doomed without encryption

In the early days, SIP messages would be transported across the public Internet in UDP datagrams without any encryption. SIP itself wasn't originally designed for NAT and a variety of home routers were created with "NAT helper" algorithms that would detect and modify SIP packets to try and work through NAT. Sadly, in many cases these attempts to help actually clash with each other and lead to further instability. Conversely, many rogue ISPs could easily detect and punish VoIP users by blocking their calls or even cutting their DSL line. Operating SIP over TLS, usually on the HTTPS port (TCP port 443) has been an effective way to quash all of these different issues.

While the example of SIP is one of the most extreme, it helps demonstrate the benefits of making encryption universal to ensure stability and cut out the "man-in-the-middle", regardless of whether he is trying to help or hinder the end user.

Is one certificate enough?

Modern SIP, XMPP and WebRTC require additional services, TURN servers and WebSocket servers. If they are all operated on port 443 then it is necessary to use different hostnames for each of them (e.g. turn.example.org and ws.example.org. Each different hostname requires a certificate. Let's Encrypt can provide those additional certificates too, without additional cost or effort.

The future with Let's Encrypt

The initial version of the Let's Encrypt client, certbot, fully automates the workflow for people using popular web servers such as Apache and nginx. The manual or certonly modes can be used for other services but hopefully certbot will evolve to integrate with many other popular applications too.

Currently, Let's Encrypt only issues certificates to servers running on TCP port 443. This is considered to be a privileged port whereas any port over 1023, including the default ports used by applications such as SIP (5061), XMPP (5222, 5269) and TURN (5349), are not privileged ports. As long as Let's Encrypt maintains this policy, it is necessary to either run a web server for the domain associated with each certificate or run the services themselves on port 443. Running the services themselves on port 443 turns out to be a good idea anyway as it ensures that RTC services can be reached through HTTP proxy servers who fail to let the HTTP CONNECT method access any other ports.

Many configuration tasks are already scripted during the installation of packages on a GNU/Linux distribution (such as Debian or Fedora) or when setting up services using cloud images (for example, in Docker or OpenStack). Due to the heavily standardized nature of Let's Encrypt and the widespread availability of the tools, many of these package installation scripts can be easily adapted to find or create Let's Encrypt certificates on the target system, ensuring every service is running with TLS protection from the minute it goes live.

If you have questions about Let's Encrypt for RTC or want to share your experiences, please come and discuss it on the Free-RTC mailing list.

DrupalEasy: Best Practices = Effective Government

Planet Drupal -

When it comes to serving their constituents with effective online access, the Iowa Public Employee Retirement System keeps getting it right.

From the time IPERS was first deciding to shed their Dreamweaver framework a few years ago for something more robust, to ensuring that they have well-trained internal Drupal talent; the IPERS Application Programming Services and Communication teams rocked the process and aced the outcome by sticking with best practices.  

The IPERS APS and Communication teams chose Drupal through an extremely efficient process, focused on what other agencies had already put in place, how the transition went, and how the new framework was working out. The solution would of course have to be cost effective, ensure that the needs of the agency and their 700 daily users were met, be implemented in a timely way, and utilize the ability of their internal team to deliver and maintain high levels of service for years to come.

Carla Stoner

Carla Stoner, who has been with IPERS for 19 years, is the APS team member directly responsible for the technical function of the web site and coordination with the Office of the Chief Information Officer. APS and the Communication teams streamlined their selection process, using the experiences and examples of other Iowa agencies that had already upgraded their web sites. Once they narrowed down the field of potential frameworks, a final demo of DotNetNuke by a fellow state agency made Drupal the clear choice. They contracted and worked closely with an outside consulting company to develop the new IPERS site, which went live in the summer of 2015.

While the new build was going on, Carla was made aware of DrupalEasy’s Drupal Career Online program. “My supervisor was the one who found the DrupalEasy training course for me,” she explains, “He wanted a type of training that would have substance and not something that would last only a week and be crammed with spoon-fed work exercises.”

The DCO is long-form training with integrated instruction, an actively-engaged expert teacher (MIke Anello; ultimike on Drupal.org) focused on student learning, a built-in learning community, and comprehensive learning and resource materials. The program emphasizes Drupal best practices and community participation.

“My supervisor and I were both impressed with the length of the course, knowing that there would be a lot of material covered. We also liked the idea of all the ‘hands on’ experience…” she recalls. With this in mind, they decided to wait on formal training for Carla until her schedule allowed her to really engage. After the transition to the new site, she was encouraged to devote the 11+ hours per week to the 12-week session of the DCO that began that September.

“I had zero background in Drupal, but had used Dreamweaver, which gave me exposure to HTML and CSS,” she said. She continued, “...All of the topics covered in the DCO are very relevant to my work.  Even though our test and production environments are setup a bit differently from the norm (Drush and Git aren’t used as prevalently), learning these basic tools of Drupal have increased my skills for when I do get to use them.”

She added, “The DrupalEasy course is laid out in such a way that it keeps building on each segment. You don’t just learn it once and forget it.  Michael has you continually utilizing what you learned and then reapplying it... I also enjoyed the “community” we developed amongst ourselves, the classmates.  We helped each other.  Michael fostered an atmosphere that made learning fun... It helped build camaraderie.  I still feel that same camaraderie to this day.”

Carla’s learning also continues. “My DrupalEasy class ended last November (2015) and even now as I come across a request to change our website, I remember back to when Michael taught us how to accomplish that.  And if I don’t remember, I can always review the very handy screencasts he has done.”  She is also among the DCO alumni who take advantage of Mike’s open office hours every Thursday afternoon.“We all try to help each other. Even though I am by no means an expert...there are times that I feel I’m making a helpful suggestion or can see as I’m watching Michael demonstrate how to solve a person’s issue…,” she concludes.

IPERS transition to their Drupal site, starting with the selection of the framework, into the site development and continuing on with internal staff development demonstrates the effectiveness of using tried and true best practices.   They looked at their needs, found the most cost-effective solutions, and committed the time and effort to ensure the best possible outcomes. That’s effective government.

If you would like to learn more about Drupal Career Online, you can attend one of two Taste of Drupal informational workshops coming up in August and September. 

Liip: An opensource Drupal theme for the Swiss Confederation

Planet Drupal -

After having contributed to the official styleguide of the Swiss Federal Government and having implemented it on a couple of websites, we decided to go further and bring these styleguide into a theme for Drupal, a well-known, pluripotent and robust CMS we implement regularly at Liip.

The current result is a starterkit providing the essential bricks to start in a snap a website project for the federal government running with Drupal 8, based on the version 3 of the official styleguide.

Navigation modules, multilingual environnement per default (German, French, Italian, Rumantch and English), responsive layout following the Web Content Accessibility Guidelines, we threw the fundamental stones for bootstraping a web platform for the Confederation.

con~foederatio : to build a league, together.

In other words, joining forces, to support a common cause. From the very start of the project we decided to opensource the code, as a participatory initiative.
Learn more about this intent (German only).

Any developer working on a new website for the swiss government can now quickly start developing with this Drupal starterkit, then modify, contribute and improve it collegially. Pulling requests and opening issues on GitHub is the recommended way to help us extend further the project.

What’s inside the box

The Bund-Starterkit provides theme and elements based on the official styleguide (version 3.0.0) of the Swiss Federal Administration.

This starterkit also contains a base to quickly implement a website running on Drupal 8 for the Swiss Federal Administration. Currently, it provides the following Drupal and frontend elements:

  • Multilingual main navigation blocks
  • Multilingual service navigation blocks
  • Multilingual footer service navigation blocks
  • Logo block
  • Language switcher block with German, French, Italian, Rumantsch enabled
  • All the assets (CSS, SASS. JS files) provided by the official styleguide
  • A ready-to-use SASS workflow
Installation process, an overview

Please check the Readme file to quickly start your project. But let’s have a look at the details of the installation process. First of all, Composer (a PHP dependencies manager) is binding together for us the following repositories:

After downloading the sources with Composer and setting your vhost and hosts files, you have two options. Continuing with a few drush commands to run the Drupal installation process, or following the installation wizard in the browser. If you choose this last option, don’t forget to select the «Bund profile» option when the wizard ask you to choose a profile:

Continue with the last steps of the wizard and that’s it. you should be able to see an empty Drupal 8 website, painted with the swiss administration’s corporate sauce.

Inserting menus content

With the help of a .CSV file and some drush commands, you can quickly import your menu structure. Once done, create and assign your content the the freshly created menu items through the Drupal administration interface.

Theming

Don’t forget to create a personal Drupal sub-theme from the bund_drupal_starterkit_theme, as a Drupal best practice.  Don’t edit the existing theme directly or you could loose your changes after a future update.

Frontend

This starterkit use the official styleguide (version 3.0.0) as a submodule. All existing CSS/JS files and assets are imported and available per default, but not necessary integrated as a drupal module at the moment. We highly encourage you to check the official styleguide before adding any new CSS style or JS files to your project. Based on the existing styles, it should be possible to create a lot of Drupal templates without modifying or extending any CSS. And as already said, we invite you to share any Drupal template matching the styleguide you would develop for your project.

Further reading

PreviousNext: Refactoring Drupal batch API callbacks to increase testability

Planet Drupal -

Drupal's Batch API is great, it allows you to easily perform long running processes with feedback to the user.

But during Drupal 8's development processes it was one of the remaining systems that didn't get the full object oriented, service-based architecture.

Much of the batch API is largely unchanged from Drupal 7.

But that doesn't mean you can't write unit-testable callbacks.

Let's get started.

Wuinfo: Joy Of Collaboration

Planet Drupal -

We make our life easier by making our colleague's lives easier. If our manager is in a stressful state, we'd better find the way to do something. It is such a fulfill feeling when we can do something together and contribute as a member of a productive team.

I had been in a financial system project for a company in NYC. We needed to migrate a huge amount of content from old system to a new one (Tech: Drupal 5 to Drupal 7). The business is making money by selling data. So, data accuracy was a big thing. Due to the complexity of the data, couple months into the project, we had not got the content migrated. Some technical problems prevented us from going forward. Everyone in the team was under pressure and working very hard. Company executives were starting to losing patience and doubt our ability to get the job done. Our boss was under a lot of stress. In a weekly meeting a few weeks after I joined the project, our manager told us that he was not sure he would still be working for the company the next day. He was afraid he might get fired by his boss. It was like a stone in my stomach. What would happen to us if he lost the job? The whole team was quickly motivated. We all liked him and did not want it to become reality. We all know it was the time all out for a greater good.

For the interest of the group, we did not care about a small personal loss. When migrating location nodes, we needed Google map API to translate hundreds of thousands postal address. It is not free. To save time from asking permission to buy the service, one of our colleagues just went ahead and created an account with his personal credit card. It cost him some money but saved some time for the whole team. We all worked late, collaborated closely and more efficiently. We did not mind to sacrifice for the interest of the project.

My job was to assistant the other backend developer to migrate the content. It was such a compelling feeling to be a part of it and wanted the success of the project. It occupied my mind. When eating, walking, taking a shower, sleeping and even dreaming I had been thinking the ways to solve some technical problems; contemplating the best possible solutions. Many of us include myself were a little bit sick. But, physical health with good rest and diet is the key to a clear and sharp mind. Even though we had a lot of stress, I believe that was one of the key elements to the success of the project. I had learned some time management skill before. Not wasting a minute, I allocated enough time to eat and sleep, and that help me to keep my mind fresh and calm all the time. Two weeks after the meeting, we successfully overcame all the major technical difficulty and got the content migrated.

Everyone seemed to be relaxed right away. It was a pleasure to the conversation during the following meeting. Like fighting a battle should by should against a ferocious enemy and win it, everybody in the team felt closer and more connected to each other. We helped each other and collaborated closely and made our life easier. It is a real joy from collaboration.

CiviCRM Blog: Mapping it in 5-10min - a CiviCON 2016 Lightening Talk

Planet Drupal -

Someone asked me to post this here - so that he can give it a try!

I did a Lightening Talk at CiviCON 2016 showing how you can put your Contacts on a Leaflet Map. It only takes a few minutes to put your CiviCRM Contacts on a Leaflet Map if you're using Drupal. Leaftlet is an open-source JavaScript Library for interactive maps. In addition what's really cool is that you can color the PIN based on the value of a CiviCRM custom field!

I've posted the details in a QA format including some of my slides from my CiviCON Lightening Talk on CiviCRM's StackExchange site:

http://civicrm.stackexchange.com/questions/12862/how-to-put-your-civicrm...

Give it try!

CiviConCiviCRMDrupalTips

Freelock : Git Branch Strategy meets Continuous Deployment

Planet Drupal -

Our branch strategy based on Git Flow did not survive. It was getting a bit old in the tooth, but the final blow was automation.

At Freelock, we've been hard at work building out automation so we can handle the maintenance on hundreds of websites with better test coverage and more confidence than ever before. Exciting news! It's all coming together, and we have it working across the board on ALL of our projects, now.

DrupalDevOpsContinuous IntegrationContinuous DeploymentQuality AssuranceDrupal PlanetBotgit flowgit

Fuse Interactive: Why you and your clients should be excited to build your next project with Drupal 8

Planet Drupal -

Over 8 months after release and my first D8 site under my belt I can now say I am excited for the future of working with Drupal’s freshest release. That being said at this stage in the game the decision to go with D8 should approached with caution. It does what it does well but many of those shiny contrib modules you’re used to using just aren’t there yet. Unless your team and client are willing to spend the time and money needed to develop or port the missing functionality it might not be a fit for that particular project.

ImageX Media: Higher Education Notes and Trends for the Week of July 4, 2016

Planet Drupal -

The landscape of higher education continues to shift toward changing student demographics, evolving different learning approaches and what seems like a perpetual shortfall of funding for post-secondary institutions. These trends mirror that of our client website aspirations which are now more than ever are focusing on engagement with key audiences such as prospective students and alumni due to greater competition in the marketplace with less dollars to spend. 

Chromatic: Digging In To Drupal 8: Code Snippets for Site Builders

Planet Drupal -

The more I work with Drupal 8, the more I realize how much has changed for developers in the Drupal community. While the transition to a modern, object-oriented system is what's best for the longevity of the platform, it certainly doesn't come without challenges. As someone who doesn't come from an OOP background, I've found the transition difficult at times. In many cases, I know exactly what I want to do, just not how to do it the "Drupal 8 way". On top of this, tutorials and blog posts on D8 are all over the map in terms of accuracy. Many posts written during D8's development cycle are no longer applicable because of API changes, etc.

Below is a list of snippets that might be helpful to site builders or developers more familiar with D7 hooks and procedural. It might also be useful to OOP folks who are new to Drupal in general. My goal below is to add to and update these snippets over time.

Routes & Links Determine the Current Drupal Route

Need to know what the current Drupal route is or need to run some logic against the current route? You can get the current route like so:

$route = \Drupal::routeMatch()->getRouteName();

To some, the \Drupal::routeMatch() syntax might look foreign (it did to me). Here's a rundown of what's happening here:

First, \Drupal. This is calling the global Drupal class, which, in Drupal 8, is a bridge between procedural and OO methods of writing Drupal code. The following comes from the documentation:

This class acts as a unified global accessor to arbitrary services within the system in order to ease the transition from procedural code to injected OO code.

Right. Moving on to ::routeMatch(). Here we're using the routeMatch() method which "Retrieves the currently active route match object." Simple enough. But what is "::" all about? This StackOverflow answer helped me to understand what that's all about.

From there, the getRouteName() method returns the current route name as a string. Here are some example routes: entity.node.canonical, view.frontpage and node.type_add.

Is this the Front Page Route?

Need to check if the current route is the front page route? There's a service and method for that:

// Is the current route/path the front page? if ($is_front = \Drupal::service('path.matcher')->isFrontPage()) {}

Here we're calling the path.matcher service (defined in /core/core.services.yml) and using the isFrontPage() method. For more on services, check out the "Services and Dependency Injection Container" documentation on api.drupal.org which helped me understand how all of these bits work together and the why of their structure.

Get the Requested Path

Need to know what the current page's requested path was, as opposed to the route? You can do this:

$current_uri = \Drupal::request()->getRequestUri(); Redirect to a Specific Route

Need to redirect to a specific page? In Drupal 7, you would likely handle this with drupal_goto() in your page callback function. In Drupal 8, you can use RedirectResponse() for that. Here is the relevant changelog.

Here are some examples, borrowed heavily from said changelog. First, in procedural PHP:

use Symfony\Component\HttpFoundation\RedirectResponse; function my_redirect() { return new RedirectResponse(\Drupal::url('user.page')); }

Here is how you would use a Drupal 8 controller to accomplish the same thing:

use Drupal\Core\Controller\ControllerBase; class MyControllerClass extends ControllerBase { public function foo() { //... return $this->redirect('user.page'); } } Links on the Fly

Drupal 7 and prior relied heavily on the l() function. (In fact, I would wager this was my most used function over the years. In Drupal 8, if you need to create links on the fly, utilize the Link class

$link = \Drupal\Core\Link::fromTextAndUrl($text, $url); Working with Entities Query Database for Entities

If you need to query the database for some nodes (or any other entity) you should use the entityQuery service. The syntax should be pretty familiar to most D7 developers who have used EntityFieldQuery:

// Query for some entities with the entity query service. $query = \Drupal::entityQuery('node') ->condition('status', 1) ->condition('type', 'article') ->range(0, 10) ->sort('created', 'DESC'); $nids = $query->execute(); Loading Entities

If you need to load the actual entities, you can do so a number of ways:

While the following will technically work in Drupal 8:

$node = entity_load_multiple('node', $nids);

This method has been deprecated in Drupal 8 and will be removed before Drupal 9, in favor of methods overriding Entity::loadMultiple(). To future-proof your code, you would do something like the following:

$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);

Here's how you would do similar for a single node:

$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);

Here are a few other entity snippets that might be useful:

// Link to an entity using the entity's link method. $author_link = $user->toLink(); // Do the same thing, but customize the link text. $author_link = $user->toLink('Some Custom Text'); // Given a node object, here's how to determine its type: $type = $node->getType(); // To get the full user entity of the node's author: $author = $node->getOwner(); // To get the raw ID of the author of a node: $author_id = $node->getOwnerId(); Image Styles

Need to whip up an image using a particular image style on the fly? This will work for that:

// Create an instance of an image using a specific image style, given a path to a file. $style = \Drupal\image\Entity\ImageStyle::load('yourStyle_image'); $img_path = $user->field_profile_some_image->entity->getFileUri(); $img_style_url = $style->buildUrl($img_path);

That's it for now. I intend to keep this post updated as we learn more and more about the new world of Drupal 8. If you have a snippet worth sharing, drop us a line via Twitter and we’ll add it to this post (with credit of course).

Chromatic: Be Promiscuous with Drush's core-quick-drupal

Planet Drupal -

Aren't you a cutie?

Here at Chromatic HQ, the team is encouraged to give back to the open-source community. (And on company time!) One way to do this is by reviewing and contributing Drupal patches. For me, this can be both rewarding and frustrating. When things go well, I feel good about contributing and I might even get a commit credit! But there are times when patches don't apply, I have no clue what's wrong and I need to start fresh. First, I curse mightily at the time wasted, then I create a new db, and then re-install a fresh copy of Drupal, and then configure it etc. etc. Using drush site-install makes this process relatively easy, but what if it could be easier? (Hint: It is!)

Hooray for promiscuity!

I recently had a fling with Drush's core-quick-drupal command. I had known about it for years, but I hadn't realized what it could really do for me. This has now changed, and together we're having an open affair!

For the uninitiated, drush core-quick-drupal takes advantage of PHP's built-in web server (PHP >= 5.4) and uses a sqlite database to get a fresh, stand-alone copy of Drupal up and running, all in about a minute. It has two aliases: drush qd and, my personal preference, drush cutie.

Out-of-the-box overview
  • In about a minute it installs a full instance of Drupal.
  • Runs a web server at http://127.0.0.1:8888 (no apache config).
  • Uses a self-contained sqlite file as the db (no mysql db to create and configure).

It's so much fun, you may want to follow along. From the command line, just cd to a folder of your choosing and run drush cutie --yes. (You'll need to have drush installed.)

Behind the scenes, a folder is created called quick-drupal with a timestamp appended to the end. (One of my older cutie folders is quick-drupal-20160214193640... a timestamp from a Valentine's evening with Drush that my wife won't soon forget!) Inside the new quick-drupal folder are subfolders with the latest D8 files and the sqlite db file. (There are lots of options to customize the Drupal version and environment, but the default nowadays is Drupal 8.)

Running it looks something like this drush cutie --yes Project drupal (8.0.3) downloaded to ... Installation complete. User name: admin User password: EawsYkGg4Y Congratulations, you installed Drupal! Listening on http://127.0.0.1:8888

(The output above has been edited to highlight the tastier bits!)

And with that I have the latest version of D8 running at http://127.0.0.1:8888. As you can see from the shell output above, the superuser is admin with a password of EawsYkGg4Y.

Okay, okay, very cool, but what can I do with it? Here's a breakdown:
  1. Review patches with minimal fuss, thereby giving back to the Drupal community.
  2. Investigate new modules without sullying your main dev environment.
  3. Test that new Feature you created to see if it really works.
  4. NOT RECOMMENDED! When that friend asks you how long it will take to build him a website, respond with "about a minute" and fire it up.
You thought I was done?

Let's run through the steps to review a patch. This is where drush core-quick-drupal really shines because it's best to have a clean install of Drupal to work with; this minimizes the number of externalities that can interfere with testing. Having a single-command, throwaway copy of vanilla Drupal is the way to go.

You could call this a blog version of a live demo; I have chosen a patch out in the wild to review. I found this one for the core taxonomy module, that had a status of "Needs Review" on D.O.

The patch file itself is here: https://www.drupal.org/files/issues/taxonomy-term-twig-cs.patch

Here are the steps I took on the command line:

# Install a temporary copy of D8 into a folder I named "test2644718" drush cutie test2644718 --yes

With the above command I got my environment running. The patch itself simply fixes the formatting in taxonomy-term.html.twig, which is a default template file for taxonomy terms, provided by the core taxonomy module.

I first tested to see the original template in action. Satisfied with the way it was working, I took steps to apply the patch.

# Move into the root folder of the new site cd test2644718/drupal/ # Use wget to grab the patch from D.O. wget https://www.drupal.org/files/issues/taxonomy-term-twig-cs.patch # Apply the patch patch -p1 < taxonomy-term-twig-cs.patch patching file core/modules/taxonomy/templates/taxonomy-term.html.twig

The patch was applied successfully and a minor change in taxonomy-term.html.twig was made. I quickly tested to ensure nothing had blown up and was satisfied that the patch works as expected.

Back in D.O., I added my two cents and marked the issue as Reviewed & tested by the community. And that's that.

Update

Though the patch originally sat awaiting review for 2 months, I'm happy to claim that my review got things moving again! After I posted RTBC, a flurry of activity took place with the scope increasing and new patches being created. I reviewed those too! A day later the patches were committed to 8.1.x. Nice.

Pages

Subscribe to Cruiskeen Consulting LLC aggregator