Problems when saving multiple articles using articleModel->save()

155 views
Skip to first unread message

mixa...@gmail.com

unread,
May 5, 2023, 3:56:53 PM5/5/23
to Joomla! General Development
Hi, I am trying to batch save some articles using a foreach loop.

I am facing the two following issues :
  1. If the category does not exist, in the first run in the loop, a category is created with name and alias of the catid.
    But in the second run, the exact same thing is happening an error "Another category with the same parent category has the same alias." is thrown.

  2. The articles ID is always the same, so in every save the next article, overwrites the previous one. I discovered that, adding a breakpoint and checking the content in every run.
Any Ideas ?

Here is the code :

use Joomla\CMS\Factory;
use Joomla\CMS\Filter\OutputFilter;

$app = Factory::getApplication();
$mvcFactory = $app->bootComponent('com_content')->getMVCFactory();
$articleModel = $mvcFactory->createModel('Article', 'Administrator', ['ignore_request' => true]);

$articles = [
[
    'catid' => 12,
    'alias' => OutputFilter::stringURLSafe('My Article 1'),
    'title' => 'My Article 1',
    'introtext' => 'My Article Intro Text',
    'fulltext' => 'My Article Full Text',
    'state' => 1,
'language' => '*',
],
[
    'catid' => 12,
    'alias' => OutputFilter::stringURLSafe('My Article 2'),
    'title' => 'My Article 2',
    'introtext' => 'My Article Intro Text',
    'fulltext' => 'My Article Full Text',
    'state' => 1,
'language' => '*',
],
];

foreach($articles as $article) {
if (!$articleModel->save($article)) {
    throw new Exception($articleModel->getError());  
}

Thank  you

Viper

unread,
May 5, 2023, 5:36:08 PM5/5/23
to Joomla! General Development
Create model inside foreach loop. When you do it outside, the model state is still the same on each loop.

mixa...@gmail.com

unread,
May 6, 2023, 3:57:23 AM5/6/23
to Joomla! General Development
Yeap, This solves the problem with the articles with same id.
Thank you.

The issue with category remains though.

Viper

unread,
May 6, 2023, 2:17:06 PM5/6/23
to Joomla! General Development
Check if category exist. It can be done by calling getItem() from Joomla\Component\Categories\Administrator\Model\CategoryModel or implement your own method to check category by title.

mixa...@gmail.com

unread,
May 6, 2023, 3:42:28 PM5/6/23
to Joomla! General Development
Well...
This is what I wanted to avoid :p
I didn't find an easy way (I mean some built-in method) to check for the category by title or alias, so I just used the Factory::getDbo() and built a query and check with  ...$db->setQuery in my method as you proposed.

Anyway I think that this should be done upon article->save. 
I could even call it a bug.

Than you for your help !

Reply all
Reply to author
Forward
0 new messages