-
MODX Staff
- 730 Posts
I would do it like this:
$wand = $xpdo->getObject('Wand', 123);
if($wand === null) {
$wand = $xpdo->newObject('Wand', array('primary_key'=> 123));
}
$wand->save();
-
☆ A M B ☆
- 2,475 Posts
Ok... but as to my question: no matter how to quantify which object you loaded up, does that method result in an UPDATE? Or does it attempt to create a NEW object?
-
MODX Staff
- 730 Posts
Pretty sure that if you have a ->newObject()
it’s always going to result in an INSERT so if you assign the pk of an existing object, you’ll have a problem.
Raising the dead here but, reading this gives me the impression that there is no class extension to update a record?
So, do I have to just use the regular beginTransaction and commit methods?
I've never used transactions (the MyISAM engine doesn't support them). I don't see why they would be necessary.
AFAIK, if you get the object with $modx->getObject(), the save() will result in an update automatically. If you intend to create a new object, it's good form to call getObject() first to make sure it doesn't already exist. The return value of getObject() will be empty if the object doesn't exist and you can then safely call newObject() and save it.
try
if ($object=$modx->getObject($classname,array('yourfield'=>'yourvalue'))){
}else{
$object=$modx->newObject($classname);
}
if ($object){
$object->fromArray($yourvalues);
$object->save();
//get the id of the newly created object
$newid = $object->get('id');
}