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

ModelAdmin saves twice on adding?


Go to End


3 Posts   1621 Views

Avatar
theAlien

Community Member, 131 Posts

25 January 2010 at 1:34pm

Edited: 25/01/2010 1:35pm

Hi,

I have a DataObject (A) in ModelAdmin that's supposed to save data to a record on another DataObject (B) in an onBeforWrite-method.
But if I'm adding a new DataObjectA, it doesn't save to one record, but to two records on DataObjectB...

Does someone know what's happening here and how to solve this?
Below is the structure:

class DataObjectA extends DataObject{

static $db = array(
"titleA" => "Varchar",
);

static $has_many = array(
"DataObjectB" => "DataObjectB",
);

public function onBeforeWrite() {

$myDataObjectB = new DataObjectB();
$myDataObjectB->titleB = "NewTitle";
$myDataObjectB->write();

parent::onBeforeWrite();

}

class DataObjectB extends DataObject{

static $db = array(
"titleB" => "Varchar",
);

static $has_one = array(
"DataObjectA" => "DataObjectA"
);

}

BTW If DataObjectA exists and you click save, it will save just one new record on DataObjectB

Avatar
Hamish

Community Member, 712 Posts

26 January 2010 at 12:47pm

For a new record there are two operations - a 'create' and an 'update'. That is, onBeforeWrite will be called twice. The first time, the ID will be 0, so you can use that to figure out what operation is happening.

Basically, if you wrap your code in "if($this->ID) { ... }" it should fix your problem.

Avatar
theAlien

Community Member, 131 Posts

26 January 2010 at 1:44pm

thanks, works like a charm