繁体   English   中英

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

[英]Create a Joomla! Article Programmatically

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

我在堆栈溢出中找到了这个以编程方式向 Joomla 添加一篇文章,其中解释了如何做到这一点。 代码是有道理的,看起来它会起作用。 问题是,一旦开始调用包含在 com_content 中的方法,com_content 中的所有相对 URL 都会崩溃,joomla 会抛出错误。

有谁知道克服这个问题的方法? 来自上面链接的评论表明,在包含之前将当前工作目录更改为 com_content 会起作用,但我不是 100% 确定如何执行此操作。

无法更改工作目录,因为它是一个常量。 要解决此问题,您可以选择根本不使用 ContentModelArticle 而是仅使用 table 类:

$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');

我得到的错误说:

文件未找到 /var/www/administrator/com_mynewcomponent/helpers/content.php

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

支持 Joomla 2.5 和 Joomla 3.0

JTableContent 不会在 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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM