Skip to content

Instantly share code, notes, and snippets.

@mgburns
Last active March 17, 2018 20:47
Show Gist options
  • Save mgburns/dcf08b4982003202926a7f0b892bf54c to your computer and use it in GitHub Desktop.
Save mgburns/dcf08b4982003202926a7f0b892bf54c 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_193559_add_contact_page migration.
*/
class m180317_193559_add_contact_page extends Migration
{
/**
* @inheritdoc
*/
public function safeUp()
{
// Create a text field
$fields = Craft::$app->getFields();
$contactInfoField = $fields->createField([
'type' => 'craft\\fields\\PlainText',
'groupId' => 1,
'name' => 'Contact Info',
'handle' => 'contactInfo',
]);
echo ' > creating "Contact Info" field ...';
$fields->saveField($contactInfoField);
echo " done\n";
// Create a homepage section
$sections = Craft::$app->getSections();
$siteId = Craft::$app->sites->getPrimarySite()->id;
$contactSection = new Section([
'name' => 'Contact Us',
'handle' => 'contact',
'type' => Section::TYPE_SINGLE,
'siteSettings' => [
$siteId => new Section_SiteSettings([
'siteId' => $siteId,
'hasUrls' => true,
'uriFormat' => 'contact',
'template' => '_contact',
])
]
]);
echo ' > creating "Contact Us" section ...';
$sections->saveSection($contactSection);
echo " done\n";
// Set the field layout for the associated entry type
$contactEntryType = $sections->getEntryTypesByHandle('contact')[0];
$fieldLayout = $fields->assembleLayout([
'General' => [
$fields->getFieldByHandle('contactInfo')->id,
],
]);
$fieldLayout->type = Entry::class;
$contactEntryType->setFieldLayout($fieldLayout);
echo ' > saving "Contact Us" entry type ...';
$sections->saveEntryType($contactEntryType);
echo " done\n";
// Add content to the homepage entry
$elements = Craft::$app->getElements();
$contactEntry = Entry::find()->section('contact')->one();
$contactEntry->contactInfo = 'Call me maybe?';
// $contactEntry->setFieldValue('contactInfo', 'Call me maybe?');
echo ' > updating "Contact Us" entry ...';
$elements->saveElement($contactEntry);
echo " done\n";
}
/**
* @inheritdoc
*/
public function safeDown()
{
echo "m180317_193559_add_contact_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