Creating a Craft CMS Field Type

Setting Up a Craft CMS Module for a Field Type

We’re going to use the Craft Module starter module that is available on my Github account. Installing it is as simple as following the instruction. Let’s walk through these together.

We want to focus on build­ing our first field type for this course, so we’ll start with a sim­ple pre-built Craft module. 

We’re going to use the Craft Mod­ule starter mod­ule avail­able on my Github account. Installing it is as sim­ple as fol­low­ing the instruc­tion. Let’s walk through these together.

  1. Down­load the mod­ule as a zip file.
  2. Unzip the down­loaded file. 
  3. Rename to craft-module
  4. Place the entire direc­to­ry in the modules direc­to­ry in your Craft project. I’m going to do this in my CraftQuest project.
  5. Update the Craft project config/app.php to boot­strap the module. 
  6. Update the project’s composer.json file so that the class file is includ­ed in Composer’s autoload files. After that, we’ll need to rebuild the autoload files:
    composer dump-autoload
    

With that done, we should be able to load our site just as before. Our mod­ule doesn’t do any­thing yet, so Craft should just boot­strap it and then con­tin­ue on as nor­mal. No errors is good good news.

Prepar­ing for a Field Type

To pre­pare for our cus­tom fields, let’s cre­ate a fields direc­to­ry inside the mod­ule src direc­to­ry to hold the cus­tom fields code. Sup­pose you’ve fol­lowed along in my oth­er cours­es on extend­ing Craft. In that case, you will rec­og­nize this pat­tern of cre­at­ing direc­to­ries inside the src direc­to­ry for each com­po­nent we are adding to Craft.

craft-module
├── README.md
└── src
    ├── CraftModule.php
    └── fields

Inside the fields direc­to­ry, we will cre­ate a class file for each field type that we want to make. 

In the fol­low­ing video, we’ll work on our first field type for a world lan­guage dropdown.

Creating a Craft CMS Field Type is made up of the following videos: