Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

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.

Data Model Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Creating Records and Database Lessons


Go to End


2 Posts   1606 Views

Avatar
SilverstripeNewbie

Community Member, 14 Posts

2 October 2015 at 7:13am

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.

Avatar
Devlin

Community Member, 344 Posts

2 October 2015 at 9:03pm

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');
			}
		}	
	}

}