Does anybody have any idea of how I can check whether or not a dataobject already exists? I'm just looking for an if statement that I can use before making my dataobject that I want to create.
Thanks
This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.
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.
Does anybody have any idea of how I can check whether or not a dataobject already exists? I'm just looking for an if statement that I can use before making my dataobject that I want to create.
Thanks
if(DataObject::get_one('DataObjectType'))
Thanks for the reply,
I'm actually creating a group on the fly each time I create a page. The group is named by the title of the page so what I would like to do is check that there is not already a group of the same name.
This is the if statement I am using but it doesn't seem to be working for me:
if(DataObject::get_one('Group') != $this->Title)
I'm sure it's just a sytax problem but I can't seem to figure it out
DataObject::get_one() returns the whole object so that comparison won't work. You can however add it as a where cause in the statement
if(DataObject::get_one('Group', "Title != '$this->Title'"))
Thanks willr,
I've tried your suggestion but it seems that this check still is not working, the security group is still being duplicated.
To give you a better idea I have posted the code from my page class here:
static $has_written = false;
function onBeforeWrite(){
if(DataObject::get_one('Group', "Title != '$this->Title'")){
if(!self::$has_written){
$group = new Group();
$group->Title = $this->Title;
$group->write();
}
self::$has_written = true;
}
parent::onBeforeWrite();
}
Well think about what thats saying. Thats saying if there is not a Group without the Title 'Title'. Which will mean it won't work if you have any other group.
Try something like
if(!DataObject::get_one('Group', "Title = '$this->Title'"))
Ah you're the man!
Yes that's it, works like a dream. One more question though related to this, when creating a new page I'm getting a security group being created for 'New Page'. Is there anyway to avoid this happening? I'm not quite sure why this is happening in the first place.
Otherwise works like a charm now though
Thanks again
if($this->Title != "New Page" && !DataObject::get_one('Group', "Title != '$this->Title'")) {
Or is that just too hacky :D
I'm not quite sure why this is happening in the first place.
When you create a page it writes a copy of it (even before you have added any data) to ensure that the page ID exists, allowing you to add things like relationships without saving the page before hand.