Let's continue building out our Contact Form by creating a field group to hold our contact fields.
Let’s continue building out our Contact Form by creating a field group to hold our contact fields. For right now, we’ll create a new migration to handle this. Later on in the course we’ll create a mega migration that makes it easier to set up everything in one fell swoop.
craft migrate/create add_contact_form_group
In this migration we’ll create a single field group called “Contact Form” with the name property. When we run this migration, it will create a new field group in Craft. We’ll use it in the next video when we create our first fields migration.
We need to use the FieldGroup
model and the construct a query, so we’ll import craft/models/FieldGroup
and craft\db\Query
.
use Craft;
use craft\db\Migration;
use craft\models\FieldGroup;
use craft\db\Query;
Next in the safeUp()
method, we will define the new field group. The new field group only needs the name
attribute.
$fieldGroup = new FieldGroup([
'name' => 'Contact Form',
]);
And then we return the saveGroup
method to save our new field. The method returns a boolean whether the field was successfully saved or not.
return (Craft::$app->fields->saveGroup($fieldGroup));
For the safeDown
method, we need to query for the group an then delete it by id.
$group = (new Query())
->select('id')
->from('fieldgroups')
->where(['name' => 'Contact Form'])
->one();
return(Craft::$app->fields->deleteGroupById($group['id']));
Okay, let’s give our new migration a try by running craft migrate/up
.
craft migrate/up
Looks good! Let’s test the safeDown()
method to make sure that’s working okay, too.
craft migrate/down
Now we’ve been able to create a field group with a content migratino. In the next video we’ll create the fields that will belong to the the field group.
Content Migrations in Craft is made up of the following videos: