创建一个Joomla!文章以编程方式

问题描述 投票:2回答:3

我创建了自己的组件。当我向组件添加新记录时,我还希望它在joomla中创建一篇新文章(即使用com_content)。

我在堆栈溢出Programmatically adding an article to Joomla上发现了这个,它解释了如何做到这一点。代码是有道理的,看起来它会起作用。问题是,一旦调用com_content中包含的方法,com_content中的所有相对URL都会崩溃,joomla会抛出错误。

有谁知道克服这种情况的方法吗?上面链接中的注释表明,在包含它之前将当前工作目录更改为com_content将会有效,但我不能100%确定如何执行此操作。

php joomla content-management-system joomla2.5
3个回答
14
投票

由于它是常量,因此无法更改工作目录。要解决此问题,您可以选择不使用ContentModelArticle,而只使用表类:

$table = JTable::getInstance('Content', 'JTable', array());

$data = array(
    'catid' => 1,
    'title' => 'SOME TITLE',
    'introtext' => 'SOME TEXT',
    'fulltext' => 'SOME TEXT',
    'state' => 1,
);

// Bind data
if (!$table->bind($data))
{
    $this->setError($table->getError());
    return false;
}

// Check the data.
if (!$table->check())
{
    $this->setError($table->getError());
    return false;
}

// Store the data.
if (!$table->store())
{
    $this->setError($table->getError());
    return false;
}

请注意,上面的代码不会触发之前/之后的保存事件。但是,如果需要,那么触发这些事件应该不是问题。另外值得注意的是,不会自动设置字段published_up,并且不会重新排序该类别中的文章。

要重新排序类别:

 $table->reorder('catid = '.(int) $table->catid.' AND state >= 0');

1
投票

我得到的错误说:

找不到档案/var/www/administrator/com_mynewcomponent/helpers/content.php

我通过在此位置创建一个空文件以解决错误消息并手动将/var/www/administrator/com_content/helpers/content.phprequire_once语句包含在一起来解决问题。


1
投票

Support Joomla 2.5 and Joomla 3.0

JTomContent在Joomla之前没有自动加载!版本3.0,所以它需要包括:

if (version_compare(JVERSION, '3.0', 'lt')) {
    JTable::addIncludePath(JPATH_PLATFORM . 'joomla/database/table');        
}   
$article = JTable::getInstance('content');
$article->title            = 'This is my super cool title!';
$article->alias            = JFilterOutput::stringURLSafe('This is my super cool title!');
$article->introtext        = '<p>This is my super cool article!</p>';
$article->catid            = 9;
$article->created          = JFactory::getDate()->toSQL();
$article->created_by_alias = 'Super User';
$article->state            = 1;
$article->access           = 1;
$article->metadata         = '{"page_title":"","author":"","robots":""}';
$article->language         = '*';

// Check to make sure our data is valid, raise notice if it's not.

if (!$article->check()) {
    JError::raiseNotice(500, $article->getError());

    return FALSE;
}

// Now store the article, raise notice if it doesn't get stored.

if (!$article->store(TRUE)) {
    JError::raiseNotice(500, $article->getError());

    return FALSE;
}
© www.soinside.com 2019 - 2024. All rights reserved.