Giving each page an auto number

I need to give each page a unique number, going up in increments of 1.

I am really not sure how to do this. I guess I need to create a global field and then increment this field on the page save hook. At the same time I will save this value to a field on the page itself? Is there a better approach?

not sure if you can set your own identification though…

other than that you could just have a plugin function which reads out the field, sort by biggest value, increments and saves if the field is empty…

both approaches are with saving inside a field…

i previously had something like

  • parent page with number field
  • child page with number field

hook => read parent page current number => write current number +1 to child => update parent to this number

currently i am going a different approach… i have a model to turn my sqlite data into children pages, while there i can set ID’s, to be unique and auto increment or count rows as desired… this also does not use a parent page saving the number, as sqlite is faster than alot of pages and we could run Db::max any time and increment it by one…

Yes, this is what I was thinking of doing - any chance you can dig the code out? :slight_smile:

What is your use case?

I am creating invoices with kirby - every time I create a new one I want an auto incrementing reference assigned to the page this:

INV-1001
INV-1002
INV-1003

etc…

In this case a hook makes the most sense, I think.

Ok, that was easy - I :hearts: Kirby

'hooks' => [
        'page.create:after' => function ($page) {

          $newid = site()->invstart()->int() + 1;
          $page->update([
                  'ref' => $newid
          ]);

          site()->update([
            'invstart' => $newid
          ]);

        }
    ]

There is a very nice method for you: increment()

For site

For page

2 Likes