Content Migrations in Craft

Creating Fields with a Content Migration

Our contact form is going to have a series of simple fields for the user to fill out. Let's create them with a content migration.

Our con­tact form is going to have a series of sim­ple fields for the user to fill out. The fields we’ll cre­ate are:

  • First Name
  • Last Name
  • Email Address
  • Mes­sage

All of these fields will be of the type plain text except the email field.

Let’s cre­ate our migra­tion file:

craft migrate/create add_form_fields

We want to assign our new fields to the group we cre­at­ed in the last video, so the first step we need to take is to get that group ID so we can pass it in when we cre­ate the new fields.

First we’ll import craft\db\Query class:

use craft\db\Query;

and the inside of the safeUp() method, we get the group. We’ll fetch it by name, which is Con­tact Form”.

$group = (new Query())  
 	->select('id')  
	 ->from('fieldgroups')  
	 ->where(['name' => 'Contact Form'])  
	 ->one();

Our approach right now for the fields will be to define the fields and then cre­ate them all as part of the return statement.

First, we’ll import the Plain­Text and Email class­es we need to define the fields:

use craft\fields\PlainText;  
use craft\fields\Email;

And then define our fields inside of the safeUp() method. The first name and last name fields will be plain text field types, but we’ll use the native Email field type for the email address field.

$firstNameField = new PlainText([  
	 'groupId' => $group['id'],  
	 'name' => 'First Name',  
	 'handle' => 'firstName',  
	 'required' => true,  
	 'charLimit' => 150,  
	 'multiline' => false,  
]);  
  
$lastNameField = new PlainText([  
	 'groupId' => $group['id'],  
	 'name' => 'Last Name',  
	 'handle' => 'lastName',  
	 'required' => true,  
	 'charLimit' => 150,  
]);  
  
$emailAddressField = new Email([  
	 'groupId' => $group['id'],  
	 'name' => 'Email Address',  
	 'handle' => 'emailAddress',  
	 'required' => true  
]);

To cre­ate the fields we’ll call the saveField method for each one in the return statement.

return(  
	 Craft::$app->fields->saveField($firstNameField) &&  
	 Craft::$app->fields->saveField($lastNameField) &&  
	 Craft::$app->fields->saveField($emailAddressField)  
);

Cre­at­ing the safeDown() method is sim­i­lar to what we did with the field group. We need to find the id of each field and then pass it in to the deleteFieldById method inside of the return state­ment. That method returns a boolean so if one of those fail then the entire migra­tion will fail. If they all pass then the entire migra­tion will succeed.

Okay, let’s test both meth­ods in our migra­tion and see how they work. 

craft migrate/up

This should suc­cess­ful­ly cre­ate all of our fields and assign them to the cor­rect group. 

Content Migrations in Craft is made up of the following videos: