Search code examples
phpjoomla

Updating an existing article in joomla


I have that code to store a new article in joomla:

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        = "some content";
$article->catid            = 9;
$article->created          = JFactory::getDate()->toSQL();;
$article->created_by_alias = 'my editor';
$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;
}

But I don't find how to update an existing one with its id. Where is it in the doc ? Do you have suggestions ?


Solution

  • You can use load function to first load that record and after assigning new values you can store into the table as shown in below code -

    $articleId = 6;// Change this to actual article id
    JTable::addIncludePath(JPATH_PLATFORM . 'joomla/database/table');
    $article = JTable::getInstance('content');
    $article->load($articleId);
    $article->title = $article->title . ' Updated';
    if (!$article->check() || !$article->store())
    {
        throw new RuntimeException($article->getError());
    }