Panel: Sort tags on save

Hi,

is it possible to save tags in the panel alphabetically on save? E.g. convert

----

Tags: One Tag,Another Tag,My Tag,No Tag

----

to

----

Tags: Another Tag,My Tag,No Tag,One Tag

----

automatically on save.

Bye,
Tobi

Sounds like a perfect use case for panels hooks in combination with the page update method.

I haven’t use the hook system so far, so this is just kind of a guess!? :wink:

Yes, a post update hook is the best way, sth like

<?php
<?php
kirby()->hook('panel.page.update', function($page) {
  	if(isset($page->content()->data['tags'])) {
	  $tags = $page->tags()->split();
	  sort($tags);
	  $tags = implode(",",$tags);
	  try {
		  $page->update(array(
		    'tags'    => $tags,
		    ));
		} catch(Exception $e) {
	  		echo $e->getMessage();
		}
	}	
	});

Thanks! That works great :smile:

I replaced sort with natcasesort because the latter is caseinsensitive.

As far as I can see this won’t cause an error for pages that don’t have a tags field, does it?

I haven’t tested that but you could put the code within the hook function within an if condition, just to make sure.

Edit: With the code above, if the field does not exist, it will be created (so, every page you save, will get a tags field) and if there are no tags, the field will be empty. Maybe you should just limit the behavior to templates that have a tags field.

How can I test if a page has a field? Is if($page->tags()) the right way?

I edited the code above but maybe what you suggested is enough. The above code checks if the key exists.

Edit: No,if($page->tags()) does not work …

Thanks again! It works fine … unfortunately there seems no Hook for the site options so I have to sort the site tags manually …

In my test environment this works for the site options as well, provided there is a tags field in your site blueprint

Uuups … may fault … the field was named keywords