Hi,
I want to create a country select field in the backend and populate it with entries from my database.
After hours of trial and error I made it work, but I’d like to document it here and ask a few questions.
Setup:
I went through the select field docs and tried to query a method from my corresponding page model in site/models/partner.php
<?php
class PartnerPage extends Kirby\Cms\Page
{
public function getCountryList()
{
$result = Db::table('phpwcms_country')->select('*');
return $result->all();
}
}
This worked, but in case I need the method somewhere else I decided to create a plugin as recommended.
Kirby::plugin(
'mo/country-list',
[
'pageMethods' => [
'getCountryList' => function () {
$result = Db::table('phpwcms_country')->select('*');
return $result->all();
},
],
]
);
- Is that the right approach?
- Is there a database request every time a page loads or only when the method is finally called in the panels (or in a controller)?
Then the configuration of the field in the panel (partner.yml) looks like this:
title: Partner
options:
changeTitle: false
changeStatus: true
changeSlug: false
columns:
- width: 1/3
fields:
mod_partner_country_de:
label: Country
type: select
options: query
# fetch the getCountryList method in mo/country-list plugin
query:
fetch: page.getCountryList
# these are `arrayItem`
# https://getkirby.com/docs/reference/panel/fields/select#options-from-other-fields
value: "{{arrayItem.country_iso}}"
text: "{{arrayItem.country_name_de}}"
What I found hard in the process of coming to this solution was mainly my inability to debug, what came back from the fetch: page.getCountryList
. I finally tried arrayItem
which, in hindsight makes sense, but on my way to that, I tried to convert the result set to an array, which was harder then I thought it would be.
I know I still miss a lot of knowledge of Kirby’s internals, but how do others debug panels and the ajax response? At the end I dumped $page->getCountryList()
in a controller to inspect the output in the frontend just to see what comes back.
I might go ahead and try to get https://github.com/itsgoingd/clockwork running, which I can highly recommend - it will output var dumps into a Chrome/Firefox panel and keeps the ajax requests intact.