Skip to main content

Switchable Background Colors Using a List Field

Design
Front-end Development
Drupal

I've worked on several sites now and I've found that I'm constantly adding the ability for users to be able to change the background color of a section. This is great to add in so that there is more customization for each section and to visually break up the different sections. There are several ways to achieve this, but for this example, I'll use a field to add a class to the section.

First, you want to go to the paragraph type that you want to add this field to, in this case, I'm using a section. Add a new field type of List (text) and name it accordingly. Once the field is created you can add a list of the allowed values for the field. Follow the format of key|Label and list out all the possible colors. It's important to make sure that the number of values is limited to one so that someone doesn't select more than one option.

List of possible background colors used for field

 

Save the field settings after all the possible values are listed. Then you'll want to go into the preprocess file for paragraphs, find the paragraph bundle you added the field to and add the two lines below.

$color = $variables['elements']['THE_COLOR_FIELD_NAME_HERE']['#items'][0]['value'];
$variables['classes_array'][] = 'background--' . $color;

Adding these two lines will get the value that is selected by the user and add a class of background--[color-name] that can then be styled using css.