Using a Tags-Field in page creation dialog for an automatic title

I use a tags-field in the page creation dialog like this:

create:
  fields:
    - categories

with

fields:
  categories:
    label: Kategorien
    type: tags

It works fine. But now I want to use the new automatic generated title, by using the first tag value. But I have no idea how to get it. I tried something like

create: 
  title: "{{ page.categories.split.first }} – {{ page.topic }}

or even with a custom page method, like:

Kirby::plugin('my/firstcategory', [
  'pageMethods' => [
    'firstcategory' => function() {
        return $this->categories()->split()->first();
    }
  ]
]);

Is it possible, that it doesn’t work with tags-fields?

Hi and welcome to our forum!

The problem here is that you are calling a collection method ( first()) on a simple array. This is not possible. Such methods can only ever be used with an object of the class they are member of, see A brief intro to object oriented programming in PHP | Kirby CMS

So what you need to return from your method is the index of the first element, which defaults to 0

return $this->categories()->split(',')[0];

And since we are in the context of the page object, use $this instead of $page

Thank you for the quick response. I already tried that. The problem seems to be, as soon as I try to access the category-field, the methods “returns” nothing. Other fields do work like a charm.

I think the problem is that you can only refer to fields, not to methods. Note that topic also needs to be in your list of fields, otherwise it won’t work, anyway.

For this use-case I’d therefore recommend a page model that overwrite the writeContent method

Yes, of cause. Something like:

return "prefix-".$this->topic();

works fine. But this

return "prefix-".$this->categories()->split(',')[0];

returns nothing, even not the „prefix-“part

I followed the instructions on Page blueprint | Kirby CMS and everthing works fine, except when I want to use a tags-field or something like a checklist-field.

Yes, as I mentioned above, you need to use a field that returns a simple string value, not an array, because value modifications do not work in these string templates.