Skip to main content

Blog

Test your Drupal site's functionality in a human-readable format.

Behavior-driven development is a great way to write tests for code because it uses language that real humans can understand. Once you learn about BDD and its benefits, you may want to implement it in your next project. Let's see how to implement BDD in Drupal using Behat with the Mink extension.

Find It Use Cases

Find It Cambridge

Curated by members of the Cambridge Kid's Council, Find It Cambridge was designed to help busy parents stay informed about the plethora of educational opportunities available for their children.

Find It Immigrant Navigator (link coming soon!)

Curated by Immigrant Family Services Institute, the Immigrant Navigator was designed to provide information on events and services for new Haitian Immigrants in order to ease their transition into life in the United States.

 

David has been doing web development for 12 years now and Drupal development for the last 6. In his early days as programmer he read about the Free Software movement and immediately wanted to be part of it.

He started contributing to different free software projects but the majority of his work has been made for Drupal, as a core contributor and helping to fix and improve some contrib modules he enjoys helping Drupal become better so that more people can adopt it.

 

Part analyst, part troubleshooter, and part troublemaker, Stefan serves as Agaric's secret weapon and resident heretic. From his homeland of Germany, with other Agarics in Massachusetts, and at Drupal events around the world, Stefan programs, administers systems, and questions Drupal dogma.

Multilingual in human and computer languages, Stefan's technological curiosity and talents have benefited Agaric clients and the Drupal community. With an interest in integrating systems via web services, his work has included LDAP and Kerberos configuration. With his contributions to RDF in Drupal, Stefan is helping build the semantic web, in which computers understand what we mean and let us do fantastically smart and complex things with the knowledge we're all putting online.

Gracias por el interetes en nuestras capacitaciones. Solo necesitamos un poco de información acerca de lo que buscas y nos pondremos en contacto pronto.

In the previous entry, we learned that the Migrate API is an implementation of an ETL framework. We also talked about the steps involved in writing and running migrations. Now, let’s write our first Drupal migration. We are going to start with a very basic example: creating nodes out of hardcoded data. For this, we assume a Drupal installation using the standard installation profile, which comes with the Basic Page content type. As we progress through the series, the migrations will become more complete and more complex. Ideally, only one concept will be introduced at a time. When that is not possible, we will explain how different parts work together. The focus of today's lesson is learning the structure of a migration definition file and how to run it.

List of migrate plugins

Writing the migration definition file

The migration definition file needs to live in a module. So, let’s create a custom one named ud_migrations_first and set Drupal core’s migrate module as dependencies in the *.info.yml file, ud_migrations_first.info.yml.  The contents of the file will be:


type: module
name: UD First Migration
description: 'Example of basic Drupal migration. Learn more at https://understanddrupal.com/migrations.'
package: Understand Drupal
core: 8.x
dependencies:
  - drupal:migrate

Now, let’s create a folder called migrations and inside it, a YAML (Yet Another Markup Language) configuration file called udm_first.yml. Note that the extension is, yml not yaml. The contents of the file will be:


id: udm_first
label: 'UD First migration'
source:
  plugin: embedded_data
  data_rows:
    -
      unique_id: 1
      creative_title: 'The versatility of Drupal fields'
      engaging_content: 'Fields are Drupal''s atomic data storage mechanism...'
    -
      unique_id: 2
      creative_title: 'What is a view in Drupal? How do they work?'
      engaging_content: 'In Drupal, a view is a listing of information. It can a list of nodes, users, comments, taxonomy terms, files, etc...'
  ids:
    unique_id:
      type: integer
process:
  title: creative_title
  body: engaging_content
destination:
  plugin: 'entity:node'
  default_bundle: page

The final folder structure will look like:


.
|-- core
|-- index.php
|-- modules
|   `-- custom
|       `-- ud_migrations
|           `-- ud_migrations_first
|               |-- migrations
|               |   `-- udm_first.yml
|               `-- ud_migrations_first.info.yml

YAML is a key-value format with optional nesting of elements. They are very sensitive to white spaces and indentation. For example, they require at least one space character after the colon symbol (:) that separates the key from the value. Also, note that each level in the hierarchy is indented by two spaces exactly. A common source of errors when writing migrations is improper spacing or indentation of the YAML files.

A quick glimpse at the migration configuration file reveals the three major parts: source, process, and destination. Other keys provide extra information about the migration. There are more keys that the ones shown above. For example, it is possible to define dependencies among migrations. Another option is to tag migrations so they can be executed together. We are going to learn more about these options in future entries.

Let’s review each key-value pair in the file. For, id it is customary to set its value to match the filename containing the migration definition, but without the .yml extension. This key serves as an internal identifier that Drupal and the Migrate API use to execute and keep track of the migration. The id value should be alphanumeric characters, optionally using underscores to separate words. As for the label key, it is a human readable string used to name the migration in various interfaces.

In this example, we are using the embedded_data source plugin. It allows you to define the data to migrate right inside the definition file. To configure it, you define a data_rows key whose value is an array of all the elements you want to migrate. Each element might contain an arbitrary number of key-value pairs representing “columns” of data to be imported.

A common use case for the embedded_data plugin is testing of the Migrate API itself. Another valid one is to create default content when the data is known in advance. I often present introduction to Drupal workshops. To save time, I use this plugin to create nodes which are later used in the views creation explanation. Check this repository for an example of this. Note that it uses a different directory structure to define the migrations. That will be explained in future blog posts.

For the destination, we are using the entity:node plugin which allows you to create nodes of any content type. The default_bundle key indicates that all nodes to be created will be of type “Basic page”, by default. It is important to note that the value of the default_bundle key is the machine name of the content type. You can find it at /admin/structure/types/manage/page In general, the Migrate API uses machine names for the values. As we explore the system, we will point out when they are used and where to find the right ones.

In the process section you map columns from the source to node properties and fields. The keys are entity property names or the field machine names. In this case, we are setting values for the title of the node and its body field. You can find the field machine names in the content type configuration page: /admin/structure/types/manage/page/fields. Values can be copied directly from the source or transformed via process plugins. This example makes a verbatim copy of the values from the source to the destination. The column names in the source are not required to match the destination property or field name. In this example, they are purposely different to make them easier to identify.

You can download the example code from https://github.com/dinarcon/ud_migrations The example above is actually in a submodule in that repository. The same repository will be used for many examples throughout the series. Download the whole repository into the ./modules/custom directory of the Drupal installation and enable the “UD First Migration” module.

Running the migration

Let’s use Drush to run the migrations with the commands provided by Migrate Run. Open a terminal, switch directories to Drupal’s webroot, and execute the following commands.


$ drush pm:enable -y migrate migrate_run ud_migrations_first
$ drush migrate:status
$ drush migrate:import udm_first

The first command enables the core migrate module, the runner, and the custom module holding the migration definition file. The second command shows a list of all migrations available in the system. Only one should be listed with the migration ID udm_first. The third command executes the migration. If all goes well, you can visit the content overview page at /admin/content and see two basic pages created. Congratulations, you have successfully run your first Drupal migration!!!

Or maybe not? Drupal migrations can fail in many ways, and sometimes the error messages are not very descriptive. In upcoming blog posts, we will talk about recommended workflows and strategies for debugging migrations. For now, let’s mention a couple of things that could go wrong with this example. If after running the drush migrate:status command, you do not see the udm_first migration, make sure that the ud_migrations_first module is enabled. If it is enabled, and you do not see it, rebuild the cache by running drush cache:rebuild.

If you see the migration, but you get a yaml parse error when running the migrate:import command, check your indentation. Copying and pasting from GitHub to your IDE/editor might change the spacing. An extraneous space can break the whole migration so pay close attention. If the command reports that it created the nodes, but you get a fatal error when trying to view one, it is because the content type was not set properly. Remember that the machine name of the “Basic page” content type is page, not basic_page. This error cannot be fixed from the administration interface. What you have to do is rollback the migration issuing the following command: drush migrate:rollback udm_first, then fix the default_bundle value, rebuild the cache, and import again.

Note: Migrate Tools could be used for running the migration. This module depends on Migrate Plus. For now, let’s keep module dependencies to a minimum to focus on core Migrate functionality. Also, skipping them demonstrates that these modules, although quite useful, are not hard requirements for running migration projects. If you decide to use Migrate Tools make sure to uninstall Migrate Run. Both provide the same Drush commands and conflict with each other if the two are enabled.

What did you learn in today’s blog post? Did you know that Migrate Plus and Migrate Tools are not hard requirements for Drupal migrations projects? Did you know you can place your YAML files in a migrations directory? What advice would you give to someone writing their first migration? Please share your answers in the comments. Also, I would be grateful if you shared this blog post with your friends and colleagues.

Next: Using process plugins for data transformation in Drupal migrations

This blog post series, cross-posted at UnderstandDrupal.com as well as here on Agaric.coop, is made possible thanks to these generous sponsors: Drupalize.me by Osio Labs has online tutorials about migrations, among other topics, and Agaric provides migration trainings, among other services.  Contact Understand Drupal if your organization would like to support this documentation project, whether it is the migration series or other topics.

Select a language

Navigate the site in your language of choice or contribute improvements to the translations so that Find It can better meet the needs of the diverse communities it serves.

I am very happy the bug is fixed and this blog post will be obsolete in mere days! Usually this sort of technical noodlings get relegated to our raw notes, currently hosted through GitLab, but figured at least a few other Drupal developers would want to know what has been going on with their toolbars.

Image credit: "Too Many Tabs" by John Markos O'Neill is licensed with CC BY-SA 2.0.

Training FAQ

Here are some quick answers to Frequently Asked Questions about Agaric trainings.

Can I get a discount when purchasing more than one training?

Yes, a 15% discount is available for additional trainings. Contact Agaric after purchasing your first training to get the information needed to purchase second or third at a discount.

Are scholarships available?

Yes, partial and full scholarships are available! We are prioritizing people facing disadvantages, in particular survivors of historical and ongoing discrimination and people under-represented in technology. Contact Agaric with your circumstances and for more information. Agaric will review your submission internally only— we do not share the information you provide in determining your eligibility for a discount/scholarship with anyone outside Agaric.

What if my corporate employer cannot submit payment for my attendance before the training date? If your company sees the benefit of you getting training from Agaric but the accounts payable department will not be able to accommodate fulfilling payment prior to the training date, please contact us for an invoice due up to 90 days after the training.
I'm not sure I meet the prerequsites or will be able to set up a development environment.

Every training includes sessions ahead of time to help everybody get their local development environment set up before the training (if needed). We'll also direct you to other resources helpful for getting up to speed before the training. Contact Agaric to check in with where you are to get our help ensuring you get the full benefit of the training.

Can I cancel and get a refund?

No, we do not offer refunds but tickets are transferable and we'll help you re-sell the ticket, so please contact Agaric if you can't make the training.

Will I receive a recording or other materials?

Yes, all attendees will be sent recordings from the training as well as the curriculum and materials used in the training and additional books or other references and resources.

Will Agaric provide a certificate of completion?

Yes, all students who participate in the full training will receive a Certificate of Completion.

Have more questions? Ask Agaric!

.

Agaric builds tools for medical and scientific communities to advance their work, enhance collaboration, and improve outcomes.  And we've been doing this—helping healthy discussion about science and medicine flourish online—since 2008.

Reusable platforms for advanced online collaboration

Therapy Fidelity App

Agaric is developing the Therapy Fidelity app: an all-in-one, inexpensive mobile web application to help therapists do the work of counseling. The app automates surveys, handles multiple CBT protocols, tracks fidelity, monitors outcomes, and more. This application is being developed for Scheeringa Mind Company with initial funding by Tulane University.  It is built in JavaScript (React and Typescript) and Golang and makes extensive use of Truevault and AWS APIs.

The Collaboratory

The National Institute for Children's Health Quality partnered with Agaric to build the Collaboratory—a platform designed specifically to help healthcare improvement teams collaborate, innovate, and make change. During this partnership, begun in 2015, Agaric built a collaborative analytics tool that allows healthcare quality teams to visualize, compare, and benchmark data, identify opportunities for improvement, and celebrate their successes. We were proud to be NICHQ's 2020 partners in making the most of the digital health revolution.

Platform for Experimental Collaborative Ethnography (PECE)

In 2015, we began contributing to PECE, an open source digital platform that supports multi-sited, cross-scale ethnographic and historical research.  PECE is built as a Drupal distribution that can be improved and extended like any other Drupal project.  Agaric's contributions include building an API integration between PECE's bibliographic citation capabilities and Zotero's open source reference management and collaborative bibliography tools.

We have been brought back for a larger role to realize the full upgrade of this distribution and platform to Drupal 10.

Partners In Health Drug Resistant Tuberculosis Network and EndTB.org

Beginning in 2010, Agaric took over the development of the DRTB Network platform for Partners In Health, the famed international nonprofit public health organization, and the TB Care II initiative.  The core of this work was connecting practitioners in the field with experts through a natural yet structured response process complete with careful editorial review.  This crucial work lives on with endTB.org, a partnership between Partners In Health, Médecins Sans Frontières, and Interactive Research & Development.  All of this work for PIH is in Drupal.

Science Collaboration Framework

Woman looking at linked documents.Agaric was the lead developer for the Science Collaboration Framework, a project of Harvard's Initiative in Innovative Computing. Working with researchers from Harvard University and Massachusetts General Hospital, we built a reusable platform for collaboration and communication in biomedical research, enriching the contributions of scientists and the biomedical online community with semantic data, highlighting advanced, structured relationships between contributed resources, and facilitating structured community discourse around biomedical research. We even earned a writeup in a scientific journal for our work!

As part of SCF, Agaric led the work of building the website for an online community of Parkinson's disease researchers and research investors, on the Science Collaboration Framework, for the Michael J. Fox Foundation for Parkinson's Research.

Ask Agaric for help building your world-bettering community today!

We have a number of processes and tools we use as we develop:

  • Local development: we all develop locally on our own computers and push each change to a common code repository which we maintain.

  • Each task including new features, bugs or changes are kept track of as an issue ticket. These tickets will be accessible to Urban Edge staff as well as ourselves. Here is where we can track progress in code changes, elaborate on details and generally where we keep track of the hundreds of small issues that will come up.

  • Resources allowing, we use automated tests which emulate a human's interaction with a browser to make sure new work we does not unknowingly break site functionality. This ensures a solidly functioning site even as major changes take place.

  • We have experience managing a wide range of servers, server environments, or specialized hosting environments, and related technologies:

    • We have written our own battle-tested server deployment code, which securely pushes changes in code to any target location.
    • Deployments can run manually or to a desired level of automation, such as always deploying to a staging website automatically on a successful build, and then manually progressing to live after review.
    • Our existing deployment tools can handle configuring a virtual (or physical) server from the ground up, or else function within a variety of PHP-based website hosting providers.
    • Additionally, we can support container-based environments by providing docker container configurations for running the required services.
    • Dependent upon the hosting platform, we also manage additional security and reliability features, such as sites having automated system updates, virus scans of uploaded files, custom backup schedules, additional firewall protections, monitoring services, or other customized needs.
    • We can also work alongside existing IT service providers with recommendations regarding things you may already manage, such as CDN (content delivery networks), email, or DNS (domain name) changes that may be needed.

Read more about our tools for environment management and development.