I am trying to develop a hobby project based on https://www.themealdb.com/ api.
I am trying to create an article programmatically for https://www.themealdb.com/api/json/v1/1/search.php?s=Arrabiata and I was able to create an article with:
if (!defined('_JEXEC')) {
define('_JEXEC', 1);
define('JPATH_BASE', realpath(dirname(__FILE__)));
require_once JPATH_BASE . '/includes/defines.php';
require_once JPATH_BASE . '/includes/framework.php';
defined('DS') or define('DS', DIRECTORY_SEPARATOR);
}
$app = JFactory::getApplication('site');
$url = 'https://www.themealdb.com/api/json/v1/1/search.php?s=Arrabiata';
$response = json_decode(curlFnToGetResponseFromMealDB($url));
$meal = $response->meals;
$cat_mealdb_id = 233; // I have a function that gets the category
$tags= []; // I have a function that gets the tags
$args = [
'title' => $meal->strMeal . '-' . uniqid(),
'catid' => $cat_mealdb_id,
'introtext' => '', //nl2br($meal->strInstructions),
'fulltext' => '', //nl2br($meal->strInstructions),
'tags' => $tags
];
$article_id = prepareArticle($args);
function prepareArticle($args) {
$article = [
'id' => !empty($args['id']) ? $args['id'] : null,
'catid' => !empty($args['catid']) ? $args['catid'] : null,
'title' => !empty($args['title']) ? $args['title'] : null,
'alias' => !empty($args['alias']) ? $args['alias'] : null,
'introtext' => !empty($args['introtext']) ? $args['introtext'] : null,
'fulltext' => !empty($args['fulltext']) ? $args['fulltext'] : null,
'state' => 1,
'language' => '*',
'tags' => !empty($args['tags']) ? $args['tags'] : [],
];
$article_id = createArticle($article);
return $article_id;
}
function createArticle($data)
{
$data['rules'] = [
'core.edit.delete' => [],
'core.edit.edit' => [],
'core.edit.state' => [],
];
$basePath = JPATH_ADMINISTRATOR . '/components/com_content';
require_once $basePath . '/models/article.php';
$config = [];
$article_model = new ContentModelArticle($config);
if (!$article_model->save($data)) {
$err_msg = $article_model->getError();
return false;
} else {
$id = $article_model->getItem()->id;
return $id;
}
}
This is working well. I was able to create an article. Now I need to create custom fields based on the meal.
In this case:
Create a field with name
penne rigate
, if not exists. (penne rigate
is thestrIngredient1
)Add the value of
strMeasure1
(1
pound to that field)Map the field to this created article.
How to create an article field and map it to the article?
null
when an error doesn't throw an exception so that I can use nullable return types (since php 7.1). I commonly see code usingfalse
, but php doesn't have "falsible" types. Although since PHP8, there ismixed
which makes it okay. Some good reads: stackoverflow.com/q/37033142/2943403 , hashbangcode.com/article/best-practice-return-types-php , php.watch/versions/8.0/mixed-type