Skip to content

Instantly share code, notes, and snippets.

@eriweb
Created January 8, 2018 22:14
Show Gist options
  • Save eriweb/f865d982bc7979f5235a11e3fd8d219a to your computer and use it in GitHub Desktop.
Save eriweb/f865d982bc7979f5235a11e3fd8d219a to your computer and use it in GitHub Desktop.
public function safeUp()
{
$fieldGroupName = 'myFieldGroup';
$fieldService = Craft::$app->getFields();
$fieldGroup = new FieldGroup();
$fieldGroup->name = $fieldGroupName;
$fieldGroupSuccess = $fieldService->saveGroup($fieldGroup);
if ($fieldGroupSuccess) {
$fieldGroupId = null;
// FIXME: Couldn't find a method to search for a field group by name
$fieldGroups = $fieldService->getAllGroups();
foreach ($fieldGroups as $_group) {
if ($_group->name == $fieldGroupName) {
$fieldGroupId = $_group->id;
}
}
if (!$fieldGroupId) {
echo "Couldn't find ID for field group, aborting";
return false;
}
$field = $fieldService->createField([
'type' => 'craft\fields\PlainText',
'groupId' => $fieldGroupId,
'name' => 'fieldName',
'handle' => 'fieldNameHandle'
]);
}
return $fieldService->saveField($field);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment