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.

Customising the CMS /

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

Default values for relation's pre-existing records


Go to End


3 Posts   927 Views

Avatar
svandragt

Community Member, 44 Posts

13 April 2013 at 1:02am

OK I have added a relation to an existing DataObject with records. The relation is displayed in the CMS through a DropdownField.
I have set the default value for this relation for new records using populateDefaults(), say to 3.

The problem I am having how would I change the default value for records that existed before I added this relationship (as they show up as blank in the GridField and with an ID of 0 in the database for the relationID column).

I can edit the database directly and update all records with ID 0 but an solution coded in the dataobject would be preferable, if this is possible? I also don't want to ask my editors to re-save all records one by one.

Avatar
Willr

Forum Moderator, 5523 Posts

13 April 2013 at 4:27pm

Running a SQL query directly would be less code (and faster) but if you want to do it via the framework one way to do migrations is to use a BuildTask.

<?php

class DoStuff extends BuildTask() {

public function run($request) {
$records = Page::get('Page')->filter(array(
"SomeID" => 0
));

foreach($records as $record) {
$record->SomeID = 3;
$record->write();
}

}

Then run dev/tasks/DoStuff to perform the operation.

Avatar
svandragt

Community Member, 44 Posts

13 April 2013 at 10:15pm

Edited: 13/04/2013 10:16pm

Ah great hadn't used build tasks before, this example is just what I need to get to grips with that also. Thanks so much Willr!