We use cookies to make your viewing experience better. By accepting you consent, you agree to our Cookie policy

Accept
Improve your Craft CMS skills

Craft CMS: How To Create Dropdown Fields

10 min read
Shape May 2022 HR 20 andy

Sick of messy free-text fields? Craft CMS dropdowns provide the structured content control you crave. This guide highlights the immense time savings, usability, and data quality benefits of dropdowns. Learn how to quickly create, populate, and integrate dropdowns into your editing workflow. Find tips for outputting, validating, and troubleshooting dropdowns across templates and forms. Master the art of optimized content capture with Craft CMS dropdowns.

In Craft CMS, dropdown fields provide a controlled, optimized way to capture structured content. Create dropdowns in Settings > Fields, define options and settings, relate to entries or other elements, display values in Twig templates, populate options dynamically from code/APIs, output on frontend forms, implement conditional logic, and troubleshoot issues with logging and inspection.

Dropdown Fields in Craft CMS

Defining Dropdown Fields

A dropdown field in Craft CMS, also known as a select field, is a UI element that displays a list of preset options for users to choose from. The options appear in a dropdown menu that expands when clicked.

Dropdowns are one of the most common field types used in Craft CMS. They allow the site admin to create a controlled list of choices rather than having users enter freeform text input. The available options can be manually defined or populated dynamically from a database table.

Common uses of dropdown fields include site navigation menus, category/tag filters, user settings, and any other scenario where the input needs to be restricted to a predefined set of options. For example, a dropdown field could be used on a contact form to allow users to select their state/province from a list rather than typing it in.

Benefits of Using Dropdown Fields

There are several advantages to using dropdown fields in Craft CMS:

  • Preset options - Since the admin predefines the options, it guarantees valid data will be submitted. The allowed values are constrained rather than allowing freeform input.

  • Space saver - A dropdown takes up less space than displaying all options visually like radio buttons or checkboxes. This can help reduce clutter, especially for long lists.

  • Ease of use - Dropdowns require just one click to make a selection rather than clicking multiple times for other field types like radio buttons. Users find dropdowns intuitive and familiar.

  • Data quality - Constraining inputs optimises data quality since users can't provide invalid or nonsense values. Useful for standardising data.

Compared to other field options like radio buttons or checkboxes, dropdowns are best suited when space is limited or you want to constrain the input to a relatively short list of options.

Radio buttons allow multiple options visually but take up more space.

Overall, dropdowns strike the right balance between ease of use for the front-end user and administrative control for site builders. They enable creating a controlled, optimised user experience while requiring minimal effort to implement in Craft CMS.

Creating Dropdown Fields in Craft CMS

To create a dropdown field in Craft CMS, just follow these simple steps:

  1. Navigate to Settings > Fields and click the "New Field" button.

  2. Select "Dropdown" as the field type.

  3. Give the field a descriptive handle and name. The handle is used for programming while the name displays in the control panel.

  4. Define the dropdown options by entering one option per line in the "Options" box.

  5. Set any additional configuration options like making it a required field.

  6. Click "Save" and the field will now be available to use in your sections and entries.

  7. To display the dropdown on the front-end, use a {% select %} tag in your Twig templates.

That's all there is to it! With just a few clicks, you can add a handy dropdown field to your Craft CMS site and start constraining your content to controlled options.

Populating Dropdowns Dynamically

Hardcoding dropdown options works fine for small lists but for larger dynamic lists, you can populate options directly from a database table.

For example, you may have a table of countries you want to pull into a dropdown. Rather than manually entering hundreds of options, just select "Relate to a source" when creating the field.

Then choose the appropriate table column to display and value to submit. When entries use this field, the dropdown will be auto-populated with the latest data from that table.

This dynamic population ensures your dropdowns are always in sync with the latest data in your database. No more manual updates required!

Dropdown fields are a versatile option in Craft CMS for presenting users with a select list of predefined choices. They provide an intuitive UI while giving admins complete control over the allowed inputs.

Dropdowns help create clean, validated data submissions without sacrificing ease of use. And dynamic population from database tables scales dropdowns to any list size while reducing manual work.

For partnering quality data capture with sleek, minimalist UI designs, dropdown fields should be a go-to tool in every Craft CMS developer's toolbox. Their flexibility and convenience earn them a top spot in Craft's expansive field type roster.

Creating Dropdown Fields

Accessing the Fields Page

The starting point for building a new dropdown field in Craft CMS is accessing the Fields page located in the control panel navigation. Under the Settings menu, you'll find the Fields option which opens the main field management hub.

Alternatively, you can directly navigate to /admin/settings/fields to land right on the Fields page. This is where all custom fields are organized and created. Upon arriving, you'll see existing fields listed and a prominent "New Field" button in the top right corner. Clicking this crucially opens the field creation modal where you can finally select "Dropdown" as the desired field type to build.

Adding a New Dropdown Field

After accessing the Fields page, the next step is clicking that vital "New Field" button to initiate building your dropdown. In the creation modal that opens, you'll be presented with a menu to choose the specific field type needed. Scrolling down reveals the "Dropdown" option which is perfect for our use case.

With "Dropdown" selected, Craft switches the view to reveal the configuration panel containing all the core settings for constructing our new dropdown field. This is where you define the basics like giving the field a descriptive name and handle for internal reference in the CMS, composing instructions to guide content creators, and most importantly, specifying the actual options that will populate the front-end dropdown.

Field Settings and Configuration

Upon initially naming and labeling the dropdown field using self-explanatory handles, the primary configuration involves defining those select options authors will choose from. The provided text box allows entering one value per line, such as "Option 1" on one line and "Option 2" on the next. You can even specify both the visible text and submitted values using pipes.

Additional key settings include making the field required or optional, enabling translation, restricting to single or multiple selections, and dynamically populating options from a database table. The options configured here directly determine what is presented in the dropdown on the front-end. Keeping them concise yet relevant maximizes usability for authors and end-users.

Broader configuration like adding validation rules, visibility conditions, and field grouping unlocks richer, more tailored dropdown experiences.

In summary, the Fields page is the gateway for creating new dropdown fields in Craft CMS. A few clicks to access it, select "New Field", choose "Dropdown", define options, and configure settings gives both admins and authors an easy, optimized dropdown field tuned for validated, high quality data capture across the site.

Configuring Field Options

Option Labels and Values

Once you've created a new dropdown field in Craft CMS, the next step is configuring the options users can select from. These options have both a visible label and an underlying value submitted to the template.

To set the labels, simply add each one on a new line in the provided text box during field creation. For example:

Red

Green

Blue


This will create three options with those labels. To also customize the submitted values, you can use pipes to separate the label and value:

Red|#FF0000

Green|#00FF00

Blue|#0000FF


Now "Red" will be shown to users but "#FF0000" is the value sent to the template. This lets you tailor both what's displayed and what data gets captured.

You can also edit options after initial field creation. Just go back to the field settings and update the labels and values as needed. Adding, removing, or modifying options can be done at any time.

For multiselect dropdowns, you can specify an array-formatted value like ['red','green'] to allow multiple submissions. The labels would remain simple strings.

Default Selection

When creating a dropdown field, you may want one of the options to be selected by default rather than having no initial selection.

To set a default, add (default) next to the desired label:

Red

Green

Blue (default)

Now "Blue" will be automatically selected when users first open the dropdown. This provides a predefined selected choice before the user takes any action.

Default selections are useful in situations like:

  • Requiring a specific initial value

  • Setting a recommended or popular option

  • Providing an instructive placeholder choice

Just be sure the default makes logical sense as the starter option in context. And you can still leave the field blank by default too.

Reordering Options

Once you've defined labels and values for your dropdown options, you may want to rearrange their order.

By default, options appear in the order you've entered them. But you can manually change the order by dragging and dropping options using the drag icon next to each.

This allows fully customizing the option order as needed. Be purposeful in ordering - place more common options first, group related options together, or alphabetize for better scannability.

For dynamic dropdowns populated from a source, you can sort the options using:

{% set options = craft.entries.section('sectionHandle').orderBy('title asc') %}

This queries the entries and orders them by title alphabetically ascending.

On the front end, use {% for option in options|sort %} to output them in a specific order.

Restricting Selections

By default, dropdown fields allow only a single selection. But you can enable multiple selections with the "Allow multiple selections?" checkbox when creating or editing the field.

This allows users to choose multiple options at once. The submitted value becomes an array of selections rather than a single value.

Multiple selection dropdowns work great for things like picking multiple categories or tags. Just be aware that from a UX perspective, long multi-select lists can become overwhelming. Stick to single-select dropdowns when:

  • Options exceed 10-15 choices

  • Only one option can be chosen

  • View space is very limited

For required single-select fields, make sure to provide a default first option like "Select one..." that has no value submitted.

Configuring the options for a dropdown field involves setting labels and values, choosing a smart default, organizing the order, and enabling multiple selections if warranted. Taking the time to purposefully tailor options makes your dropdowns more intuitive and user-friendly while capturing higher quality data.

Relating Dropdowns to Entries

Adding Fields to Sections

Once you've created a dropdown field in Craft CMS, the next step is adding it to one or more sections so it can be used by entries in those sections.

To relate a dropdown to a section:

  1. Go to the Sections page and select the desired section.

  2. Click on the "Fields" tab.

  3. Select your newly created dropdown field(s).

  4. Click the "Save" button.

The dropdown field will now be available when editing entries in that section. You can add the same dropdowns to multiple sections as needed.

For example, you may create a "Product Categories" dropdown field and add it to several product-related sections so authors can consistently categorize entries without freeform values.

Displaying on Entry Edit Pages

When you've added a dropdown field to a section, it will now display when editing entries in that section. Authors creating or updating entries will see the dropdown preset with the options you configured. They simply select one or more choices as needed to populate the field.

The current selection will be highlighted and the value(s) selected will be temporarily saved while editing the entry. Only when the full entry is saved will the dropdown selection be permanently stored.

For required fields, the "Save" button will remain disabled until a selection is made. Optional fields can be left blank.

Saving Selected Values

When an entry with a dropdown field is saved, the currently selected option(s) will be stored and related to that entry.

For example, if the author picks "Category A" from a dropdown list, the underlying value tied to that label (e.g. "category-a") gets saved to the entry record in the database.

Then when editing the entry later, the dropdown will display preselected with the saved value to indicate what had previously been chosen. Authors can change the selection or leave as-is before saving it again.

For multiple-select dropdowns, an array of all selected option values gets stored. On re-edit, all previously selected options will display as checked by default.

So relating dropdown fields to sections allows capturing consistent, structured data with each entry while streamlining the input process for authors thanks to predefined options.

Relating to Other Elements

In addition to entries, dropdown fields can be related to categories, global sets, and other elements:

  • Categories - Restrict choices for categorized content

  • Users - Capture role, department, or other user data

  • Assets - Organize images, docs, and files

  • Global Sets - Classify reusable content sets

  • Tags - Standardize tag options for entries

Relating dropdowns provides a portable way to manage and select from predefined options across multiple elements in your Craft site.

Adding dropdown fields to sections makes them available for entry authors to populate with consistent, structured data. The selections display during editing and get saved directly on entries for easy relation. This structured approach maximizes control and data quality for the site admin while optimizing the authoring experience.

Displaying Dropdowns Front-End

Overview of Twig Syntax

Once you've created a dropdown field and related it to entries in Craft CMS, the next step is displaying the selected values on the front-end. This is accomplished using Twig templates.

Twig provides a fast, flexible templating language optimized for Craft CMS. It allows outputting dynamic content, looping through results, and implementing conditional logic.

Some key Twig syntax includes:

  • {{ variable }} - Prints a variable's value

  • {% for item in array %} - Loops through an array

  • {% if condition %} - Conditional statement

  • {% endif %} - Closes conditionals

Craft passes all dropdown fields into the Twig templates where they can be outputted or manipulated as needed.

Outputting Field Values

To display the value of a dropdown field on the front-end, you can use the {{ entry.handle }} syntax:

{% set color = entry.colorDropdown %}


<p>The selected color is {{ color }}</p>


This will print the underlying value of whatever option was chosen for that entry's "colorDropdown" field.


For multiple selection dropdowns, it will output an array:

{% set colors = entry.colorDropdown %}


<p>The selected colors are:</p>


<ul>

{% for color in colors %}

<li>{{ color }}</li>

{% endfor %}

</ul>


This loops through each selected color and displays it in a bulleted list.

Conditionals Based on Value

You can use Twig conditionals and logic to check the dropdown value and output different content accordingly:

{% set size = entry.sizeDropdown %}


{% if size == 'small' %}

<p>The small widget is in stock.</p>

{% elseif size == 'large' %}

<p>The large widget is backordered.</p>

{% endif %}


Here the text changes dynamically based on the sizeDropdown value.

For multiple selections, you can check if a specific value is in the array:

{% if 'preorder' in entry.statusDropdown %}

<p>This item is available for preorder.</p>

{% endif %}


Conditionals allow tailoring theexperience based on the dropdown data.

Outputting the Field Itself

You can also output the full dropdown field directly using:

{{ entry.colorDropdown }}


This renders the dropdown with the options configurable in the CMS rather than just the saved value.

Useful for front-end authors editing content or to reuse the dropdown styles.

Twig provides everything needed to output dropdown values, implement dynamic logic, or display the full field itself. Combined with Craft's flexible templating and JSON data, dropdowns enable fine-tuned front-end experiences tailored to the structured data captured.

Populating Options Dynamically

Options from PHP Code

Rather than statically defining dropdown options in the Craft CMS admin UI, you can dynamically determine options on the fly using PHP code. To do this, first choose "PHP Code" as the source when creating your dropdown field. This will allow defining a custom PHP function that returns an array of options.

Within this function, you have full control to build the array however needed - integrate with other CMS data, query databases, hit external APIs, implement complex conditional logic, etc. The possibilities are endless compared to hardcoded admin configuration.

For example, you could have a function that checks the current day of the week, then returns a different set of options depending on whether it's a weekday or weekend. Or pull options from a MySQL database table that stores values entered by users on the front-end. The options array gets passed back to Craft to populate the dropdown seamlessly. So for advanced custom use cases, PHP code provides maximum flexibility.

Syncing with Data Sources

In addition to PHP code, dropdown options can be populated dynamically from external data sources outside of Craft itself. For example, your dropdown choices may live in a headless CMS like Contentful, a PostgreSQL database, a SaaS app's API, or even payment and CRM platforms.

Using their respective APIs and Craft plugins, you can sync and integrate these sources to dynamically drive your dropdown options. A real-world example is a "Product Categories" dropdown that queries a Shopify store's API to pull its latest categories.

Now whenever the category list changes in Shopify, your dropdown updates instantly as well, always in sync.

When to Use Dynamic Options

Some examples of when dynamic configuration is useful: complex conditional logic dependent on multiple factors, frequently changed external data, large lists that are easier to manage programmatically, aggregating options from diverse sources, and advanced customization needs.

In summary, rely on simple hardcoded options for small, static datasets. But utilize dynamic PHP code and external APIs for large, complex, frequently updated option lists requiring maximum flexibility. Just be mindful of performance, failovers, security, and testing. With proper precautions, dynamic population unlocks new levels of power and interconnectivity.

Dynamically populating dropdown options via PHP code and external API integration provides limitless possibilities compared to static admin configuration. Syncing options with live data sources ensures they stay current across systems while enabling advanced customization logic. When carefully implemented, dynamic dropdowns greatly extend interoperability and customization in Craft CMS.

Using in Front-End Forms

Output as Form Input

In addition to the control panel, dropdown fields in Craft CMS can be output on the front-end as part of HTML forms for user input.

For example, you may want to collect data like contact preferences or interests:

<form method="post">


{# Output dropdown #}

{{ entry.contactMethod }}


<input type="submit">


</form>


This would display the dropdown options from the field. Be sure to set a name attribute for form submission:

<select name="contact">

{# Dropdown options #}

</select>


You can also preselect the saved value on page load for editing:

<select name="contact" value="{{ entry.contactMethod }}">

</select>


This provides an easy way to reuse existing dropdown fields for front-end data collection.

Submitting Form to Save

When the form is submitted by the user, you can handle the POST request to save the selected dropdown value to an entry.

For example:

{% if craft.app.request.isPost %}

{# Get posted dropdown value #}

{% set contact = craft.app.request.getBodyParam('contact') %}


{# Save to entry #}

{% do entry.setFieldValue('contactMethod', contact) %}

{% do craft.app.elements.saveElement(entry) %}


<p>Thanks, your choice was saved!</p>


{% endif %}


This grabs the posted dropdown value, saves it to the matching entry field, and saves the entry.

Validation and Error Handling

For required dropdowns, you may want to validate the submission and display errors on invalid data:

{% set contact = craft.app.request.getBodyParam('contact') %}


{% if not contact %}

<p class="error">Please make a selection</p>

{% else %}


{# Save entry #}


{% endif %}


This checks if contact is empty and shows an error.

You can also validate against your allowed option values:

{% set allowed = ['email', 'phone'] %}


{% if contact not in allowed %}

<p class="error">Invalid selection</p>

{% endif %}

This ensures the posted value matches your expected options.

Validation helps catch any submission issues before data gets saved. Displaying dropdowns as front-end form elements allows reusing existing options for user input. Handling the form post saves selections to entries for structured data capture. Validation checks protect data integrity. Combined, frontend dropdown forms provide an easy yet powerful way to collect consistent, structured user data.

Managing Conditional Logic

Showing/Hiding Other Fields

In addition to capturing and outputting values, dropdown fields in Craft CMS can drive conditional logic that shows or hides other fields.

For example, when a specific dropdown option is selected, you may want to reveal an additional set of related fields.

To set this up:

  1. On the dropdown field settings, enable "Show this field only if..."

  2. Choose "Value is equal to..."

  3. Pick the triggering option value.

  4. Select the fields to show.

Now when that dropdown value is picked in either the control panel or front-end form, the additional fields will appear automatically.

This conditional logic can apply to both frontend and backend fields. Useful for progressively revealing advanced options only when needed.

Segmenting Options by User Type

Craft lets you customize dropdown options depending on the user context viewing or editing the field.

For example:

  • Show admin/internal options only for admin users

  • Display customer-specific choices for logged in customers

  • Present different choices for unique visitor segments

To segment options:

  1. Create user groups and assign users

  2. Craft entry permissions for each group

  3. Set conditional dropdown options per group

Now when different users encounter the dropdown, they will see options tailored specifically to them.

Other Conditional Use Cases

Additional examples of dropdown conditional logic include:

  • Custom validation error messages by selection

  • Require custom field values only for certain choices

  • Hide unrelated fields when "Other" is picked

  • Disable date picker if "Not applicable" chosen

  • Populate a related selection dropdown based on initial choice

  • Insert special instructions after problematic selections

  • Mandate confirmation for destructive options

The possibilities are endless! Consider any use case where revealing supplemental context or restricting invalid combinations improves the editing experience.

For extensive custom rules, you can use a plugin like Freeform to model complex conditional logic across multiple fields and selections.

Code Implementation

To implement dropdown conditional logic in code:

  • Use Twig if, elseif, and optional else blocks to check values.

  • Fetch the selected value with entry.handle or craft.app.request.getBodyParam('handle') on front-end.

  • Show/hide fields using CSS like {% if ... %}<style>#field {display:block;}{% endif %}

  • Validate with if entry.handle not in ['allowed', 'values']

  • For complex logic, loop through field sets conditionally

By combining dropdown values with Twig conditionals, the possibilities for tailored field presentation and validation are endless.

Using dropdown values to conditionally show/hide fields creates progressive disclosure experiences. Segmenting options by user provides personalized choices adapted to context. Additional advanced logic further tunes the editing interface based on selections. When combined with code implementation, dropdowns enable fine-grained customization and workflow optimization.

Troubleshooting Issues

Debugging Blank/Wrong Values

Troubleshooting dropdowns displaying blank or incorrect values can be tricky, but a few debugging strategies can help uncover the issue:

First, verify a selection is actually being made in the control panel or front-end form, as no value at all is a common culprit. Logging the dropdown value directly using craft.app.logger.log() provides visibility into what is being saved behind the scenes.

Wrapping output in try/catch blocks also helps identify errors clearly.

Check for typos in both field handles and the selected options that may lead to mismatched data. Reviewing your output and submission syntax against Craft's standards can catch inconsistencies. Clearing caches occasionally resolves odd dropdown glitches as well.

Lastly, test viewing the dropdown as both admins and front-end users to pinpoint any permission issues. By thoroughly logging values, catching errors, checking syntax, clearing caches and testing as different users, you can systematically debug the cause of incorrect dropdown values.

Fixing Validation Errors

For dropdowns used in frontend submission forms, debugging validation errors when they occur is crucial.

First, output any validation error messages thrown to analyze the exact problem. Logging the craft.app.request.getBodyParams() allows inspection of the actual submitted data to check for issues.

Test valid and invalid submissions to effectively test your validation conditions in action. As needed, simplify complex conditional validation temporarily by commenting out sections to isolate troublesome areas.

Ensure your validation code is matching the form input names for the expected parameters. Double check the HTML contains the proper required attributes on fields. And watch out for typos in code, handles or values that could lead to problems.

Taking time to properly log and test validation in action makes narrowing down the source of errors much quicker.

Styling and Markup Issues

If dropdown styling like alignment, sizing or responsiveness is broken, there are a few troubleshooting techniques to try:

First, inspect the rendered HTML for any invalid markup affecting styling. Override any problematic default CSS with custom classes and styles to adjust sizing and positioning as needed. Toggle JavaScript off to see if libraries like jQuery are interfering.

Compare rendering across different browsers to identify any CSS targeting issues. Craft includes useful .select and .selectlist helper classes to simplify styling. Also ensure other nearby UI elements aren't affecting the dropdown display. With careful HTML inspection and CSS adjustment, most dropdown styling issues can be pinpointed and fixed.

In summary, when dropdowns behave unexpectedly, methodical troubleshooting by logging values, debugging errors, simplifying conditions, and inspecting HTML can identify solutions. Carefully reviewing errors and testing systematically makes solving problems much more manageable.

Shape April 2022 HR 202
Andy Golpys
- Author

Andy has scaled multiple businesses and is a big believer in Craft CMS as a tool that benefits both Designer, Developer and Client. 

Share
Feedback
Show us some love
Email Us
We usually reply within 72 hours
Agency Directory
Submit your agency
Affiliate Partners
Let's chat