Creating pages dynamically from plugin

Hi there,

I’m trying to develop a plugin, that basically fetches data from an API and saves this data as pages within a configurable folder. So far I’m doing the most of that in plain php and I’m just wondering if there is a better way using the giving Grav API. So I thought I just can create a “$page = new Page();”, adding content and header data, and just save it via “$page->save()”. But it seems, that I do not get that right. So, this is what I am doing so far:

// First check if folder an pages exist
$pagesPath = $locator->findResource('user://pages', true);
$dynPath = $this->config->get("plugins.voffice.dynPath"); // e.g. /dynpages
$dynFolder = $page->find($dynPath);
$existing = $page->evaluate(['@page.children'=>$dynPath]);

if (!$dynFolder) {
    Folder::create($pagesPath . $dynPath);
}

foreach($existing as $e) {
    Folder::delete($e->path());
}


$dynContent = getFromApi();

foreach($dynContent as $c) {
    $page = new Page();
    $page->title($c['name']);
    $page->path($pagesPath . $dynPath . "/" . $c['pathname'] . "/" . "template.md");
    $page->setContent($c['content']);
    $page->header($c['props']);
    $page->save(); // Does not write the file/folder
    // manually do file operations
    Folder::create(dirname($page->path()));
    file_put_contents($page->path(), $page->raw());
}

Is this the right way to go or is there a “better” way for my approach?
And, btw. all my created md fies are empty so far, so the file is created, but the content is is not set…

Welcome @page6.

The Add Page By Form Plugin creates a page using data from a Grav form.

You could either have a look how saving works or adapt the plugin to your needs.

If you run into problems I would be glad to help but I can’t explain how Grav works, I just managed to get a working plugin :woozy_face:

2 Likes

Thank a lot, @bleutzinn!
I could figure it out by following your plugin. And the file is written by $page->save() after I’ve set the following properties:

$page = new Page();
$page->name(...);
$page->title(...);
$page->folder(...);
$page->extension(...);
$page->parent($parentPage); // Needs to be a Page Object, or at least implement the PageInterface  
$page->filePath(...);
$page->routable(...);
$page->header(...);
$page->frontmatter(...);
$page->rawMarkdown(Yaml::dump((array)$page->header(), 20));
$page->file()->markdown($page->rawMarkdown());
$this->grav['pages']->addPage($page);
$page->save();

@page6 I’m glad I could be of help. Can you please mark this topic as ‘Solved’? That makes it easier for forum users to spot solved problems. Thanks.

Sure!
Sorry, I thought I had marked it already… my bad!