I have been trying to get my head wrapped around Migrations in Craft 3 and find myself struggling with added a new section.
I have managed to add a new volume, but not a section. Here’s where I have got to so far…
<?php
namespace craft\contentmigrations;
use Craft;
use craft\db\Migration;
/**
* m180428_195138_test migration.
*/
class m180428_195138_test extends Migration
{
/**
* @inheritdoc
*/
public function safeUp()
{
if (is_null(Craft::$app->volumes->getVolumeByHandle("newvolume"))) {
$volume = new \craft\volumes\Local([
"name" => "New volume",
"handle" => "newvolume",
"hasUrls" => true,
"url" => "@web/images/newvolume",
"path" => "@webroot/images/newvolume"
]);
Craft::$app->volumes->saveVolume($volume);
}
if (is_null(Craft::$app->sections->getSectionByHandle("awesomeNews"))) {
$section = new \craft\models\Section([
'name' => 'Awesome News',
'handle' => 'awesomeNews',
'type' => 'Channel',
'siteSettings' => [
new \craft\models\Section_SiteSettings([
'siteId' => Craft::$app->sites->getPrimarySite()->id,
'enabledByDefault' => true,
'hasUrls' => true,
'uriFormat' => 'foo/{slug}',
'template' => 'foo/_entry',
]),
]
], true);
Craft::$app->sections->saveSection($section);
}
}
/**
* @inheritdoc
*/
public function safeDown()
{
$newvolume = Craft::$app->volumes->getVolumeByHandle("newvolume");
if (!is_null($newvolume)) {
Craft::$app->volumes->deleteVolumeById($newvolume->id);
}
$awesomeNews = Craft::$app->sections->getSectionByHandle("awesomeNews");
if (!is_null($awesomeNews)) {
Craft::$app->volumes->deleteSectionById($awesomeNews->id);
}
}
}
The migration states it has been successful, however, I only see the new volume, not the section. I have tried to execute this with only the block relating to the section.
Does anyone know if it is possible to create a new section with Migrations? If it is, any idea what may be wrong with the above?