Jump to:

3430 Posts in 1057 Topics by 734 members

Data Model Questions

SilverStripe Forums » Data Model Questions » ModelAdmin saves twice on adding?

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

Page: 1
Go to End
Author Topic: 896 Views
  • theAlien
    Avatar
    Community Member
    131 Posts

    ModelAdmin saves twice on adding? Link to this post

    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

  • Hamish
    Avatar
    Community Member
    712 Posts

    Re: ModelAdmin saves twice on adding? Link to this post

    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.

  • theAlien
    Avatar
    Community Member
    131 Posts

    Re: ModelAdmin saves twice on adding? Link to this post

    thanks, works like a charm

    896 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.