Attempting to display values from Multiselect field using blueprint()

I’m trying to set up some basic categorisation and filtering for the blog on a client site. I have the YML all set up in the articles blueprint:

	label: Article Categories
	type: multiselect
	min: 1
		mresearch: Market Research
		busdev: Business Development Services
		corsoc: Corporate Social Responsibility
	default: mresearch

I have then used the blueprint() method to display the long text label based on the value stored e.g. “Market Research” when “mresearch” is in the article.txt file.

$catlist = $article->blueprint()->field('articlecategories');
$catvalue = $article->articlecategories()->value();
echo $catlist['options'][$catvalue] ?? $catvalue;

However, when multiple categories are selected for an article, I simply get the string of the comma-separated values, e.g. mresearch, busdev

I’m sorry if this is a simple fix, but I can’t workout where or how to start processing a string that contains multiple values and then displaying them correctly. It’s been a while since I’ve done much PHP or Kirby so I’m struggling a little.

Can someone please help?

Would the PHP Explode function help?

Set the separator as ', ’ (comma space) then you’ll get back an array of individual values.

I’m missing a bit of context where you are using this.

To get an array of all values stored in your articlecategories field, call split():

$catvalues = $article->articlecategories()->split(',');

Then you can loop through this array, and grab the long name from the blueprint.

1 Like

Hey @texnixe - that was what I needed. Sorry about the lack of context - I simply wanted to display the category for each post/article on the posts page. I’ll turn each one of those category labels into a link for filtering the blog by category, but this first step was hurting my brain a bit.

I’ve ended up with the following (which I will now add formatting and HTML to).

$catlist = $article->blueprint()->field('articlecategories');
$catvalues = $article->articlecategories()->split(',');
foreach ($catvalues as $catvalue) {
	echo $catlist['options'][$catvalue] ?? $catvalue;

This looks very similar to the split() method below, so thanks for suggesting it @ScreenRes - I’m sure it would also work.

That’s right, internally the split() field method uses Str::split() from the toolkit which in turn uses explode() internally, but also does some trimming. And it’s much more comfortable to call the field method on the field object, instead of

$values = explode(', ', $article->articlecategories()->value());

As @texnixe said it’s more or less the same thing but the Kirby split() method is neater.