Encode a tags field into JSON to fetch in a select field

Hello,

The idea is to let the user generate his/her own categories trough a tags field on a configuration page and to output that string as JSON.

This is what I’m doing:

<?php
header('Content-type: application/json; charset=utf-8');

$data = $page->categories();
$json = array();

foreach($data->split(',') as $category) {
	$json[] = $category.":".$category;
}

echo json_encode($json);
?>

And, in a blueprint I have this:

category:
    label: Product Type
    type: checkboxes
    options: kirby-url/categories

Is this the correct way of doing this?

I’d do this:

<?php
header('Content-type: application/json; charset=utf-8');

$data = $page->categories();
$json = array();

foreach($data->split(',') as $category) {
	$json[$category] = $category;
}

echo json_encode($json);

?>

An alternative would be to create a custom categories select field that fetches the data from the configuration page.

Thanks for the input. The array is being encoded nicely now but the field still won’t recognize the link.

Can I fetch a tags variable and split it through the query options in the field? If not, then I guess I’ll have to change the logic of the categories and use subpages instead of the tags field to populate the categories, huh?

What sort of url is that, you need to pass an absolute URL like so:

http://yourdomain.com/xyz or 
http://localhost/kirby

You cannot use a relative link.

No, you can’t. But as I said above, you can create a custom select field that fetches the options from the tags field and passes them as options.

Edit: See this post for an example: Fetch query from parent page

1 Like

Yes, it’s an absolute URL. I changed that to clean things up a bit. Something along this line:

http://localhost/store/categories

Oh, ok, I get it now. Creating a custom field would require a bit of work, it’s something I’ve never done before.

Thanks! That’s great to start. I’ll mark this as solved. :smile:

Dynamic options with an url work perfectly fine, however.

I briefly tested this:

  1. created a folder /categories with a categories.txt file in it
  2. created a template with the json encode stuff inside
  3. create a blueprint with the category field:
category:
    label: Product Type
    type: checkboxes
    options: http://localhost/k223/categories

Works.

Hmmm… yes, in theory it should work, but it does not. I don’t know what could be causing that.

What happens if you call the URL directly in the browser?

It echoes the JSON object.

But guess what? The problem only occurs locally. I just uploaded the project to a test server to post some links and it’s now working!

Thanks Sonja. :slightly_smiling: