Created
September 11, 2017 14:06
-
-
Save Wiejeben/31c52010090d841d0b894c769ba006b0 to your computer and use it in GitHub Desktop.
Craft 3 Migration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace craft\contentmigrations; | |
use Craft; | |
use craft\db\Migration; | |
use craft\models\Section; | |
use craft\fields\PlainText; | |
use craft\models\FieldLayoutTab; | |
use craft\models\Section_SiteSettings; | |
/** | |
* m170911_134136_create_locations_entries migration. | |
*/ | |
class m170911_134136_create_locations_entries extends Migration | |
{ | |
/** | |
* @inheritdoc | |
*/ | |
public function safeUp() | |
{ | |
// Add new field | |
$addressField = new PlainText(); | |
$addressField->groupId = 1; | |
$addressField->name = 'Address'; | |
$addressField->handle = 'address'; | |
$addressField->multiline = true; | |
Craft::$app->fields->saveField($addressField); | |
// Create new section | |
$section = new Section(); | |
$section->name = 'Locations'; | |
$section->handle = 'locations'; | |
$section->enableVersioning = true; | |
$section->type = Section::TYPE_STRUCTURE; | |
$section->maxLevels = 1; | |
// Set section uri and template | |
$allSiteSettings = []; | |
foreach (Craft::$app->getSites()->getAllSites() as $site) { | |
$siteSettings = new Section_SiteSettings(); | |
$siteSettings->siteId = $site->id; | |
$siteSettings->hasUrls = true; | |
$siteSettings->uriFormat = 'locations'; | |
$siteSettings->template = 'locations.twig'; | |
$allSiteSettings[$site->id] = $siteSettings; | |
} | |
$section->setSiteSettings($allSiteSettings); | |
Craft::$app->sections->saveSection($section); | |
// Set-up default entry type of a new section | |
$entryType = $section->getEntryTypes()[0]; | |
$fieldLayout = $entryType->getFieldLayout(); | |
// Create field layout tab to assign fields to | |
$fieldLayoutTab = new FieldLayoutTab(); | |
$fieldLayoutTab->name = 'Content'; | |
$addressField->required = true; | |
$fieldLayoutTab->setFields([$addressField]); | |
$fieldLayout->setTabs([$fieldLayoutTab]); | |
$entryType->setFieldLayout($fieldLayout); | |
Craft::$app->sections->saveEntryType($entryType); | |
} | |
/** | |
* @inheritdoc | |
*/ | |
public function safeDown() | |
{ | |
Craft::$app->sections->deleteSection(Craft::$app->sections->getSectionByHandle('locations')); | |
Craft::$app->fields->deleteField(Craft::$app->fields->getFieldByHandle('address')); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment