In a plugin, in Kirby 3, how can I set an option to a default value when none has been defined in config.php? That option is re-used several times inside the plugin, so using the alternate syntax of option("someOption", "default value"); is not DRY. I prefer to do this once in the plugin’s index.php.
In Kirby 2, you could do the following:
if (c::get("someOption") == "") {
c::set("someOption", "default value");
}
How can I access that default value, that has been set in plugin options, early in the bootstrap phase (before the route is being evaluated)? Are plugin options already loaded then?
I’ld need it in a helper function for the route pattern.
Below is a simplified use case of a plugin I try to build. The RouterPatternHelper::getOverviewPattern() function returns an array of patterns which match the localized slugs of a given “overview page”, who’s id (in the default language) is set in the plugin’s overviewPageId-option. But it contains an opinionated default value (“overview”) in the plugin that should be able to be overriden in the config.php (but it should also be possible to not set it in the config.php, and rely on the default page id, as set in the plugin’s options).
The “problem” I try to solve is that I find it error-prone to always have to manually build pattern-arrays which match a certain page in a multilingual setup (e.g.: “/en/overview/xxx”, “/nl/overzicht/xxx”, “/de/ubersicht/xxx”, …), especially because slugs can be altered by website editors and I want to still have a positive match for that page afterwards in my route.
This is my attempt to get this working; and where I’m stuck:
// site/plugins/myPlugin/classes/RouterPatternHelper.php
namespace bvdputte\myPlugin;
use Kirby\Cms\App;
class RouterPatternHelper {
/**
* Prepare the router pattern to match the overview page
*
* @return object
*/
public static function getOverviewPattern()
{
$kirby = App::instance();
$overviewPage = $kirby->find(option("bvdputte.myPlugin.overviewPageId")); // <- I need this to work
$overviewPattern = [];
foreach($overviewPage->translations() as $lang) {
$pattern = "(:any)/" . $home->slug($lang->code()) . "/(:any)";
array_push($overviewPattern, $pattern);
}
return $overviewPattern;
}
}
This has no effect, and still works only if the option is set in config.php too. When I remove it there (it’s still in the plugin’s index.php, so the fallback should work), I get an error because it resolves as null…
So… my setup kinda works, but I only have to find a way to keep it working when no option is set in config.php, so it falls back to the option defined in the plugin.
it returns the option value alright (I just returned the option value from the function for testing), or if I call `dump(bvdputte\myPlugin\RouterPatternHelper::getOverviewPattern()) in a template. But somehow it doesn’t like it in the pattern.