Inhalt abgleichen
Drupal.org - aggregated feeds in category Planet Drupal
Aktualisiert: vor 28 Minuten 13 Sekunden

ADCI Solutions: Why you should migrate your site to Drupal

17. November 2017 - 11:45

You probably would agree that Drupal is a universal solution for the most of the sites. Drupal handles huge content websites, runs simple landing pages. This CMS is used both by clients with limited budgets and those who invest a fortune into web apps. 

We - Drupalers of all kinds - know all the pros. But sometimes we need a reminder. Read this article about Drupal's advantages and reasons for migrating a site to this CMS.

 

Read it yourself and share with your clients and prospects.

 

ADCI Solutions: Why you should migrate your site to Drupal

17. November 2017 - 11:45

You probably would agree that Drupal is a universal solution for the most of the sites. Drupal handles huge content websites, runs simple landing pages. This CMS is used both by clients with limited budgets and those who invest a fortune into web apps. 

We - Drupalers of all kinds - know all the pros. But sometimes we need a reminder. Read this article about Drupal's advantages and reasons for migrating a site to this CMS.

 

Read it yourself and share with your clients and prospects.

 

ADCI Solutions: Why you should migrate your site to Drupal

17. November 2017 - 11:45

You probably would agree that Drupal is a universal solution for the most of the sites. Drupal handles huge content websites, runs simple landing pages. This CMS is used both by clients with limited budgets and those who invest a fortune into web apps. 

We - Drupalers of all kinds - know all the pros. But sometimes we need a reminder. Read this article about Drupal's advantages and reasons for migrating a site to this CMS.

 

Read it yourself and share with your clients and prospects.

 

ADCI Solutions: Why you should migrate your site to Drupal

17. November 2017 - 11:45

You probably would agree that Drupal is a universal solution for the most of the sites. Drupal handles huge content websites, runs simple landing pages. This CMS is used both by clients with limited budgets and those who invest a fortune into web apps. 

We - Drupalers of all kinds - know all the pros. But sometimes we need a reminder. Read this article about Drupal's advantages and reasons for migrating a site to this CMS.

 

Read it yourself and share with your clients and prospects.

 

ADCI Solutions: Why you should migrate your site to Drupal

17. November 2017 - 11:45

You probably would agree that Drupal is a universal solution for the most of the sites. Drupal handles huge content websites, runs simple landing pages. This CMS is used both by clients with limited budgets and those who invest a fortune into web apps. 

We - Drupalers of all kinds - know all the pros. But sometimes we need a reminder. Read this article about Drupal's advantages and reasons for migrating a site to this CMS.

 

Read it yourself and share with your clients and prospects.

 

ADCI Solutions: Why you should migrate your site to Drupal

17. November 2017 - 11:45

You probably would agree that Drupal is a universal solution for the most of the sites. Drupal handles huge content websites, runs simple landing pages. This CMS is used both by clients with limited budgets and those who invest a fortune into web apps. 

We - Drupalers of all kinds - know all the pros. But sometimes we need a reminder. Read this article about Drupal's advantages and reasons for migrating a site to this CMS.

 

Read it yourself and share with your clients and prospects.

 

ADCI Solutions: Why you should migrate your site to Drupal

17. November 2017 - 11:45

You probably would agree that Drupal is a universal solution for the most of the sites. Drupal handles huge content websites, runs simple landing pages. This CMS is used both by clients with limited budgets and those who invest a fortune into web apps. 

We - Drupalers of all kinds - know all the pros. But sometimes we need a reminder. Read this article about Drupal's advantages and reasons for migrating a site to this CMS.

 

Read it yourself and share with your clients and prospects.

 

ADCI Solutions: Why you should migrate your site to Drupal

17. November 2017 - 11:45

You probably would agree that Drupal is a universal solution for the most of the sites. Drupal handles huge content websites, runs simple landing pages. This CMS is used both by clients with limited budgets and those who invest a fortune into web apps. 

We - Drupalers of all kinds - know all the pros. But sometimes we need a reminder. Read this article about Drupal's advantages and reasons for migrating a site to this CMS.

 

Read it yourself and share with your clients and prospects.

 

ADCI Solutions: Why you should migrate your site to Drupal

17. November 2017 - 11:45

You probably would agree that Drupal is a universal solution for the most of the sites. Drupal handles huge content websites, runs simple landing pages. This CMS is used both by clients with limited budgets and those who invest a fortune into web apps. 

We - Drupalers of all kinds - know all the pros. But sometimes we need a reminder. Read this article about Drupal's advantages and reasons for migrating a site to this CMS.

 

Read it yourself and share with your clients and prospects.

 

ADCI Solutions: Why you should migrate your site to Drupal

17. November 2017 - 11:45

You probably would agree that Drupal is a universal solution for the most of the sites. Drupal handles huge content websites, runs simple landing pages. This CMS is used both by clients with limited budgets and those who invest a fortune into web apps. 

We - Drupalers of all kinds - know all the pros. But sometimes we need a reminder. Read this article about Drupal's advantages and reasons for migrating a site to this CMS.

 

Read it yourself and share with your clients and prospects.

 

ADCI Solutions: Why you should migrate your site to Drupal

17. November 2017 - 11:45

You probably would agree that Drupal is a universal solution for the most of the sites. Drupal handles huge content websites, runs simple landing pages. This CMS is used both by clients with limited budgets and those who invest a fortune into web apps. 

We - Drupalers of all kinds - know all the pros. But sometimes we need a reminder. Read this article about Drupal's advantages and reasons for migrating a site to this CMS.

 

Read it yourself and share with your clients and prospects.

 

Sooper Drupal Themes: Introducing 4 Theme Designs, 5 Glazed Builder Features And New Portfolio Tools

16. November 2017 - 22:31

We're super excited for you to have 4 smoking hot new designs as well as some awesome improvements to our Drupal 7 products! Our updates our available for download immediately!

4 Hot New Theme Designs

With our Drupal 8 development nearing completion we're making sure all our designs are looking their best and are ready for prime-time. SooperThemes is all about empowering users with top notch design and we produced 4 smoking hot new demos for Photography, (Drupal) Agency, App, and Marketing Agency websites.

Photography Drupal Theme Demo Photography Studio Homepage Photo Portfolio Homepage Minimal Gallery Homepage Material Design Portfolio Homepage Coverbox Homepage Full Screen Slider Homepage App Drupal Theme Demo App FAQ App Showcase View App Team and Testomonials iPhone X Mockup With Text (Drupal) Agency Drupal Theme Demo Agency Homepage Portfolio Features Services / Solutions About Us Marketing Agency Drupal Theme Demo Marketing Home Marketing Services About Us Showcase Gallery 5 New Glazed Builder Features Gradient Design Tool For Stunning Section Backgrounds

Design stunning, layered backgrounds for your sections without photoshop! All the beautiful multi-colored sections in our new App demo were made with Glazed Builder. Our gradient tool supports color transparency which means you can create stunning gradients and then blend them with patterns or photography to create mesmerizing designs. If it's your job to create engaging landing pages your job is now easier with Glazed Builder. 

We Listened: New Button To Add Sections Anywhere In Your Page

When landing pages get very long dragging new sections from the top of the page can become tedious. You complained and we listened! A popular request was to make the main Glazed Builder controls float and follow along with you when scrolling down the page. However, this solution can cause conflicts with other controls, and can become confusing when using nested Glazed Container. Instead we designed a new solution that is both clear and effective:  

Save Precious Time With Single Click Inline Editing

Glazed Builder is all about getting things done fast and with ease. Previously inline editing required 1 click to initialize the editor and a second click to place the cursor where you want to start typing. From now on the first click is not needed any more and you can click and type directly, saving you precious milliseconds and providing a more intuitive editing experience! 

Using External Images in Glazed Builder

Thanks to the fully featured media library integration managing images in Glazed Builder was already a great experience. However, we have now exposed the image url on all image widgets in Glazed Builder so that you can directly reference external images, without needing to import them to your media library. 

Vertical Centering Option On Sections

Sections already had a full width option and a full height option. We added a vertical centering option. Vertical centering was already possible using padding but since full height sections with centered text are now a popular design pattern we decided to add this option that makes a good companion to the already existing settings for full width and 100% height.

CMS Portfolio Module Revamped And New Module To Be Announced Tomorrow

For the production of our Photography demo we launched many new capabilities in our portfolio modules. The Glazed CMS Portfolio module previous offered just 2 displaying images: stacked images and thumbnails that link to a lightbox. We needed this component to be more flexible so that we can customize image display for different use cases. The result is a fusion between field formatters, views, and our portfolio images field. You can now use views to format the image field in portfolio pages. Furthermore, you can select any field formatter and view on a per-node basis as well. Our photography demo has a complete dropdown menu showcasing different variations (It's the Gallery Pages dropdown).

On top of that, we have dropped the MD Portfolio module from our products and wrote a new module from scratch for both Drupal 7 and 8. This new module is called SooperThemes Portfolio and will be the topic of another blog post tomorrow! If you're looking to update your website and it uses our portfolio modules it's recommended to wait for tomorrow's blog post.

As always, see our changelogs in the documentation section for a more complete list of changes and feel welcome to give us feedback in the comments! For bug reports please use our support forum.

roomify.us: Announcing BAT for Drupal 8

16. November 2017 - 20:29
The best open-source booking system builder is now available for the world-class Drupal 8 CMS.

Elevated Third: WATCH Elevated 3 Takeaways: Website Launch

16. November 2017 - 20:26
WATCH Elevated 3 Takeaways: Website Launch WATCH Elevated 3 Takeaways: Website Launch Joe Flores Thu, 11/16/2017 - 11:26

In this edition of 3 Takeaways, Joe Flores, Senior Drupal Developer, answers the question, "what happens during website launch?" From quality assurance to setting the domain name, this video clears things up. 

 

 

Hi everybody. My name is Joe Flores, I’m one of the senior developers here at Elevated Third and I’m here to talk to you about your website launch.

Website launch is the culmination of the entire design and dev process and there is a lot riding on the success of this part of the project. There are so many things that can go wrong during launch and here’s what we do to make sure things go as smooth as possible.

Takeaway #1: How launch is different from development

We’re not actually creating code. We are assuming the content of the website is finished and that there will be no major structural changes. This is to ensure that there are no conflicts between the dev server and live. At this point, we are assuming that content changes will only happen on the live website.

Takeaway #2: Configuration and testing

During the launch process your website will be moving on to a new server with more memory and storage space that we configure for security and speed. So we do things like changing admin password, enabling caching, disabling development workflow modules, and configuring marketing automation rules. We do all of this to make sure no one sees an unfinished product. So then, we perform one final QA to make sure everything is running.

Takeaway #3: The actual launch

We spend on average 2 days doing all this stuff to make sure launch is the easiest part of the process. By this point, we caught all big errors and ensured the site is secure. So all this part involves is setting the domain name. We did all the front loading to make sure the launch is smooth and this process only takes a couple of hours.

And that is your 3 takeaways for website launch.

Acro Media: Acro Media offering $4000 tuition subsidy towards College’s new Certificate

16. November 2017 - 18:32

As one of North America’s premier users of Drupal we have worked together with Okanagan College to develop a new Drupal Web Developer Certificate that will be offered weekday evenings beginning January 8, 2018.

We are so anxious to find coding talent that we are putting our own money on the line in hopes of addressing our HR recruitment challenges.

“We need great candidates for interesting and exciting CMS work in Kelowna and are looking forward to hiring graduates from this program,” says Shae Inglis, CEO of Acro Media. “In fact, Acro Media is going beyond just supporting the OC program. We are also sponsoring a contest to provide a $4,000 tuition award to a talented student who submits the best code sample before Dec. 15 for the January intake of the course. Contest details are available at www.acromedia.com/contest

“The Drupal Web Developer Certificate will give students the knowledge, practice and experience to find great jobs and careers in the Okanagan. This exciting Okanagan College and industry partnership has resulted in a program that will provide companies with highly qualified and work-ready graduates,” explains Dennis Silvestrone, Okanagan College’s Director of Continuing Studies and Corporate Training.

Taught by industry experts, this 240-hour Certificate will be offered at the Okanagan Innovation Centre in downtown Kelowna Mondays through Thursdays from 4:30 p.m. to 9:30 p.m. Students applying for the Drupal Web Developer Certificate are financial aid and student loan eligible.

For more information visit www.okanagan.bc.ca/drupal or call 1-888-638-0058 to learn more about qualifying for this Certificate.

Flocon de toile | Freelance Drupal: Change configuration directly on a Drupal 8 production site

16. November 2017 - 15:00
Managing native configuration with Drupal 8 makes it very easy to make changes or additions to the configuration from a site instance (such as a development environment) to another site instance (the production environment). These configuration exports and imports of a site are made in one piece: that is, the entire configuration of a site, which is updated. Thus if configuration additions have been made to the production site, they will be overwritten at the next import of the configuration if these configurations are not present also on the source environment. But there are valid use cases where certain configurations can and must be modified directly in production. Examples of immediate use are, for example, the creation of new Webform forms, or the creation or update of new Newsletters managed with the SimpleNews module. It is quite legitimate for a webmaster to modify or create new NewsLetters on the production site. It's almost like content, except that ... it's a configuration entity. Let's discover how to manage these particular cases with the module Configuration split, module that will allow us to maintain an organized process to manage the evolution and maintenance of a site in production while allowing the modification of some configurations live.

Dropsolid: ngrok: testing payment gateways in Drupal commerce

16. November 2017 - 10:15
16 Nov Testing payment gateways in Drupal commerce: ngrok to the rescue Marek Drupal 8 Tech

Building commerce websites always means building integrations. Every time we work on project that is aimed at selling something (products, subscriptions, paid access, etc.), we have to choose a payment provider that will take care of our transactions.

Almost every payment provider out there gives us the ability to test their services using some sort of testing or sandbox environment. This is a nice chance to fully test the checkout funnel and avoid stressful situations when deploying the application to a live environment.

While setting up commerce checkout flow locally, you’ll probably run into one (or all) of the following hiccups:

  • Issues with setting up a payments provider account,
  • No ability to parse incoming webhooks,
  • Problems with redirecting your customers back to the website.


The reason is simple: you’re hidden behind your NAT/firewall, so there is no way to reach your website from any remote server. As a workaround, you could probably create a manual payment method (for example bank transfer) and use this to browse all steps of your checkout flow. But you'll have to admit: this won't solve your main problem. Alternatively, you could clone your project to a remote environment, but is this always necessary? There has to be a better way to save time and keep working locally whilst keeping the full ability to test and debug remote services. Let’s have a closer look at how to wrap it all together with Drupal 8, Commerce 2 and a small tool called ngrok. In this example, I will be using the Mollie payments platform - scroll down to find out more! (Additional info about how to use Mollie and Drupal together in this post)

 

Download and set up ngrok

Ngrok is a very simple command line tool that allows you to expose a local web server to the internet. It takes only a few moments to set it up and its variety of configuration options is quite impressive (see the corresponding documentation).
 

Create ngrok account and download library files

Three easy steps:

  1. Simply visit ngrok.io and create a new account: https://dashboard.ngrok.com/user/signup
  2. Download and unpack the ngrok binary: https://ngrok.com/download
  3. Install your authtoken. Your personal account comes with its own token, which is available for reference via this link: https://dashboard.ngrok.com/get-started

When you get your token, locate the ngrok file and run the following command:

# ./ngrok {command} {param_is_a_token_conaining_lot_of_strange_chars_like_3Adacx$$321!} ./ngrok authtoken 5RpgRe8UA4qFWXtZoZb5P_3KeqMMsh6BjYMtWnJpgJt
Tune up your virtual host

Tune up the configuration of virtual host with the website you want to test by adding the server alias. For example, your apache2 vhost, with URL http://ngork.local, should have a *.ngrok.io alias, so you conf file should start like this:

ServerName ngrok.local ServerAlias *.ngrok.local *.ngrok.io Run ngrok

The very basic usage to start a simple HTTP tunnel goes like this:

# ./ngrok {command} {local_hostname}:{port} ./ngrok http ngrok.local:80
  • http command says start an HTTP tunnel
  • local_hostname argument says forward tunnel to this hostname
  • and port argument says listen on that port

After running the command, you will see ngrok up and running:

That should do the trick for now: you should be able to visit your page at URL provided by ngrok. The unfortunate thing about a free account is that every time you start a new tunnel, it creates a new URL. You can visit the ngrok web interface at http://127.0.0.1:4040 to check the status, incoming requests, connections, headers and much more.

 

Set up Commerce 2 / Drupal 8

Our test project needs a basic setup, with the following commerce 2.x modules turned on:

  • Commerce Checkout
  • Commerce Order
  • Commerce Payment
  • Commerce Price
  • Commerce Product
  • Commerce Store
  • Commerce Cart - not really required, but helpful to easily jump through the UI
  • Mollie Payment

Configure basics - set up you default store, product type etc. at the end your checkout flow will contain following panes:

 

Set up a Mollie payment account

Log in to the Mollie dashboard and jump to the Website profiles page, where you can create a profile or edit an existing one. Under contact information, provide the URL that is generated by your running ngrok process. Mollie will use it to send you all the webhooks:

Next, expand the Live end Test API keys pane to find the credentials that you need to configure the payment method in commerce. Install the Mollie Payment module and navigate to the Payment UI ( /admin/commerce/config/payment-gateways). Next, fill out the new payment method form with all the required details:

 

Test it...

That’s it! You can start with testing your payments, add any product to your cart and run through the checkout. After reviewing your order, you will automatically get redirected to the payment page, select any method and submit your transaction. For payment providers where you can define a full return URL and not only the domain - which is not the case with Mollie -, you can add XDEBUG_SESSION_START={YOUR-IDEKEY}, and start a debug session, as if you were working  on a regular local environment.

With ngrok up and running and your Mollie profile properly configured, you will get back to your local website. In the following few minutes, your local project should be receiving a bunch of webhooks. Whilst you wait for them coming in, you can preview your transactions in the Dashboard.

 

Key takeaways

Ngrok is definitely a great time-saver. It provides a lot of useful features and helps to resolve a variety of problems that you’ll often encounter during local development. In this article, I just demonstrated one example of its usage. It’s good to keep in mind that ngrok allows you to do much more:

  • Demoing - with ngrok running on your machine, you can share your local project with your teammates and clients
  • Insecure/mixed content check - with ngrok you can access your project via https:// which allows you to check insecure content warnings (no SSL needed!)   
  • Analysis - using the dashboard that is located at http://localhost:4040, you can inspect all requests/responses
  • Secure connection - you can secure your tunnel with a password  
  • Receiving webhooks - finally, you’re able to receive all webhooks and respond to them
  • Developing headless Drupal applications - while working locally you can expose your endpoints to your teammates ( check our article about Drupal 8 and React )

 

Drupal 8 is a really powerful and API-ready framework. It works very well together with lots of external services. Considering this, in addition to the never-ending technological progress, this flexible situation forces us to leave our self-created comfort zone and “I only use one tool” mentality. There are plenty of options to learn more about and use external tools, APIs and services. This provides a lot of flexibility, but, on the other hand, also requires some adaptation, has a learning curve and requires focus at every single stage of product development.

As developers - who don’t like mistakes, especially when payment integrations and real money are involved - we can’t afford to miss a beat here. Checkout funnels are leads that convert into real sales. They provide crucial business value to our clients and have to be extremely reliable; every payment needs to come through successfully. Testing your payment services through ngrok will allow you to stay in close control of your project, reduce stress and track down any issues before you spin up your application. It doesn’t take much time to set up, but the payoff is tremendous.

 

 

As always, you can discover more Drupal secrets on our blog. Automatic quarterly updates? Subscribe to our newsletter!

PreviousNext: Reusable style guide components using field formatters and twig embed

16. November 2017 - 4:32
Share:

At PNX, style guide driven development is our bag. It’s what we love: building a living document that provides awesome reference for all our front end components. And Drupal 8, with its use of Twig, complements this methodology perfectly. The ability to create a single component, and then embed that component and its markup throughout a Drupal site in a variety of different ways without having to use any tricks or hacks is a thing of beauty.

by Jack Taranto / 16 November 2017 Create a component

For this example we are going to use the much loved collapsible/accordion element. It’s a good example of a rich component because it uses CSS, JS, and Twig to provide an element that’s going to be used everywhere throughout a website.

To surmise the component it’s made up of the following files:

collapsible.scss collapsible.widget.js collapsible.drupal.js collapsible.twig collapsible.svg

The .scss file will end up compiling to a .css file, but we will be using SASS here because it’s fun. The widget.js file is a jQuery UI Widget Factory plugin that gives us some niceties - like state. The drupal.js file is a wrapper that adds our accordion widget as a drupal.behavior. The svg file provides some pretty graphics, and finally the twig file is where the magic starts.

Let’s take a look at the twig file:

{{ attach_library('pnx_project_theme/collapsible') }} <section class="js-collapsible collapsible {{ modifier_class }}"> <h4 class="collapsible__title"> {% block title %} Collapsible {% endblock %} h4> <div class="collapsible__content"> {% block content %} <p>Curabitur blandit tempus porttitor. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Morbi leo risus, porta ac consectetur ac, vestibulum at eros. Praesent commodo cursus magna, vel scelerisque nisl consectetur et. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.p> {% endblock %} div> section>

This is a standard-ish BEM based component. It uses a js-* class to attach the widget functionality. We also have a {{ modifier_class }} variable, that can be used by kss-node to alter the default appearance of the collapsible (more on this later). There are two elements in this component title and content. They are expressed inside a twig block. What this means is we can take this twig file and embed it elsewhere. Because the component is structured this way, when it’s rendered in its default state by KSS we will have some default content, and the ability to show it's different appearances/styles using modifier_class.

Our twig file also uses the custom Drupal attach_library function which will bring in our components CSS and JS from the following theme.libraries.yml entry:

collapsible: css: component: src/components/collapsible/collapsible.css: {} js: src/components/collapsible/collapsible.widget.js : {} src/components/collapsible/collapsible.drupal.js : {} dependencies: - core/jquery - core/drupal - core/jquery.once - core/jquery.ui - core/jquery.ui.widget

This is a pretty meaty component so it’s got some hefty javascript requirements. Not a problem in the end as it’s all going to get minified and aggregated by Drupal Cores library system.

And there we have it - a rich javascript component. It’s the building block for all the cool stuff we are about to do.

Use it in a field template override

As it stands we can throw this component as-is into KSS which is nice (although we must add our css and js to KSS manually, attach_library() won’t help us there sadly - yet), but we want drupal to take advantage of our twig file. This is where twigs embed comes in. Embed in twig is a mixture of the often used include, and the occasionally used extend. It’s a super powerful piece of kit that lets us do all the things.

Well these things anyway: include our twig templates contents, add variables to it, and add HTML do it.

Because this is an accordion, it’s quite likely we’ll want some field data inside it. The simplest way to get this happening is with a clunky old field template override. As an example I’ll use field--body.html.twig:

{% for item in items %} {% embed '@pnx_project_theme/components/collapsible/collapsible.twig' %} {% block title %} {{ label }} {% endblock %} {% block content %} {{ item.content }} {% endblock %} {% endembed %} {% endfor %}

Here you can see the crux of what we are trying to achieve. The collapsible markup is specified in one place only, and other templates can include that base markup and then insert the content they need to use in the twig blocks. The beauty of this is any time this field is rendered on the page, all the markup, css and js will be included with it, and it all lives in our components directory. No longer are meaty pieces of markup left inside Drupal template directories - our template overrides are now embedding much richer components.

There is a trick above though, and it’s the glue that brings this together. See how we have a namespace in the embed path - all drupal themes/modules get a twig namespace automatically which is just @your_module_name or @your_theme_name - however it points to the theme or modules templates directory only. Because we are doing style guide driven development and we have given so much thought to creating a rich self-contained component our twig template lives in our components directory instead, so we need to use a custom twig namespace to point there. To do that, we use John Albins Component Libraries module. It lets us add a few lines to our theme.info.yml file so our themes namespace can see our component templates:

component-libraries: pnx_project_theme: paths: - src - templates

Now anything in /src or /templates inside our theme can be included with our namespace from any twig template in Drupal.

Use it in a field formatter

Now let’s get real because field template overrides are not the right way to do things. We were talking about making things DRY weren’t we?

Enter field formatters. At the simple end of this spectrum our formatter needs an accompanying hook_theme entry so the formatter can render to a twig template. We will need a module to give the field formatter somewhere to live.

Setup your module file structure as so:

src/Plugin/Field/FieldFormatter/CollapsibleFormatter.php templates/collapsible-formatter.html.twig pnx_project_module.module pnx_project_module.info.yml

Your formatter lives inside the src directory and looks like this:

<?php namespace Drupal\pnx_project_module\Plugin\Field\FieldFormatter; use Drupal\Core\Field\FieldItemListInterface; use Drupal\Core\Field\FormatterBase; use Drupal\Core\Form\FormStateInterface; /** * A field formatter for trimming and wrapping text. * * @FieldFormatter( * id = "collapsible_formatter", * label = @Translation("Collapsible"), * field_types = { * "text_long", * "text_with_summary", * } * ) */ class CollapsibleFormatter extends FormatterBase { /** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode = NULL) { $elements = []; foreach ($items as $delta => $item) { $elements[$delta] = [ '#theme' => 'collapsible_formatter', '#title' => $items->getFieldDefinition()->getLabel(), '#content' => $item->value, '#style' => NULL, ]; } return $elements; } }

And the hook_theme function lives inside the .module file:

<?php /** * @file * Main module functions. */ /** * Implements hook_theme(). */ function pnx_project_module_theme($existing, $type, $theme, $path) { return [ 'collapsible_formatter' => [ 'variables' => [ 'title' => NULL, 'content' => NULL, 'style' => NULL, ], ], ]; }

Drupal magic is going to look for templates/collapsible-formatter.html.twig in our module directory automatically now. Our hook_theme template is going to end up looking pretty similar to our field template:

{% embed '@pnx_project_theme/components/collapsible/collapsible.twig' with { modifier_class: style } %} {% block title %} {{ title }} {% endblock %} {% block content %} {{ content }} {% endblock %} {% endembed %}

Now jump into the field display config of a text_long field, and you’ll be able to select the collapsible and it’s going to render our component markup combined with the field data perfectly, whilst attaching necessary CSS/JS.

Add settings to the field formatter

Let's take it a bit further. We are missing some configurability here. Our component has a modifier_class with a mini style (a cut down smaller version of the full accordion). You'll notice in the twig example above, we are using the with notation which works the same way for embed as it does for include to allow us to send an array of variables through to the parent template. In addition our hook_theme function has a style variable it can send through from the field formatter. Using field formatter settings we can make our field formatter far more useful to the site builders that are going to use it. Let's look at the full field formatter class after we add settings:

class CollapsibleFormatter extends FormatterBase { /** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode = NULL) { $elements = []; foreach ($items as $delta => $item) { $elements[$delta] = [ '#theme' => 'collapsible_formatter', '#title' => !empty($this->getSetting('label')) ? $this->getSetting('label') : $items->getFieldDefinition()->getLabel(), '#content' => $item->value, '#style' => $this->getSetting('style'), ]; } return $elements; } /** * {@inheritdoc} */ public function settingsSummary() { $summary = []; if ($label = $this->getSetting('label')) { $summary[] = 'Label: ' . $label; } else { $summary[] = 'Label: Using field label'; } if (empty($this->getSetting('style'))) { $summary[] = 'Style: Normal'; } elseif ($this->getSetting('style') === 'collapsible--mini') { $summary[] = 'Style: Mini'; } return $summary; } /** * {@inheritdoc} */ public function settingsForm(array $form, FormStateInterface $form_state) { $form['label'] = [ '#title' => $this->t('Label'), '#type' => 'textfield', '#default_value' => $this->getSetting('label'), '#description' => t('Customise the label text, or use the field label if left empty.'), ]; $form['style'] = [ '#title' => t('Style'), '#type' => 'select', '#options' => [ '' => t('Normal'), 'collapsible--mini' => t('Mini'), ], '#description' => t('See Styleguide section 6.1 for a preview of styles.'), '#default_value' => $this->getSetting('style'), ]; return $form; } /** * {@inheritdoc} */ public static function defaultSettings() { return [ 'label' => '', 'style' => '', ]; } }

There's a few niceties there: It allows us to set a custom label (for the whole field), it automatically assigns the correct modifier_class, it links to the correct section in the style guide in the settings field description, and it adds a settings summary so site builders can see the current settings at a glance. These are all patterns you should repeat.

Let's sum up

We've created a rich interactive BEM component with its own template. The component has multiple styles and displays an interactive demo of itself using kss-node. We've combined its assets into a Drupal library and made the template - which lives inside the style guides component src folder - accessible to all of Drupal via the Component Libraries module. We've built a field formatter that allows us to configure the components appearance/style. Without having to replicate any HTML anywhere.

The component directory itself within the style guide will always be the canonical source for every version of the component that is rendered around our site.

Tagged Twig

Posted by Jack Taranto
Front end developer

Dated 16 November 2017

Add new comment

DrupalEasy: DrupalEasy Podcast 198 - Dave Hall - Drupal Distributions and Puppies

16. November 2017 - 2:53

Direct .mp3 file download.

Dave Hall (skwashd), Managing Director, Dave Hall Consulting joins Mike Anello to talk about the current state of Drupal distributions and what the future may hold.

Interview DrupalEasy News Sponsors
  • Drupal Aid - Drupal support and maintenance services. Get unlimited support, monthly maintenance, and unlimited small jobs starting at $99/mo.
  • WebEnabled.com - devPanel.
Follow us on Twitter Subscribe

Subscribe to our podcast on iTunes, Google Play or Miro. Listen to our podcast on Stitcher.

If you'd like to leave us a voicemail, call 321-396-2340. Please keep in mind that we might play your voicemail during one of our future podcasts. Feel free to call in with suggestions, rants, questions, or corrections. If you'd rather just send us an email, please use our contact page.

Mediacurrent: Content as the Common Language of Web Development

15. November 2017 - 21:21

If there’s one thing I learned while attending DrupalCon Baltimore 2017 this past spring, it’s that those of us involved in building the web are only getting more and more specialized in how we help build it. It boggles the mind to witness the sheer amount of new session tracks, new technologies, new design patterns, and new discussions that come up each year at DrupalCon.