The example from silverstripe.org/learn/lessons/introduction-to-the-orm?ref=hub, I think I understand the $LatestArticles function part. But where do I define the creation of the records like in the first part of the lesson where $product = Product::create(); Creation goes to controller or where? I'm trying to populate tables coming from a large dataset (from textfile) into defined tables in SIlverstripe.
We've moved the forum!
Please use forum.silverstripe.org for any new questions
(announcement).
The forum archive will stick around, but will be read only.
You can also use our Slack channel
or StackOverflow to ask for help.
Check out our community overview for more options to contribute.
There are two good places for this. The BuildTask class or the DataObject->requireDefaultRecords() method.
The BuildTask is a simple task. You can find them under "mysite.com/dev/tasks"
<?php
class MyDataObjectTask extends BuildTask {
protected $title = 'MyDataObject Build Task';
protected $enabled = true;
public function run($request) {
$list = array(); // dataset to import
foreach ($list as $item) {
$myDataObject = MyDataObject::create();
$myDataObject->Foo = 'Bar';
$myDataObject->write();
DB::alteration_message('MyDataObject #' . $myDataObject->ID .' created', 'created');
}
}
}
DataObject->requireDefaultRecords() is a method in your DataObject. It will be automatically called on /dev/build.
<?php
class MyDataObject extends DataObject {
private static $db = [
'Foo' => 'Varchar(3)'
];
public function requireDefaultRecords() {
parent::requireDefaultRecords();
// execute only if MyDataObject is empty
if (!MyDataObject::get()->exists()) {
$list = array(); // my dataset to import
foreach ($list as $item) {
$myDataObject = MyDataObject::create();
$myDataObject->Foo = 'Bar';
$myDataObject->write();
DB::alteration_message('MyDataObject #' . $myDataObject->ID .' created', 'created');
}
}
}
}