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 contact form is going to have a series of simple fields for the user to fill out. The fields we’ll create are:
All of these fields will be of the type plain text except the email field.
Let’s create our migration file:
craft migrate/create add_form_fields
We want to assign our new fields to the group we created 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 create 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 “Contact 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 create them all as part of the return statement.
First, we’ll import the PlainText and Email classes 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 create 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)
);
Creating the safeDown()
method is similar 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 statement. That method returns a boolean so if one of those fail then the entire migration will fail. If they all pass then the entire migration will succeed.
Okay, let’s test both methods in our migration and see how they work.
craft migrate/up
This should successfully create all of our fields and assign them to the correct group.
Content Migrations in Craft is made up of the following videos: