2

I want to be able to add many articles programmatically in Joomla, from the command line using the cli feature in Joomla CMS.

I am basically using Create a Joomla! Article Programmatically but my script closes out after creating just one article with the error line

Error displaying the error page: Application Instantiation Error:Application Instantiation Error

This is the code that I am running from within the /cli folder in Joomla.

I am using Joomla 3.4

<?php
const _JEXEC = 1;

if (file_exists(dirname(__DIR__) . '/defines.php'))
{
    require_once dirname(__DIR__) . '/defines.php';
}

if (!defined('_JDEFINES'))
{
    define('JPATH_BASE', dirname(__DIR__));
    require_once JPATH_BASE . '/includes/defines.php';
}

require_once JPATH_LIBRARIES . '/import.legacy.php';
require_once JPATH_LIBRARIES . '/cms.php';
require_once JPATH_CONFIGURATION . '/configuration.php';


class AddArticle extends JApplicationCli
{
    public function doExecute()
    {
        $count = 10;
        while ($count > 0) 
        {
            $count--;

            $jarticle                   = new stdClass();
            $jarticle->title            = 'New article added programmatically' . rand();

            $jarticle->introtext        = '<p>A programmatically created article</p>';

            $table = JTable::getInstance('content', 'JTable');
            $data = (array)$jarticle;

        // Bind data
            if (!$table->bind($data))
            {
                die('bind error');
                return false;
            }

        // Check the data.
            if (!$table->check())
            {
                die('check error');
                return false;
            }

        // Store the data.
            if (!$table->store())
            {
                die('store error');
                return false;
            }
    }
}
}

JApplicationCli::getInstance('AddArticle')->execute();
Cœur
  • 37,241
  • 25
  • 195
  • 267
user1104799
  • 161
  • 3
  • 13
  • I'd say the following: it is mandated that you have a category id for a category that exists and you need to have a user id for the creator. You can predefine these in various ways e.g. finding hte uncategorized category and the first user. – Elin Oct 20 '15 at 02:49

1 Answers1

2

I was able to find the answer to this as it had been raised as an issue at github, so I am posting that solution here.

https://github.com/joomla/joomla-cms/issues/7028

It is necessary to register the application like this, if the command line app uses JTable:

class MakeSql extends JApplicationCli
{

   public function __construct() 
  {
     parent::__construct();
     JFactory::$application = $this; // this is necessary if using JTable
  }

  public function doExecute()
  {
      $db = JFactory::getDbo();
      // ... etc etc ...

I did this and it worked fine.

user1104799
  • 161
  • 3
  • 13