Generate automatic directories inside the content folder

Hi Community and Support Team :v:!

I have a current code, which did the creation of child pages through the front-page for the user.

I am taking the following references and everything works correctly.

:link: Reference – Creating pages from frontend

Now my client asks me for a new requirement which is to order the folders created by year and month within the directory.

I show the controller that I currently have which is responsible for creating the child pages.


Controller:

<?php

return function ($kirby, $page) {
	$month = date('m', time());
	$year = date('Y', time());

	// Submit
	if ($kirby->request()->is('POST') && get('register')) {
		try{
			// we store registrations as subpages of the current page
			$registration = $page->createChild([
				'slug'     => md5(str::slug($data['name'] . microtime())),
				'template' => 'quote',
				'content'  => $data
			]);

			if ($registration) {
				// store referer and name in session
				$kirby->session()->set([
					'referer' => $page->uri(),
					'regName'  => esc($data['name'])
				]);

				go('success');
			}
		} catch(Exception $e) {
			echo 'Your registration failed: ' . $e->getMessage();
		}
	}
};

The route that it currently generates for each child page is the following:


:file_folder: content/quotes/name-quote


What I need is for me to save the quotes automatically as follows:


:file_folder: content/quotes/year/month/name-quote


Note: Quotes must be stored in the corresponding year and month folder, without repeating the folder or overwriting any content.

Does anyone know if there is any function within Kirby to generate directories and validate if said directory already exists by year and month?

I await your response and help please.

Thank you very much.

Regards!

Yes, Kirby has low level folder methods, ie. the DIR class.

But if you use $page->createChild(), Kirby will throw an error if a page already exists, and you can check with for example page(‘2022’) or page(‘2022/12’) if a page already exists, and if not, create those pages.

1 Like

Hi @texnixe!

OK perfect.

Thank you very much for the answer and help.

I review what you share with me and I will notify you of anything or doubt.

Thanks!