Skip to main content

Blog

There are plenty of ways—all right, too many ways—to create links when using modern Drupal (Drupal 8 and above, so including so far Drupal 9, Drupal 10, and Drupal 11).  We will share some of those ways in this regularly-updated post.  (Latest update: 2024 April 22)

The easiest way to create internal links is using Link::createFromRoute

And it is used like this:


use Drupal\Core\Link;
  $link = Link::createFromRoute('This is a link', 'entity.node.canonical', ['node' => 1]);

Using the Url object gives you more flexibility to create links, for instance, we can do the same as Link::createFromRoute method using the Url object like this:


  use Drupal\Core\Link;
  use Drupal\Core\Url;
  $link = Link::fromTextAndUrl('This is a link', Url::fromRoute('entity.node.canonical', ['node' => 1]));

And actually Link::fromTextAndUrl is what Drupal recommends instead of using the deprecated l() method. Passing the Url object to the link object gives you great flexibility to create links, here are some examples:

Internal links which have no routes:


$link = Link::fromTextAndUrl('This is a link', Url::fromUri('base:robots.txt'));

External links:


$link = Link::fromTextAndUrl('This is a link', Url::fromUri('http://www.google.com'));

links with only the fragment (without url) :


$link = Link::fromTextAndUrl('This is a link', Url::fromUri('internal:#fragment'));

Using the data provided by a user:


$link = Link::fromTextAndUrl('This is a link', Url::fromUserInput('/node/1');

The param passed to fromUserInput must start with /,#,? or it will throw an exception.

Linking entities.


$link = Link::fromTextAndUrl('This is a link', Url::fromUri('entity:node/1'));

Entities are a special case, and there are more ways to link them:


$node = Node::load(1);
$link = $node->toLink();
$link->setText('This is a link');

And even using the route:


$link = Link::fromTextAndUrl('This is a link', Url::fromRoute('entity.node.canonical', ['node' => 1]));

Drupal usually expects a render array if you are going to print the link, so the Link object has a method for that:


$link->toRenderable();

which will return an array.

Linking files.

Files are entities also in Drupal but a special kind.  You usually do not want to link to the entity but directly to the uploaded file.  To do that, do not use $file->getFileUri() but rather instead use createFileUrl() which will directly give you a complete string version of the URI:


$url = $file->createFileUrl();

This URL can then be used in making a link with regular HTML or the External links approach covered above.

Credit to godotislate in Drupal Slack support channel for this tip.

Final tips:

Searching a route using Drupal Console

The easiest way to find the route of a specific path is using Drupal Console, with the following command.


$ drupal router:debug | grep -i "\/node"

That will return something like:


entity.node.canonical                                 /node/{node}
 entity.node.delete_form                               /node/{node}/delete
 entity.node.edit_form                                 /node/{node}/edit
 entity.node.preview                                   /node/preview/{node_preview}/{view_mode_id}
 entity.node.revision                                  /node/{node}/revisions/{node_revision}/view
 entity.node.version_history                           /node/{node}/revisions
 node.add                                              /node/add/{node_type}
 node.add_page                                         /node/add
 node.multiple_delete_confirm                          /admin/content/node/delete
 node.revision_delete_confirm                          /node/{node}/revisions/{node_revision}/delete
 node.revision_revert_confirm                          /node/{node}/revisions/{node_revision}/revert
 node.revision_revert_translation_confirm              /node/{node}/revisions/{node_revision}/revert/{langcode}
 search.help_node_search                               /search/node/help
 search.view_node_search                               /search/node
 view.frontpage.page_1                                 /node

Listing all the possible routes with that word, we can choose one and do:


drupal router:debug entity.node.canonical

And that will display more information about a specific route:


 Route             entity.node.canonical
 Path              /node/{node}
 Defaults
  _controller      \Drupal\node\Controller\NodeViewController::view
  _title_callback  \Drupal\node\Controller\NodeViewController::title
 Requirements
  node             \d+
  _entity_access   node.view
  _method          GET|POST
 Options
  compiler_class   \Drupal\Core\Routing\RouteCompiler
  parameters       node:
                     type: 'entity:node'
                     converter: paramconverter.entity

  _route_filters   method_filter
                   content_type_header_matcher

  _route_enhancers route_enhancer.param_conversion

  _access_checks   access_check.entity

So in this way we can search the route without the needing to search in all the *.routing.yml files and in this example the route is entity.node.canonical and the param expected is node.

Print links directly within a twig template

It is also possible to print links directly on the twig template with the following syntax:

<a href="{{url('entity.node.canonical', {'node': node.id( ) }}"> {{ 'This is a link'|t }} </a>

Add links inside a t() method.

If you want to add a link inside the t() you can do what Drupal suggests on Dynamic or static links and HTML in translatable strings:


use Drupal\Core\Url;
$url = Url::fromRoute('entity.node.canonical', ['node' => 1]);
$this->t('You can click this <a href=="@link">Link</a>', ['@link' => $url->toString()]);

 

Image credit: "Anti-Muslim Ban Protests" by Mrs. Gemstone is licensed under CC BY-SA 2.0.

Stay in touch

Drutopia Features

Actions

An action is a call for concrete work from supporters. It can stand on its own or be part of a campaign. It can have a goal and due date set. For example, a call for 50 people to call a prison by June 13th demanding an investigation into prisoner abuse. An action can also be turned into a fundraiser, allowing people to donate directly to the site through Stripe. No longer will groups be dependent on proprietary platforms such as GoFundMe and IndieGoGo.

Articles

Drutopia provides an article content type and related configuration, including article types (such as "Victories" or "Press releases") and topics which span all kinds of content on the site (such as "Tenant organizing" or "Environmental racism").

Blog Posts

Drutopia provides the blog content type and related configuration, ideal for giving individuals or groups more informal voices distinct from the organization as a whole.

Campaigns

A campaign page is a central place to explain an issue, publish updates about its activity, list out demands, post calls to action, and raise funds.

Groups

  • Groups broadcast to supporters their activity and ways to support.
  • Each group has a page within the website. A group can launch a campaign, call for an action and publish a news article.
  • All of these pieces of content are displayed on a group's page, creating a mini-site.

Profile Pages

Drutopia provides a People content type for showing visitors information about staff, volunteers, contributors, and more.

The Drutopia Initiative

The Drutopia initiative lays out a technique for configuring a Drupal distribution, for the commons.  It is a recognition and a reflection in software architecture that liberation requires organizing and collective action. We ask you not to sit back and let Drutopia work its magic, but rather to stand up and, with us, build a cooperative of grassroots organizations that work together to build tools that we can own together.

Core values of the Drutopia initiative:

  • Be inclusive regarding gender, gender identity, sexual orientation, ethnicity, ability, age, religion, geography, and class.
  • Commit to protection of personal information and privacy and freedom from surveillance
  • Value collaboration and cooperation above competition
  • Prioritize human needs over private profit
  • Foster non-hierarchical structures and collective decision-making

Drutopia encourages:

  • Users and adopters to pool their resources and take a lead role in prioritizing and crowdfunding new development
  • Designers, site builders, and developers to focus on rolling their work into shared solutions available to everyone, heightening the ability of groups of all stripes and sizes to benefit.

Strategy - Shared Configuration Management

Drutopia focuses on a specific use case for websites — grass-roots organizing — and pioneers an elegant model for reducing the costs of maintaining an individual Drupal site by providing a shared base configuration for a collection of websites that are run by various organizations with similar needs that contribute to the development cooperatively.

Learn more specifics about the cooperative development strategy behind Drutopia by reading the Drutopia White Paper.

Drutopia as a LibreSaaS or Platform Cooperative

We believe that the platforms that influence and affect so much of our lives (think Facebook and Google) should be owned by the people who use them. In the same line of thinking, the potential of the Drutopia configuration framework is truly unleashed as fully hosted, member-owned platforms. Members of the platform cooperatives will drive forward the vision of the project from the perspective of those most affected– shaping the development of new features. The platforms themselves can span multiple participating hosts that endorse and follow the hosted Drutopia standards.

Contribute to the Drutopia Initiative

Drutopia is a fully functional content management system apart from all these goals, and there are a few ways different individuals and organizations can contribute to this initiative:

1) Drutopia as a Drupal distribution that can be self-hosted by anyone, but the software project will be democratically governed by members of the Drutopia cooperative. For as little as $10 a year you can become a member who votes in leadership team elections, suggests features for the development roadmap, and is part of a community that is building tools for the grassroots.

2) Non-profits and other organizations that pay Chocolate Lilly or Agaric to build a Drutopia website for their organizing will be contributing to our development efforts, and helping us to move forward in attaining the goals of the Drutopia initiative.

3) Individuals and groups that recognize needs for specialized Drupal distributions should talk to us. We encourage you to reach out and bring together others that share the same needs, so that we can collectivize the development and maintenance of more Drutopia distributions. 

Cooperative Webhosting

Staying true to the core values of Drutopia, we hosting your site through, and include membership in, democratically governed May First Movement Technology cooperative.  May First is dedicated to supporting organizers and activists by providing tools and services that protect their data and privacy from governments and corporations.

Vestibulum iaculis consectetur convallis. Donec sit amet congue massa. Quisque nec eros eu dolor posuere fermentum et vel nulla. Donec mollis leo sit amet egestas vulputate. Etiam eget ante ante. Proin dignissim justo vel nibh tincidunt, a porta dui tincidunt. Ut varius, metus ac luctus molestie, turpis magna ultricies lectus, at ornare tellus diam sit amet risus. In hac habitasse platea dictumst. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus neque dui, placerat ac massa nec, rutrum rhoncus ex. Sed ut posuere urna.

Agaric, as a worker collective, does not have bosses and employees. We have skilled, hard-working teammates coming together to figure out and do ... everything.

We will make an exception to hire an excellent business director, project leader, attention-to-detail-and-the-big-picture person. If you happen to be a front end dev too, then great! If not, well, part of your role will be helping bring on more talent.

In addition to forging grand coalitions and leading amazing projects, we need help keeping track of invoices and payments and doing financial planning, managing people's skills and availability, and writing role descriptions way better than this one.

We want someone who expects within six months of joining us to have helped make things 300% more awesome. As a principal or a hired boss, part of this role will be making the decisions of what to prioritize, and saying no to potential projects that don't fit.

OK we'll just say it: We want someone to be Agaric's Liza Kindred.

Want to be part of something that's bigger than yourself, that works on projects and ideas bigger still?

Agaric's model is Free and Open: free and open standards, free and open work and management, free and open source code, free and open documentation. So be prepared to help us share everything we build, as a collective company and with code, to the Drupal community and beyond.

Agaric is not just about doing web work as a collective. We work on interesting, exciting projects (both client work for solid financial compensation and our own platform-building initiatives for dreams of riches). We then, also collectively, take some of the resources, skills, and connections we gain in this work to help build tools, networks, and open learning projects that change the world for the better. We see tremendous potential for a better world by helping people gain more control over their own lives, and open source free software is both a metaphor and a tool for how we can better lives.

We welcome serious and/or comical inquiries.

2017 was an amazing year for me. I met so many people, attended lots of events, presented a good amount of sessions and trainings, and traveled like never before. I got to interact with the Drupal community in many ways. And I learned so much, both technical and life lessons. Let me share a summary of my year.

To make the text compact I will use some abbreviations in the text. DC for DrupalCamp and GTD for Global Training Days. Meetups refers to local user groups meetings.

Events per month

This translates to:

  • 18 conferences
  • 9 meetups
  • 12 DrupalCamps
  • 2 DrupalCons
  • 1 Drupal DevDays
  • 12 sessions presented
  • 4 trainings presented
  • 6 GTD workshop presented

Highlights this year

Thank you all

Thanks to my colleagues at Agaric for their support during my Drupal tour.

Thanks to all the event organizers who gave me the opportunity to speak at their events. And thanks to all the people who gave feedback of my sessions, trainings, and workshops.

Thanks to Baddý Breidert, Hilmar Hallbjörnsson, and all the team who organized Northern Lights DrupalCamp. They went above and beyond to pull out an event against unfavorable conditions. The night before the sessions fell a record breaking amount of snow. The organizers went to pick people up from around Reykjavik and accommodated the schedule nicely. I was trapped in a bus stops, with snow above my knees, when Hilmar and Christoph Breidert picked me up saved me and took me to the venue. On top of everything, the organizers took everyone on free tours around beautiful Iceland. It was amazing!

Thanks to all the people and organizations who set up different events where I could present during my European tour. Cristina Chumillas (Barcelona), Baddý and Christoph of 1xINTERNET (Frankfurt), Valery Lourie and the SynergyCamp team (Sofia), Sven Decabooter and the DC Antwerp team (Antwerp), Ignacio Sánchez (Madrid), and Chandeep Khosa and Gabriele (gambry) (London).

Thanks to those who hosted me during my European tour. Baddý and Christoph of 1xINTERNET in Frankfurt, my colleague Stefan Freudenberg in Hamburg, and Rodrigo Aguilera in Barcelona. They opened the doors to their homes and their families during my stay. I will always be grateful.

Thanks to Anna Mykhailova for co-presenting a training with me at BADCamp.

Thanks to the awesome organizing team of Lakes and Volcanoes DC. In particular to Lucas Hedding who has helped the Nicaraguan Drupal community in countless ways.

Thanks to the Boston Drupal user group for making me feel at home every time I visit.

Thanks to ALL the people I talked to during the 2017 Drupal tour. The Drupal community is super friendly and welcoming. It is so great to be part of it.

Trivia

Zsófi Major sent a t-shirt to Christian López. In its way from DC London to Drupal DevDays Seville, the t-shirt stopped by 9 airports.

V Spagnolo sent a present to Lucas Hedding. In its way from DrupalCon Vienna to Nicaragua, the parcel stopped by 10 airports.

The GTD in Frankfurt was super interesting. I installed Drupal in German. Not knowing the language, I had no idea how to pronounce the text on the screen. The audience was very kind in helping me. By the end of the workshop I was pronouncing some words almost right. ;)

What's next for 2018?

As my fellow drupaler Eduardo (enzo) García says in his end of year recap, travelling takes a lot of energy. I have plans to attend some events in 2018, but not as much as I did in 2017. While staying at home, I will be able to accomplish things that would be difficult otherwise.

I will kickstart my Drupal learning project: understanddrupal.com My goal is to teach Drupal in multiple languages and multiple formats. To start I will produce content in English, Spanish, and French in text and video formats.

I will learn new languages. On the human side, I will start with French and I might give German a try. On the computer side, I will start with JavaScript and then move to Python. At Agaric we serve clients in multiple countries and with different application stacks. Learning new human and computer languages will help me serve better the clients and projects I participate in.

I want to learn new things. Software testing in general and creating applications in React are my first targets. Expect blog posts about my learnings next year.

I want to participate more actively in the free software communities in my country. Drupal, WordPress, JavaScript, and others. I would like to learn from them and share what I have learned in my travels.

Thanks for a fantastic 2017! See you in 2018! :D

Hear from us

Keegan is a Web Developer, focused mostly on building sites using Drupal and/or front-end JavaScript frameworks (like React.js), and is also a Drupal core contributor.

Keegan's longest-lived hobbies are being in nature, sonic-doodling, and studying the history and philosophy of science and technology. Having a degree in Environmental Science and Technology, Keegan learned early that there is no deficiency in the capabilities of modern technology to create a more equitable and sustainable global infrastructure, but a lack of funding. Hence, Keegan believes that the future of societal health depends on collective efforts to provision and employ information and communications infrastructure that is owned and controlled by the people who use it—not by the full-fledged military contractors that big tech comprises—so that love, democracy, community, and eco-friendly infrastructure can thrive.

Keegan is inspired, as a worker-owner of a tech coop, to have recognized the practical benefits of Libre software and of the cooperative model toward the respective protection and cultivation of attentional liberation, and is always beyond delighted to hear whenever someone else has made the same or similar discoveries. Most of all, Keegan is humbled to be immersed in a positive work-culture that emphasizes action-oriented ethical practices, and to be surrounded day-to-day by brilliant friends and mentors.

Ben spoke most recently on this topic at DrupalCon Seattle and Drupal Camp Twin Cities, both in 2019, about how Drupal as a Service can save our livelihoods and our lives.  Here are some resources related to the talk and topic.

A graphic of the earth engulfed in flames.

The Earth is not dying, it is being killed, and those who are killing it have names and addresses.

Utah Phillips

As far as i can tell, the Internet hasn't sourced that quotation, but no one challenges that it was Phillips— and i thought i heard him say about the same thing on the radio, in a broadcast where he also slammed NPR, boosting community radio and, if needed, the do-it-yourself be-the-media ethos.  Maybe i'm part of a collective delusion, in which case, i'm sure Utah Phillips wouldn't care one way or another so long as we got on with working for the liberation of humanity and preserving life on planet Earth as part of that.

Sources cited

Crowd-sourcing this on Mastodon (itself interestingly compatible with LibreSaaS with instances like social.coop working on governance models, if not yet having the revenue to cover hosting, let alone contribute back to development:

Hello fediverse, what online tools do you know about that are LibreSaaS— you can pay to use them, but the full stack is free/libre open source software so you or others can totally host the entire thing yourself if you want?

I added whichever answers i didn't already have to the LibreSaaS list pad.

Tech Won't Build It

We'll keep looking for ways that cooperation can save us all (and technology can help) so sign up to get (extremely occasional, less than once a year) updates.

To learn more about the cooperative movement, visit the US Federation of Worker Owner Cooperatives.

Learning Objectives

  • Understand the different approaches to upgrading your site to Drupal 9 using the Migrate API.
  • Revise site architecture and map configuration from the previous site to the new one
  • Use the Migrate Drupal UI module to understand module requirements for running upgrades.
  • Use the Migrate Upgrade module to generate migration files.
  • Cherry-pick content migrations for getting a content type migrated to Drupal 9.
  • Modify a migration to convert a content type to a user entity.
  • Modify a migration to convert a content type to a paragraph entities.
  • Migrate images to media entities.
  • Learn about writing a custom process plugin for providing a migrate path for modules that do not include one already.
  • Tips and recommendations upgrade projects.

Prerequisites

This is an advanced course that requires familiarity with the Drupal migration concepts. Our Drupal 9 content migrations training will give you all the background knowledge that you need. Alternatively, you can read the 31 days of migrations series in our blog or watch this video for an overview of the Migrate API.

Setup instructions

Having a Drupal 7 and Drupal 9 local installation is required to take this course. We offer this repository with a virtual machine configured with the two Drupal installations used in the training. Alternatively, you can use a tool like DrupalVM, Lando, DDEV, or Docksal. You will have to be able to restore a MySQL database dump containing the Drupal 7 database. Drupal 9 site needs to be able to connect to the Drupal 7 database. Drush needs to be installed in order to run migrations from the command line.

This training will be provided over Zoom. You can ask questions via text chat or audio. Sharing your screen, but you might want to do it to get assistance on a specific issue. Sharing your camera is optional.

What to expect

Rocket launch

Prior to the training

Attendees will receive detailed instructions on how to setup their development environment. In addition, they will be able to join a support video call days before the training event to make the the local development environment is ready. This prevents losing time fixing problems with environment set up during the training.

On the days of the training

  • The training totals 7 hours of instruction, which we usually split into 2 sessions.
  • A team of developers available to answer questions and help with training-related issues.

After the training

  • Attendees will receive copies of the training recordings.
  • Attendees will receive a free copy of the 31 days of migrations book.
  • Attendees will receive a certificate of completion.

Blog

Come to the Healthcare Summit at DrupalCon 2024 next week in Portland, Oregon!

Join us for an interactive day devoted to Drupal in healthcare— a relaxed and friendly close to DrupalCon with learning, networking, and discussing.  Whether you are in a pharmaceutical company, a state department of health, a non-profit hospital, a public health organization, or anyplace else in the broad healthcare space, there are unique needs in ensuring security, accessibility, compliance, and availability of important information and tools.

Upload media inline in WYSIWYG editor in modern Drupal 10+ with CKEditor5

It seems like the best practice is that we should try to use the media manager rather than just drop in photos using the text editor method (which doesn't seem to get the photos into the media library), but how do we get the photos in the media library to be able to wrap with text and not be visually separate content?

A large lower case letter i surrounded by tiny words.

Display lists naturally with the In Other Words module for Drupal

It is common for a Drupal site to list multiple items. It could be several authors of a single article, the days that a recreation center is open, or the flavors an ice cream parlor serves. Clean, structured data is a strong point of Drupal, but the display of that structured content is limited. That is why Agaric, with support from DevCollaborative, made In Other Words, a Drupal module that gives site builders the power to configure precise and natural ways to display lists of items.

Micky Metts speaking in a webinar with the Center for Global Justice.

Did the Internet make you a criminal? How can it be proven?

Let's explore digital threats and solutions, including Internet Access, Big Data, and Surveillance Capitalism. Discover how the data collected by big tech can be used to incriminate you and learn practical tips to enhance online privacy. Explore ethical considerations and challenges posed by emerging technologies like AI and social media. Gain a deeper understanding of online privacy and learn to navigate the digital world confidently while protecting your personal information effectively.

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!

Dan left Agaric in 2011 to go forth on his own, leaving behind some famous quotations:

Like a nine-year-old in high school.

And:

That's why you'll be a small seller of custom drupal pretzels...