Copying a page without media - fiels field keep content

Is there an easy way to set global fields to empty when copying a page without media?

I’m considering using the page.duplicate:after hook from the Kirby CMS documentation (page.duplicate:after | Kirby CMS). My idea is to check each field and remove its content if certain conditions are met.

My first idea:

<?php

return [
  'hooks' => [
    'page.duplicate:after' => function (Kirby\Cms\Page $duplicatePage, Kirby\Cms\Page $originalPage) {

      // Überprüfen ob Seite das Apartment Template hat
      if($duplicatePage->template() == 'product') {

        // check all fields
        foreach($duplicatePage->fields() as $field) {

          // if field is files 
          if(SOMETHING TO CHECK TYPE == 'files') {

            // remove content
            $duplicatePage->$field()->removeAll();

          }

        }

      }

    }
  ]
];

Best regards

$page->fields() is not a valid method (or rather, it returns a field object), correct would be $page->content()->fields(), but that would give you a list of fields with key/value pairs, not with field types.

If you want to know the type of field, then you have to go via the blueprint: Accessing blueprints | Kirby CMS

@texnixe You mean something like that?

<?php

return [
  'hooks' => [
    'page.duplicate:after' => function (Kirby\Cms\Page $duplicatePage, Kirby\Cms\Page $originalPage) {

      // Check for tempalte
      if($duplicatePage->template() == 'product') {

        //  Blueprint
        $blueprint = $duplicatePage->blueprint();

        // Check fields
        foreach($blueprint->fields() as $field) {

          // check typ
          if($field['type'] == 'files') {

            // remove if "files"
            $duplicatePage->{$field['name']}()->removeAll();

          }

        }

      }

    }
  ]
];

What does removeAll do? I think it would make more sense to update all files fields in the page in one go, instead of per field.

Sorry just an placeholder :slight_smile:
I thought I would first make my own small function for it.

But maybe i can get rid of the content by unset it? Or just pass an empty string?

unset($field);

And is there a good way to update all fields of type ‘files’ at once? I just want to remove the content, because for my customer it’s a bit annoying to copy it with the connection to the original images.

You need to set the field values to null. You need to pass an array with the fields to update to page update, where the key is the fieldname and the value null.

Ok. Something like that?

$blueprint = $duplicatePage->blueprint();

$fieldsToUpdate = [];

foreach ($blueprint->fields() as $fieldKey => $field) {
    if ($field['type'] == 'files') {
        $fieldsToUpdate[$fieldKey] = null;
    }
}


$duplicatePage->update($fieldsToUpdate);

Yep

1 Like

I will try - and mark it as solution after my test :slight_smile: