Skip to content

Instantly share code, notes, and snippets.

@mgburns
Last active March 17, 2018 20:46
Show Gist options
  • Save mgburns/ba5fc984336af0db3c2a7b42f322dd8d to your computer and use it in GitHub Desktop.
Save mgburns/ba5fc984336af0db3c2a7b42f322dd8d to your computer and use it in GitHub Desktop.
<?php
namespace craft\contentmigrations;
use Craft;
use craft\base\Field;
use craft\elements\Entry;
use craft\models\Section;
use craft\models\Section_SiteSettings;
use craft\db\Migration;
/**
* m180317_193558_add_home_page migration.
*/
class m180317_193558_add_home_page extends Migration
{
/**
* @inheritdoc
*/
public function safeUp()
{
// Create a text field
$fields = Craft::$app->getFields();
$bodyField = $fields->createField([
'type' => 'craft\\fields\\PlainText',
'groupId' => 1,
'name' => 'Body',
'handle' => 'body',
]);
echo ' > creating "Body" field ...';
$fields->saveField($bodyField);
echo " done\n";
// Create a homepage section
$sections = Craft::$app->getSections();
$siteId = Craft::$app->sites->getPrimarySite()->id;
$homepageSection = new Section([
'name' => 'Homepage',
'handle' => 'homepage',
'type' => Section::TYPE_SINGLE,
'siteSettings' => [
$siteId => new Section_SiteSettings([
'siteId' => $siteId,
'hasUrls' => true,
'uriFormat' => '__home__',
'template' => '_homepage',
])
]
]);
echo ' > creating "Homepage" section ...';
$sections->saveSection($homepageSection);
echo " done\n";
// Set the field layout for the associated entry type
$homepageEntryType = $sections->getEntryTypesByHandle('homepage')[0];
$fieldLayout = $fields->assembleLayout([
'General' => [
$fields->getFieldByHandle('body')->id,
],
]);
$fieldLayout->type = Entry::class;
$homepageEntryType->setFieldLayout($fieldLayout);
echo ' > saving "Homepage" entry type ...';
$sections->saveEntryType($homepageEntryType);
echo " done\n";
// Add content to the homepage section
$elements = Craft::$app->getElements();
$homepageEntry = Entry::find()->section('homepage')->one();
$homepageEntry->body = 'This is the body text.';
// $homepageEntry->setFieldValue('body', 'This is the body text.');
echo ' > updating "Homepage" entry ...';
$elements->saveElement($homepageEntry);
echo " done\n";
}
/**
* @inheritdoc
*/
public function safeDown()
{
echo "m180317_193558_add_home_page cannot be reverted.\n";
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment