[英]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.php
和require_once
語句來解決這個問題。
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.