Using fields

by Gisle Hannemyr

One of the main features of Drupal is that it is possible to enhance existing content types and even create new content types for a website using the GUI. Also the user entity can be expanded in a similar way. This is done by means of the core Field module. This chapter demonstrates how to use the Field module to add custom fields to a content type to cater for various types of content.

Table of contents

Introduction

Field types.

One of the main features of Drupal is that its entities are extensible by means of Drupal's administrative GUI without requiring any custom code. I.e.:

  1. Any existing entity (such as a specific type of content) can be modified by adding or subtracting fields.
  2. You can define new content types of the content entity that will work within the same framework as Drupal's pre-defined content types.

The term field refers to a given piece of content within an entity. A field is characterised by having a field name, field type and widget. Drupal comes with a set of core field types (as shown in the menu reproduced to the right). A widget in this context can be a HTML5 form element or jQuery widget that is to be used for data entry.

The content that makes up a Drupal websites is a collection of entities stored in the site's database. An entity can be viewed as a container for fields, where the term field refers to a typed piece of content. A field is characterised by having a field name, field type and widget. The bundle of fields that make up a Drupal entity is called a bundle.

The purpose of the core Field module is to manage fields. It allow administrators add to or subtract from the fields that constitute a bundle. In other words, the Field lets the site builder make custom subtypes of the Drupal content entity, without having to do any programming.

noteThe content entity is Drupal's main container for content. Since “content” is a generic term, and the content entity is stored in the {node} base table in the database, the term “node content type” is sometimes used to refer to types of the content entity in order to distuingish it from other types of entities, such as users, comments, taxonomy terms and files. However, in the Drupal community, when you see the term “content type” it always means “node content type” (i.e. a type of the content entity – not a type of some other entity). Also, in the Drupal community, the term “node” always means “instance of node content type”.

The core only comes with a few basic field types and widgets to handle input. To go beyond what is provided in the core, Drupal let website designers add field types by enabling contributed modules. In the Drupal ecosystem, there exists projects that provide modules for a number of typed fields, such as date fields, entity reference fields, and link fields. See the chapter Introduction to projects to learn about how use contributed projects to add field types to a site.

noteThis chapter is about how to create specific node content types by means of fields. Beware that Drupal fields can be used with any entity, not only content. For instance, to add fields to the user entity, navigate to Configuration » People » Account settings » Manage fields and add new or existing fields to the user entity.

Enabling the required modules

First make sure the the three modules required to work with fields are enabled. They are part of core and should be enabled by default, but just to make sure, log in as an administrator, and navigate to Modules and scroll down to see that there is a tick mark in the box to the left of the three modules Field, Field SQL storage and Field UI.

Enabled.

Notice that tick mark next to Field and Field SQL storage is greyed out. This is because both are required by Field UI. Drupal will not let the administrator disable a module if the module is required by another enabled module.

Finally, scroll down to the bottom of the page and click Save configuration.

Creating a new content type

For an alternative tutorial, see the chapter describing how to create a Guestbook content type.

In this tutorial, we shall by means of example create a content type that can hold information about cameras.

(If you want to modify an existing content type (such as “Article”) instead of creating a new one from scratch, skip ahead to the section with the title “Adding fields”.)

To create this new content type, navigate to Structure » Content types » Add content type. First, you need to give the new content type a Name (e.g. «Camera»). It also needs a machine name for internal representation. The computer suggests «camera», and that's fine. The machine name is used to to construct the URL of the create content page for the content type, and must be unique. You should also add a brief Description of the content type. This description will show up in the list of content types, and when the user click on Add content and are prompted to pick a content type.

After giving the new content type a Name and a Description, scroll down to set up the workflow for adding content of this type.

First, set the Title field label to something sensible for this particular content type

In the case of the Camera content type, it doesn't really make sense to have a Title. Instead entities should be headed with a “Camera model” designation.

Also take the time to fill in an Explanation or submission guidelines to help the user understanding what is expected. Later, we're going to create a pull down menu to select the brand of the camera. That is why we refer to a pull down menu in the submission guidelines for this content type.

The Preview before submitting radio-button sets whether preview should be set to one of Disabled, Optional or Required (the Required option is guaranteed to annoy users).

The left half of the lower half of this forms works as tabs that gives access to more options when clicked. The current setting is shown. Here's a brief summary:

The screen shot below shows the Add content type-form with filled-in fields.

Add content type

When done, click Save content type. Now the Camera content type has been created. It is a subtype of the content entity.

Managing fields

You are now ready to begin customising this new content type. Note that it is possible to do this with any entity, but most common entity to customise in this way is subtypes of the content entity. The Camera content type we've just created is a subtype of the content entity.

Start by navigating to Structure » Content types. If you just installed Drupal, you'll see the two default content types (Article and Basic page that is part of core and enabled by default) and the new content type we just created (Camera).

List content type

First click on edit in the Camera row. Locate the Title field label and change it from “Title” to “Camera model”. Then press Save content type.

To configure the fields that make up the new content type, click on manage fields in the Camera row. This brings up a form that show what fields are already present in the Camera content type, and where we can delete or add fields to the content type. This form will look like the screen shot below:

manage fields

As seems un the screen shot above, two fields are already present. They are labelled “Camera model” and “Body”. It is possible to delete the “Body” field (press delete in the Operations column). But we shall keep it, as it will be handy for long text descriptions of camera models, we are just going to a few details. To do that, click edit.

This takes you to a large form that let you edit a lot of settings. It is divided into to major parts: Camera settings and Description field settings. The Camera settings portion apply only to the Description field when used in the Camera content type. The Description field settings part apply to the Description field everywhere it is used (not only in the Camera content type).

The screen shot below only show the top of the Camera settings part of the form, where we replace the Label “Body” with “Description” and type in some Help text.

edit

As for the elements of this form, is is a brief summary of all the settings:

noteIt is not possible to set the default filtered text format in this form. The Text processing radio button toggles whether the text format menu below the text field is enabled. Whenever the text format menu is enabled (radio button set to Filtered text), the default format is always the formats with the lowest weight (to set up weights, navigate to Configuration » Text formats).

Click Save settings when done fine tuning the Camera and Description field settings.

Adding fields

Now, we are going to add a couple of custom field to the Camera content type.

Start by navigating to Structure » Content types. If you just installed Drupal, you'll see the two default content types (Article and Basic page that is part of core and enabled by default) and the new content type we just created (Camera).

List content type

The field will be used to indicate camera brand. To add it, go back to the list of content types, and click on manage fields in the Camera row. This takes us back into the field manager. This time, we are going to add a new field where the user can pick the camera brand from a menu widget (Select list). The screen shot below shows how to fill in the Add new field row to add a new field labelled “Brand”.

Click on the link “manage fields” for the content type you want to modify (i.e. “Camera”). This brings you to the follwing screen.

manage fields

The first element (Label) is the human readable label that is going to be used in various displays. You can change this later if you want to. For now, enter the label “Brand” into the form.

The second element (Field name) is the name that is going to be used internally by the database for the field. This name can not be changed later. Use the field name “field_brand” for the brand field.

Field types.

The third element is the field type and is labelled Type of data to store. We pick the field type from a drop-down menu of available field types. The field type initially selected can not be changed, sp choose this carefully. With the only the default Drupal core installed, the following field types appear in this menu:

If contributed modules have been installed and enabled, more field types may appear in this menu.

You want to store the information about the brand in a compact and efficient format. Since there is only a limited number of camera brands in the world, an enumerated list with all of those we're interested in will work well. This is why we set “field_brand” to be of field type List (text).

The fourth and last item (Form element to edit the data) determines the interface or widget to use for user input. Depending on the field type of data, the following alternatives exists in core:

tipA widget is an object for capturing, editing and validating user input and possibly also displaying data, tied to the field type of the data. In the field creation form, the widget is referred to as “Form element to edit the data”. Installing a contributed project may provide additional field types and widgets.

Picking the Select list widget lets the designer create a list of DSLR camera brands that can be exposed to the user by means of a pull-down menu, radio buttons, or checkboxes.

After filling in or selecting appropriate values for Label, Field name, Type of data to store and Form element to edit the data, click Save to save the Camera content type with the new field added.

After the brand field in the camera content type has been created, you need to set up the select list with suitable values. To do this, click on the link List (text) on the Manage fields page in the row with the label “Brand”.

The Allowed values list is used to create a list of allowed of alternatives. It is possible to do this in two ways. The simplest method is to enter a list of values, one for each line. In that case, the value entered will be used a both key and label. Alternatively, the list may consists of pairs where a vertical bar character is used to separate the a key from a label. The key is the internal value stored in the database. The label is the string that will be displayed in pull.down menus, etc.

The screen shot below shows the allowed value list filled in. It is simply a list of allowed camera brands, one per line.

Allowed values list.

Click Save field settings to save this list. This takes you back to the the the Manage fields panel for the Camera content type. Now, to complete the configuration of the Brand field click on the edit link in the operations column.

We've already visited this form, when we set up the Help text, etc. for the camera Description field. However, since the field type and widget is different (i.e. List (text) and Select list instead of Long text and summary and Text area with a summary), the list of settings are slightly different.

We want to make the brand a Required field, and we also want to provide a sensible Help text. Make sure Number of values is set to one.

After we've finished specifying the list of allowed values, we need to click on Save field settings to save the list. This will take us back to the field management page. To complete the Camera content type, we are going to add an additional field, indicating the approximate selling price of the particular camera model.

We want the price to be in whole USD, so we set the type of data to store to integer. However we want the user to type in the price, instead of selecting from a list of controlled values. This is how to make a field for the price of the camera.

Add new field.

After filling in the form, click Save to save the price field. Then click on the edit link to the right of Price. This takes to a form where we can specify Camera settings and Price field settings:

We do not want to make the Price field required. Use the Prefix setting to indicate the currency of the price (e.g. “USD ” – notice the space). Number of values should be set to one.

When done, click Save settings, which again takes you back to the field management page for the Camera content type where the two newly created custom fields, “Brand” and “Price” appear at the end of the list of fields.

Before you leave the field management screen, rearrange the fields so that they appear in logical order in the form the user is going to fill in when creating camera content. Place Brand at the top (before Camera model). Place Price between Model and Description.

field_11.png

Drupal provides a drag&drop interface that makes it very easy to rearrange the sequence of fields in a form. Put the cursor over the the cross-shaped arrows on the and press the left button on the mouse. Drag the element into position using the mouse, and then release the button.

After arranging the fields in the appropriate sequence, remember to click Save to save the changes.

Ordinary users should be able to work with content of this new DSLR camera content type. This means that we must give the users permissions to create, edit and delete DSLR camera content. This is done by navigating to People » Permissions, checking the required permissions as shown below.

Permissions.

In the example, all authenticated users are allowed to create, edit and delete own camera content, but only the users that has the role of administrator are allowed to edit or delete camera content created by others.

Creating content

Field types.

Now we're done creating the Camera content type. The next step is to test the new type. Log out of the Administrator account, and log on again as an ordinary user. Expand the Add content menu. Camera should appear, after the built-in types Article and Basic page.

Click on the Camera link, and the form to create content of type Camera shall appear. The form shown below has been filled in with data about the Nikon D90.

Form.

After filling in this form with data about a particular camera model, clicking the Save button below the form will save the content in the database.

Displaying a custom content type

So far, our interactions with the custom content type have all used the Manage fields panel as a starting point. This panel lets us control how the fields are presented in the form that is displayed in the Create Camera form, but does not determine how the content is displayed after it has been created. Now is the time to configure how this content type is to be displayed.

Click on the Manage display tab. This takes us to a form where we can set up various display formats. The display settings that are shown initially are for a Default format.

If the Custom display settings menu isn't expanded, click on it to expand it.

Display fields.

In the screen shot above, notice the tick mark next to the Teaser view mode. This means that we can customise how content is shown in the Teaser view mode by setting up a Teaser format. The Default format will at least be used for the Full content view mode. The Full content view mode is typically used when the content is displayed on its own page. It is also possible to create a custom format for the three other view modes (i.e. RSS, Search index, and Search result). We may do that eventually, but in this tutorial, we are going to leave those alone, which means that the Default view mode will be used for all view modes except Teaser.

Whenever we enable a custom view mode by placing a tick mark next to it in Custom display settings menu (and clicking Save to effectuate), a button corresponding to the view mode appear next to Default button near the top of the form. Clicking on the button takes to a form where we can configure the custom view mode.

But first, we shall configure the Default view mode.

We start out by reordering the fields. We want both the Brand and Price to appear above the Description, so we use use the mouse to drag them into the right order.

Each field has a Label column to determine where the label is to appear relative to the content stored in the field. The three options are:

We want the labels for both the Brand and Price fields to appear in-line. and we hide the Description label.

The Format column determine how the content is displayed. The options available through the pull-down menu depends on the field type, but there is always a <Hidden> option to hide the content of the field. In this case, we just rely on the Default format for all three fields.

In the Price row, notice that an icon of a little cogwheel is present. Next to the cogwheel is a little summary of the current settings. In the screen shot above, the space in the sequence “1 234“ signify that space is used in an integer as thousands separator, and that any prefix and suffix is integrated into the display.

Clicking on the cogwheel icon expands the row and let us further customise how the price is displayed.

After setting up the Default view mode, click on the Save button below the form to save the settings.

If we set up the default display for the Camera content type as described above, the screen shot below shows how the display of a specific DSLR camera may look like:

D90

After we've verified that the default display is nice, we need to go back and configure the Teaser view mode. Again, we start out by putting the fields in the right order. However, in Teaser mode, we do not want show the full description, but only a trimmed version. Select the Trimmed format for the Description field. Then click on the cogwheel icon to set the trim length to 300 characters.

The Teaser view mode is typically a shorter format that is used by Drupal in lists of multiple content items.

Troubleshooting

Mismatched entity and/or field definitions [D8+]

Fixing this was at one point automatic, but was deprecated in Drupal 8.7.0 [2019-03-08] (Re: Support for automatic entity updates has been removed).

To fix it, install and enable Devel Entity Updates. This enables this drush command:

$ drush entup

See alsoSource: Drupal.SE - Jaypan [2019-06-14]. See also forum comment by D_Wicz [2020-06-24].

Final word

The Field module that is part of the Drupal core is a very powerful tool in capable hands. This tutorial has demonstrated how to use the Field module to create a basic custom content type.

See alsoNote that we've just scraped the surface. The Field module is anong the most powerful and versatile tools in the Drupal tool-chest. You may want to visit the community documentation for more comprehensive coverage.


Last update: 2018-03-11.