Add Joomla! custom fields to articles

317 Views Asked by At

For some time now Joomla! offers the possibility to add custom fields into articles.

Now I want to create new articles via the Joomla! Api, which is working fine using the following code (which is also used in the Joomla! documentation):

$article = JTable::getInstance( 'content' );

// create article entity object
$article->title             = $title;
$article->alias             = JFilterOutput::stringURLSafe( $title );
$article->fulltext          = $imagesHTML;
$article->images            = json_encode($image);
$article->catid             = $paramsArray['category_sun'];
$article->created           = JFactory::getDate()->toSQL();;
$article->created_by        = $paramsArray['user_author'];
$article->access            = 1;
$article->metadata          = '{"page_title":"","author":"","robots":""}';
$article->language          = '*';
$article->state             = 1;

// validate article
if (!$article->check()) {
    JError::raiseNotice( 500, $article->getError() );
    return false;
}
// store article into database
if (!$article->store(true)) {
    JError::raiseNotice( 500, $article->getError() );
    return false;
}

But now I want to add the custom field values also? How do I do that? Unfortunately the Joomla! documentation doesn't tell this (and is very outdated).

1

There are 1 best solutions below

0
On

I found a way doing this with Joomlas Dbo, which is doing a database query:

$field = new stdClass();
$field->field_id = 1;
$field->item_id = $article->id;
$field->value = "2018-11-06";

$result = JFactory::getDbo()->insertObject('#__fields_values', $field);

First you have to create a new field object and store it using the insertObject method. The database table which stores the custom field values is called [prefix]_fields_values.