25. August 2019

Using Linux as a Fulltime Drupal Developer

I'm a full time Drupal developer at Code Koalas a mostly Drupal shop based out of Kansas City, and I use Linux as my full time desktop environment. I started playing with Linux as early as 2008 when I download Ubuntu 8.04 Hardy Heron to get away from Windows Vista on my desktop computer that wasn't good enough to properly run Vista. I had also installed it on some old laptops for fun or friends and obviously had and used many Linux servers for work and fun but it never stuck for my desktop until 2017 when I installed Arch Linux on my work laptop a 2015 MacBook Pro. No this isn't simply a "I use Arch BTW" post, though I do use Arch and suggest that or Manjaro for people over Ubuntu for reasons, I hope to show the reasons I choose Linux in the first place and why it's still what I use today.

A Better Window Manager

On Mac windows just float wherever they like, and though I am a fan of their multiple spaces and swiping between them there is always just a mess of windows everywhere. For work I at a minimum always have at least have the following open; Firefox, Slack, a terminal, and PHPStorm. In that I might have multiple tabs and windows of both Firefox and the terminal open. So I'm at a minimum of four windows but probably more like six plus. I don't like using Apple's full screen mode (not sure why, I'm just picky) but my programs are pretty much always full screened. So I was having to use gestures all the time swiping every which way to get to the window I wasted to keep working.

I started using Phoenix which is an i3 like Window manager for Mac to give you keyboard shortcuts to move windows and make them sticky, it worked but wasn't exactly what I needed. I didn't want something like i3 that is a hack on top of Mac's window manager I just wanted i3.

So Why i3?

Mostly I decided I needed a Tiling Window Manager. A Tiling Window Manager is a window manager with an organization of the screen into mutually non-overlapping frames, as opposed to the more popular approach of coordinate-based stacking of overlapping objects. That means that windows never overlap each other, they all get their own place on the screen in a nice orderly way. I choose i3 over some of the other window managers because I knew someone with that and they were willing to share their config with me.

With i3 I was now able to press a command to open Rofi and open any program I wanted (Think Macs Spotlight), press a key combination to move a window to a different screen or workspace, have windows always fall into the place I expected them to, and press a key combination to move workspaces. Now I can work mostly with my hands staying on my keyboard and I don't have to click around all day and swipe my fingers to find the windows I want. If you too would like to get started with i3 you can take a peak at my dotfiles repo with my config in it.

I have now switched away from i3 to Sway for reasons but Sway aims to be a drop in replacement for i3 so configs can be shared but it out of the box does a lot of things nicer and runs on Wayland instead of X.

Faster Local Development

Like a lot of people in 2019 we run all of our sites on Docker, and have been for the past couple years. Docker is great and has made my life so much easier. At Code Koalas we don't just run Docker on our servers for live sites we also run those same Docker containers locally to build our sites. The great thing about this is that everyone is running the same version of PHP and has things setup the way that the stage and prod environments do. The bad thing about this is Docker for both Windows and Mac is terribly slow and buggy. Docker is meant to run on Linux servers so it runs best there and everywhere else it works but not well. Running Linux as my desktop computer means that I have the same great version of Docker running millions of services on my computer running my local sites.

Many coworkers message me asking "do you know what this container error means" with their local containers getting blown up. I'm not going to say I never have had issues but I know I haven't even had 1/10th the amount of Docker issues people on Macs have had.

How much faster?

This isn't a super scientific answer with rigorous testing but on my 2015 MacBook Pro clearing the cache on a Drupal site while on linux generally takes around one minute to around a minute and fifteen seconds. A coworker using the same model MacBook Pro but on Mac takes over three minutes to clear the cache. This is us using the time command in terminal before our drupal cr all command, and ran multiple times so in our testing Docker on Linux in three times as fast. Now that I upgraded to a custom build desktop computer at work running Linux my cache clears and 15 - 20 seconds.

Made Me A Better Dev

One of the great things about using Arch Linux and Sway is that I'm in the terminal a lot to manage a lot of computer services. Yes there are GUI for a lot of things but I personally prefer the terminal and when I'm managing remote servers all I have is a terminal anyways. I'm now way more comfortable poking around on servers trying to figure out what went wrong with them or turning on extra PHP extensions that we are missing. I now can tar a directory without having to look it up online. I also now look at the git repos of most projects I use on my computer and have seen at least a little bit of the code that goes into making the software I use daily work.

There isn't one specific thing I can point to with using Linux that made me the developer I am today but since I made the switch I'm way more knowledgeable than I used to be.

Is it really all good? Short answer no

Nothing is perfect, not every part of using Linux has been easy and great. Yes I have bricked my computer before, but I also did that on my Mac with a bad regex find and replace. Yes an update made a certain program not open anymore or function at all, but a Windows update made people lose all their info in their User folders.

The only real issue I have is I cannot use Adobe products, there have been hacks in the past that make them work but none seem to work right now. To me it's not that big a deal because when a client gives us designs in Photoshop I can always look at a JPG preview of it for general ideas and either open it or my old MacBook Pro or open it in a VM on my main computer. It's not a great solution but it's a small part of my job and Linux made the main part of my job way better so it works out. No GIMP is not the solution, I don't make the designs I open them and GIMP, though it's great, doesn't always render them right so I then build things that aren't actually part of the design but a GIMP mess up.

Conclusion

Is Linux for everyone? YES, I mean no, err maybe? Linux has been great for me and I'm not leaving anytime soon but I understand why some people don't make the jump. If you have every been curious or are finally getting frustrated on Windows or Mac give Linux a try, you might just like it enough to stay.

04. August 2019

Weeknotes #6

It's been a hot minute or two since I've updated things here, life is busy sometimes.

I added two new pages to the site, one of games I've played and whether I recommend the game or not, and one of ongoing projects I'm working on. Nothing complicated yet or even completely filled out but it expands my site beyond just random blogs.

[Quick Life Things]

  • †My van broke, then I fixed it, then it broke again in a different and worse way. (currently still broken)
  • Started building a divider wall in my garage to move my home office in there so the baby can take my office room.

[Play]

Throw Throw Burrito this game is great! It's easy to learn and fun to play. It's a fast pace match making card game, where sometimes people throw burritos at each other. We played at work and it resulted in people running and jumping over couches throwing burritos at each other.

Trogdor!! The Board Game that came in last week, I've only played it once but it was pretty fun and cooperative.

Ravine this is a card game I backed on Kickstarter awhile ago but just started playing in a last two months. It's actually really fun. One complaint would be sometimes the games are super hard and sometimes they're easy. You are supposed to control how hard the game is by how many nights minimum you need to survive but it's really just the luck of the draw pile. I've played games were most of us died by night 5 and another game where we lasted 16 nights all with full health.

Superhot VR I've played this before at a friend's house but recently just picked up an Oculus Rift S second hard for a good price. This game is what sold me on VR, this style of game I think is perfect for VR.

[Try]

Path Redirect Import this is an easy and small thing. In Drupal sites we do 301 redirects all the time, never thought about bulk importing them because normally we handle them through a htaccess or the client does them as needed. Recently I needed to add 50+ redirects to a site and editing the htaccess wasn't an option, I stumbled upon this module so now we're using it.

Control your Android Phone from your computer with scrcpy I haven't actually tried this but it seems like a cool way to use your Android phone from your computer.

Desktop Color picker for Linux: Farge I started using this color picker the other week it does what it needs to without being overly complicated or fancy.

[Read]

VS Code for PHP Development it's good to see ways to make editors beyond PHPStorm good for PHP dev, I personally use PHPStorm but I wouldn't say I'm satisfied or would recommend it to others, PHPStorm works.

No CS Degree as a person without a CS degree it's cool to read about how other people without degrees are doing in tech.

What's new in ES2019 it's good to keep up with new things in JS land, but when I can use ES6 without babel, what's what I want to know.

13. July 2019

Weeknotes #5

Last week was the 4th of July, we had family in town to celebrate and to see our baby. Due to that I missed last week as there was just too many things to do and a lot of time spent with family.

This week at work I was able to spend a good amount of time building new layouts and blocks for a site in Layout Builder. I also continued working on the date repeat update for a site and built out a First/Last date formatter. Hopefully it starts working good enough that I can share it back with people as it seems quite useful.

I crashed my Grom

It seems like I have bruised by ankle bone, maybe sprained my knee and shoulder. But WAY better than last time I crashed my bike a couple years ago and this time I was hit which was weird. Basically people shouldn't be aloud to drive. Someone was in the right turn lane of an intersection stopped, I was needing to drive through that intersection so I was in the non turning lane to the left of them. Then I guess they decided they wanted to go straight too and turned right into my lane right in front of me. I slammed on my brakes hit them and fell over. Then they drove away. I'm very lucky to walk away from that accident mostly unhurt. The next day I was walking around and mostly able to live my life except I have a slight limp and I'm sore.

[Try]

Lazydocker this is a TUI (terminal User Interface) for all your docker containers running or not. I opened this and found gigs of old containers and things unneeded that I was able to remove. I also am just a sucker for TUIs so if you know of any other good ones let me know.

Layout Builder Modal at CK we user Layout Builder now for all landing page things but one of the terrible things about it is you do everything in a 300px wide sidebar. This modal module lets you do the same things but in a modal. Normally I'm a modal hater but this is a pretty good use case for them.

[Read]

First letter pseudo element & Making responsive tables with minimal CSS this week I came across Bradley Taunt's website and he has some really good frontend tutorials these were just two of the ones that showed me new things I didn't know.

Intro Guide to Dockerfile Best Practices I use Docker all day everyday and this was a good refresher for what makes a good Dockerfile.

The death watch for the X Window System (aka X11) has probably started as a user of Wayland this is both good to read. I am looking forward to more things working properly under Wayland by default. Now if only we could get rid of Qt...

A better zip bomb cool to learn how zip bombs work and really just how unzip tool work. Be careful with that file though, I sent it as a joke in my company Slack and someone tried opening it.

30. June 2019

Weeknotes #4

This was a good week, got a lot done at work and even had enough time to mow my lawn. Summer has finally arrived in Kansas City just in time for the AC to die on my wife's van, so that made this week hotter than I would have liked. Next week is 4th of July so I have family coming into town and we're going to watch things blow up and eat grill food, it will be great!

Due to my wife being sick I worked form home on Monday to help take care of our baby while she slept. The weird thing is that may have been my most productive day of work, I got a solid 9 hours in all with minimal interruptions. I really like my office and going to work but it is really that strange that alone in a room I'm able to get more done because I can think for a least an hour at a time without interruptions. This is good news because at Code Koalas we're starting first Friday's of the month as work from home days.

I was able to get a Drupal 8 site mirroring over to Patheon with a custom pipeline. It took longer than I would have wanted but in the end it's not too complicated. Pantheon make you track all composer downloaded files if you're not using circleci, I refuse to track all my composer files because I'm not an animal. I created a pipeline that replaces the gitignore with a pantheon gitignore then composer installs and git adds and pushed up to Pantheon. We had to use an approach like that because we already have auto deploying docker containers for this site locally and on our staging, but the client ultimately wants to deploy on Pantheon. The goal was to keep our normal workflow while still using Pantheon and I believe I accomplished that.

I accidentally nuked my Desktop Arch Linux computer and had to reset everything. I recently moved from nvm to n to manage node on my laptop, and decided I wanted to move that setup to my desktop computer as well. For some reason node loves to save files in root system directories, and so does n. It wanted access to /usr/local/n I believe so I created that and chmod that but accidentally ran that just on /usr/local. Right away nothing was broken but I knew bad things had happened, then about a hour later I realized I could no longer sudo things. I tried just booting from a flash drive and changing back permissions but after a couple failed attempts I decided to just start over on this computer. A hour or two later it was up and running and good to go. I'm impressed with how quickly I got things back working, and now I know I don't have filler things I don't use anymore taking up space. This is why it's nice to have you dotfiles backed up and I've been creating a private wiki for my life which includes all the random things I run on my computer so I could easily grab those and install them.

[Try]

I mentioned Gutenberg for Drupal last week, I tried it and so should you. I put it up on my blog (this right here) and was blown away with how great it is! We spend so much time trying to add plugins and change settings in ckeditor to make it work right for our users where with Gutenberg I clicked install and enabled it for the Blog content type and I was done. So seriously try it if you haven't, I'm writing this blog right now in Gutenberg.

[Read]

$499 AMD Ryzen 9 3900X Almost as Fast as $2000 Intel Core i9-9980XE this is really good news for anyone wanting a new computer some day, you don't need that crazy AMD Ryzen 9 3900X but because it's 1/4 the price that means Intel will need to do something to still be competitive. Hopefully bringing all prices down or making an even better processor. I personally am wanting to build a new computer using a Ryzen, but this computer I'm typing on is only two years old, runs perfect and all Intel based so too big of an upgrade.

The Toyota Way this was a fun read to see what Toyota does to stay so good. The best car I ever owned was my 2003 Toyota MR2 and I miss it everyday.

HTTP Cats and IP Kittens fun ways to put more cats on the internet.

Hey advertisers, track THIS a project from Firefox that spams all the tracking scripts watching you with tons of fake data to "confuse" them. Unsure if this actually works as they have years of data on you, how much does one day move the needle on this?

HTML is the Web good read about how HTML is fundamental to the web and a lot of people seem to not care to learn it. I learned HTML first back in 2004 (I think) and it's pretty simple and all made sense to me, so it's weird than newer people and just learning React or a framework and not the language that makes the internet. But then again do people say that about me writing websites in PHP instead of learning Assembly?

Raspberry Pi 4 is released! and What do you do with your Pi? A new Pi is released that goes up to 4GB of RAM, this is great but also what is there to even do with a Pi? I think with the 4GB and dual monitor capabilities of this newest one you could seriously make it your kids computer. I had already told my wife that when our kids are old enough I'm making them build a Pi if they want to have or use a computer. I want them to understand what computers are and not just be addicted to phones like so many young kids today.

Why you need to give Firefox a chance Chrome/Google have a monopoly on the internet, Firefox is really the only Browser fighting for us to keep the web standards open and not controlled by one company. I have used Firefox on and off since it's been out, I've currently been using to for I think the last two years when the rewrote the render engine making it much faster than it used to be.

23. June 2019

Weeknotes #3

This week at work was really good. I mostly got to work on building out new features on a new Drupal 8 site we're building using Layout Builder. It's always nice to be building out features trying new things instead of digging through piles of old code trying to fix little bugs. One of the things I need to start doing is rewrite an event calendar written in D8 to actually use repeating date fields to allow for the calendar search feature to work as intended, won't be fun.

Recently the Gutenberg editor for Drupal became stable, I don't think it will replace with Layout Builder does but I'm going to try it for this site for blogs and see how much better it makes it.

This week I finally got in my new tires for my Honda Express, I got those mounted on, filled with air and actually rode it for a couple minutes yesterday, currently the max speed is 24mph so either there's an issue with the carb or possibly a blockage in the exhaust that I'll have to start working on soon.

Honda Express Moped with fresh tires
New tires mounted on the Honda Express.

Yesterday I got to go my first Royal's game of the year, we really wanted to bring Phineas but because the temperature was over 90 and very humid we left him at home. It was a fun game even though like always the Royals did lose, we got to see a good game that was close until the 10th inning. They were really good seats and thanks to a very nice client of ours.

Kansas City Royals Game

[Games]

For my weekly game night we got together and played Scythe again. I've owned the game since the Kickstarter a couple years ago, but I've only played it a handful of times. I'd rate the game probably 9/10, not sure what I'd improve my main complaint is there are so many moving parts it takes awhile to get new people into the game. That's the main reason I've only played it a couple times. My favorite part of the game is there isn't dice rolling and you cannot make the same move twice in a row so it's all strategy. Nathan beat me, which is unfortunate but fun nonetheless.

Scythe Board Game

Next week at Code Koalas we're hosting an external Mandatory Fun game night on Thursday. If you live in the KC area you should come by there will be games and good company. It's our first formal external mandatory fun game nights so hopefully it's good.

This week I also picked up Hollow Knight for Nintendo Switch this week, so far my impressions are it's a very fun game and hard. I'm currently lost off the left side of the map and I'm not sure how to get back onto the map. I'm also picking back up Golf Story to see if I can complete that game, it's one of the more fun "sports" games I've played in awhile.

[Read]

Google Calendar went down this week. That's the second service to go down in two weeks I think, not that it means that Google is going down or anything like that but it's always a good time to reevaluate whether or not you need to use a service like Google for your calendar or if a self hosted option would be better. Disclaimer I use Google Calendar for personal and work.

The worst morale-boosting gesture I've experienced. This is just a great read about how out of touch the higher-ups were while trying to cheer up their team.

The CIA Spied on People Through Their Smart TVs, Leaked Documents Reveal. and Samsung TVs should be regularly virus-checked, the company says. I've never been a huge fan of smart TVs. I'm a fan of a dumb TV with a box plugged into it, as I've never used a smart TV that didn't completely suck. I do currently own a TCL TV with a Roku built in, and I think the TVs with Android TV built in are a good idea, not sure if they will end up having the same security issues or not as they're separate systems.

15. June 2019

Weeknotes #2

This week really blew by, so did last week which would be why I missed that update, oh well. The coolest thing I did was over the weekend picked up a 1980 Honda Express II which is a little moped.

Honda Express 2

Bought it as a non running scooter that has sat for a couple years. I drained the fuel, cleaned the carburetor, replaced the battery and spark plug and got it running. Now I'm just trying to find tires that fit which seems to be a harder task then it should be.

At work I interviewed a couple developers and held reviews and one of ones for a couple of our existing developers. During interviews I've started asking critical thinking questions instead of asking questions of like "how do you do X in PHP". It will take me hiring people to find out if this really works or not.

[Try]

Aerc - terminal email client. For awhile I've been trying to use Mutt as my email client when teaming that up with offlineimap. It mostly worked and was nicer than other email clients. I most recently switch to using Claws Mail because it works. In steps Aerc

[Read]

Crucial Conversations Read this book for work, 8/10. Good book with good information but couple be cut easily in half or more and still be as useful. Talks about how to keep your cool and have meaningful crucial conversations when your brain wants to shut down and lash out at the person who just called you out in a meeting or wherever.

Matrix 1.0 released. I tried getting a Matrix server setup a couple months ago as a chat server but had issues getting it connecting to the federation. With the 1.0 release I'm willing to try it again. The main thing I want to try is the 3rd party bridges to connect multiple services. I would be running Matrix server and one app to connect Slack, Rocket.Chat, text messages and others which would be really cool.

Always own your platform. Been big on this for awhile, as Facebook and YouTube start removing people because they don't like them the fear is always what if one day you find that they've moved what was acceptable and now you're outside of that? Now you're out and you've lost all of the reach you had.

Open source seed initiative. Never realized seeds weren't open sourced, which once I thought about it of course companies own the seeds, this is cool because dooms day type of thinking we could run out of seeds and all die without something like this.

Nintendo killed it at E3 this year. Really existed to play Super Mario Maker 2, never played the first one but when I got a Switch and realized the first version existed I've been wanting that game on Switch which I now get.

 

01. June 2019

01. June 2019

Weeknotes #1

Wanted to start writing weekly recaps of the week, I heard about Dave Rupert doing that on an episode of Shop Talk Show. The thought is to get small news items and links to cool things out that don't need a full long write up. Hopefully this gets me updating content more frequently and makes me better at writing.

This week was a rough week with the holiday on Monday then Flyover Camp on Friday and Saturday so easy to realize not much work got done around the office in the three days of work we had. That's unfortunate because we are now quickly approaching a couple different deadlines at work.

Flyover Camp which was a Drupal specific camp in Kansas City was a lot of fun. At Code Koalas we sponsored the event and sent all our devs to it. It was a lot of fun and we learned a lot, you can view all of the sessions now on YouTube. To me camps are better than conference because they're smaller and you get to actually people in the Drupal community, also they're shorter so your brain gets less fried. One thing that happens at every camp and conference is after parties, and this after party was probably the best one I ever went to! We went to Pawn & Pint which is a local bar that has walls of board / party games so you go there and play games with friends over a drink and some food.

D&D Oneshot

At the after party we playing a D&D one shot with a couple people from work and some from the conference. It was my first one shot and it was a log of fun. We defeated and bag guys with no deaths of our own which is good.

08. April 2019

Bringing Sanity To Your Git Flow

Git is a great tool which enables teams to work together and deploy code, but it's not all happiness and ponies. What if you need to deploy a single hotfix into your prod build, without pushing in any more of the code that has been written since your last depoy? How can you roll back to an older version of your code? What if you want to deploy all the changes that exist in staging to production but the environments are so far apart at this point merging code is scary. With the right git flow this is a breeze, but with the wrong git flow this can be a nightmare, or my life for the past couple years.

In this post I will assume that you at least have a basic understanding of how git works, if not you can get a quick git tutorial.

A very slimmed down and common issue we used to run into is, we have our main development branch and a staging branch that updates the site our client can see. We are doing all our work in master and then every so often make merges into staging with all the changes so the client can see the updates. Then inevitably someone makes a minor hotfix change into staging so now master and staging have different code in them. Now we're ready to deploy all staging code to live, so now we need to pull our staging code into our production branch. But now what happens to that staging hotfix that happened, that's now gone in master and you're going to lose it your next deploy unless you cherry pick that back in. A visual representation of what you've made is this.

git tree
Because all the merges as this scales your git tree just continually gets messier.

A simple tool you can use to follow along or learn more of how git works, and what I've used to generate these git screenshots is here https://git-school.github.io/visualizing-git

We don't need to get too into the weeds about all the weird things and issues you can run into with git, I'm sure you've encountered them before. We at Code Koalas have moved all of our ongoing projects to follow the flow of, master branch, feature branches off a master, rebase your branch before merging and releases for staging and production are tags on master. It's as simple as that!

Here is the step by step process of the normal git flow you'd follow for everyday use.

  1. Pull down latest code on master
  2. Check out your new branch
    1. We follow a format where branch names should include the ticket number in them. CK-204
  3. Do all your work.
  4. Git add your code with a good commit message also including the ticket number
    1. CK-204: added new feature
  5. Check out master branch and pull latest code
  6. Go back to your branch and rebase it off latest master
    1. git rebase -i master
  7. Push up your code
  8. Make a merge request into master squashing commits if it is really just one feature change and closing out your branch on merge acceptance

Another git tree
You will notice here it’s mostly just one line with a lot less back and forth.

This flow helps your merge request from having phantom line adds or extra code you don't need. Also rebasing it means you will resolve all the conflicts locally before you push it up.

Great now you're ready to deploy this code to your staging environment, all you do is either create a tag based off master locally or in your remove git software (gitlab, github or whatever) and call it RC-v1.0.0 or whatever your version number is. We then have pipelines that build based off tags and if rc-* it will build and deploy to staging.

another git tree
Here you see the tag RC-v1.0.0 which is “live” on staging while the code keeps moving.

Deploying to production is the same as for staging. If everything in master needs to go live great, create a tag but this time call it release-v1.0.0 and same as before it auto deploys. If you only need a couple changes based off the last release or rc you will follow our hot fix flow which takes a previous tag and add just the commits you actually want.

  1. Create a branch off the tag you want to base this new tag off of.
    1. If it's a hot fix grab the last full release then we will just add the few extra lines needed. 
  2. You then pull in the code you need into that branch
    1. You could make a hotfix based off that branch and merge it in, then rebase it off master and merge it to master.
    2. You could cherry pick in just all the new commits that have happened into master and add those in. That's the good part about putting ticket numbers in your commit messages.
  3. Then create your new tag based off this branch.
    1. If it's a hotfix we do the same release tag we based it off of but add -hotfix-1
  4. That code will deploy based off the pipeline and tags.

another git tree
Here we have taken in the RC tag, added a hotfix then deployed that live.

That's really it, it's really simple but has made deploying code to prod no longer scary. It's cleaned up the difference between environments so getting your code into staging then into production isn't painful. Most importantly for us it's allowed us to have multiple features being built at the same time and putting one on pause and being able to deploy one of those features and not the other.

04. March 2019

Integrating The Color Module Into Your Drupal 8 Theme

Letting your user change the color of the theme can be a hassle, or downright scary. The color module built into Drupal 8 core allows administrators to change the color scheme of compatible themes. We are going to walk through the few steps that are required to get your custom theme up and running with the color module.

Possible Use Cases

  • Creating a theme that needs to work for multiple sites with different color schemes.
  • Creating a theme to contribute or resell.

What You Need

  • A Custom Theme
  • Install the Color Module (included in core)

Setting up your Theme

Once you have created your theme you will need to create the directory color and create at least one file named color.inc. There are more files that can be put here to make the preview for the admins better but they are not essential for this tutorial.

You will also need a CSS file with all of your color things that you are letting the admins control with Drupal.

Your directory structure should look like the following example. Where your CSS file is and what it is named isn’t a requirement of the Color Module, but you do need to properly link to them.

custom_theme
| -- custom_theme.info.yml
| -- custom_theme.libraries.yml
| -- color
|    |-- color.inc
| -- dist
|    |-- css
|        |-- color.css

The custom_theme.info.yml is a requirement of every theme, and the only thing worth mentioning here is that it must have a library that it is using so you can pull in your CSS changes. It should look like the following. I am sub-theming Bartik just for this sample, as it looks decent as a base to not have to write any extra HTML or CSS for this tutorial, and is not required.

name: Custom Theme
type: theme
description: Custom Theme to show color module
package: Other
core: 8.x
base theme: bartik
libraries:
- custom_theme/color

The custom_theme.libraries.yml is needed to give the path to your CSS that the Color Module will be using. It should look like the following:

color:
  css:
    theme:
      dist/css/color.css: {}

The color.inc is the file that is doing all of the work, a minimum file would be like the following:

$info = [
  // Available colors and color labels used in theme.
  'fields' =--> [
    'primary' => t('Primary Color'),
    'secondary' => t('Secondary Color'),
    'text' => t('Text Color'),
    'background' => t('Background Color')
  ],
  // Pre-defined color schemes.
  'schemes' => [
    'default' => [
      'title' => t('Default'),
      'colors' => [
        'primary' => '#3f51b5',
        'secondary' => '#536dfe',
        'text' => '#3b3b3b',
        'background' => '#ffffff'
      ],
    ],
    'red' => [
      'title' => t('Red'),
      'colors' => [
        'primary' => '#f44336',
        'secondary' => '#ffcdd2',
        'text' => '#600000',
        'background' => '#ffffff'
      ]
    ]
  ]
];

// CSS files (excluding @import) to rewrite with new color scheme.
$info['css'] = ['dist/css/color.css'];

Once that file is there you can clear your site’s cache and go to the theme settings for your site /admin/appearance/settings/custom_theme and you will see the color form. The form should have all of the fields you defined and show a color wheel allowing people to pick whatever color they’d like for the form.

Admin form in D8
The admin settings form for our custom theme

Now admins can choose whatever colors they want, or from one of your pre-created schemes. If you change those and view the site, you will see that has happened yet. The next step needed is to create the CSS that Drupal will actually be using to color the site with the values entered in the admin form.

Setting Up Your CSS

There are, in my opinion, two approaches to how you could setup your CSS file to color your site.

  1. Create color classes that you apply to your HTML as needed that color things
    .primary_color {
      color: #3f51b5;
    }
    
    .primary_color_bg {
      background-color: #3f51b5
    }
    
    
  2. Take all of the selectors that need colors and move those into your CSS file.
    #header {
      background-color: #3ft1b5;
    }
    

I personally think the first approach is much cleaner and will save you time and headaches, but in this example I’m doing the second approach for simplicity. Below is what our dist/css/color.css file looks like.

#header {
  background-image: none;
  background-color: #3f51b5;
}

h1 {
  color: #536dfe;
}

body {
  color: #3b3b3b;
  background-color: #ffffff;
}

#page {
  background-color: #ffffff;
}

Something very important that you should take note of is how colors in your CSS map to the colors in the admin form. In Drupal 8 we are grabbing the HEX defined as the default in your color.inc and replacing that with the new value saved in the config form. In our default scheme, primary color is set to #3f51b5 so in our color.css file anywhere that hex exists, it will get overridden to be the new primary color set in the admin interface.

Results

Now that everything is setup, we are good to go to the admin interface again and change the color scheme. Once changed to the red scheme, if we reload the home page this is what it looks like:

website with red theme
Our Bartik based site with the Red color scheme

We can also head back into the theme settings and choose completely custom colors, disregarding predefined color schemes.

Admin settings with color wheel
The color settings as set using the color wheel

Once we save that and head back to the homepage, we’re greeted by this very ugly site.

our website but green

This obviously isn’t the ideal situation, and you should be able to create much better looking sites if you contact a designer to create your color schemes and consider what elements should allow color changes.

Quirks you might run into

  • If you added keys in the color.inc but you don’t see them in the theme settings form even after a cache clear you must clear out the color.theme.custom_theme config. You can do that with a drush command drush cdel color.theme.custom_theme
  • This seems weird, but for me I had to make my HEX values in both my color.inc and my color.css lowercase or they didn’t get overridden.

Conclusion

The Color Module just works, is simple to set up, and is a great tool to know how to use. At Code Koalas we have used it on a multiple sites for clients and will continue to use it when it is appropriate for the project.