Quantcast
Channel: Joomla! Forum - community, help and support
Viewing all articles
Browse latest Browse all 600

Joomla! 5.x Coding • DB rows duplicating on save() method

$
0
0
Environment: Joomla 5.1.1 + MySql 8

I've tried to use the save($data) method of Joomla AdminModel to do some insert or update operations. For example let the $data->id is a primary key in the database.
I thougth if I set the $data->id to null, then the save method insert new record, and if I assign an existing ID to the $data->id then the save method update an existing record.
However the save method inserts a brand new record (with a new ID of course) regardless of the existing and valid ID.

I clean the code for brevity (I hope :) )

Code:

$m = new ExampleModel();//this will be return an existing database row id OR null if there is no row for some filter$oldDbId = $m->getDataByFilter($foo);$newObjectToSaveOrUpdate = getExampleData();$newObjectToSaveOrUpdate->id = $oldDbId;$m->save($newObjectToSaveOrUpdate);
I have debugged the code and checked these:
  • the object to save has the expected data
  • newObjectToSaveOrUpdate->id has null value to check if it will be inserted
  • newObjectToSaveOrUpdate->id has valid ID to check if it will be updated
I found a core hacking solution, but as you all know, that is rarely a valid solution, so I avoid to put into production.
In the libraries\src\MVC\Model\AdminModel.php in the save($data) method there is this code:

Code:

$pk    = (isset($data[$key])) ? $data[$key] : (int) $this->getState($this->getName() . '.id');$isNew = true;
Which is set $isNew to true regardless if there is a given primary key or not.
And if I change that line to this:

Code:

$isNew = !isset($data[$key]);
The save() method works like a charm as I expected.

However I have another expectation. This change will bring me some nasty gift later. Not to mention to always check it after every Joomla update.

So what did I wrong? Because I am pretty sure I should not touch core code.

Statistics: Posted by miertnemmukodik — Tue Sep 17, 2024 12:20 pm



Viewing all articles
Browse latest Browse all 600

Trending Articles





<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>