Jump to content

Copy a repeater field to another page


MarkE
 Share

Recommended Posts

Maybe there is something for this already in the API, or elsewhere, but I couldn't find it, so here is my suggestion.

The problem is that you can't simply copy the repeater using the API in the usual way: $page2->repeater = $page1->repeater; appears to work for page 2 but messes up page1 where the repeaters get duplicated. Instead you have to copy over each of the field values within each repeater item.

So  I wrote this. It seems to work, at least in my context. I placed it in init.php. (However, it would be better if the core handled this more intuitively ?)

/**
 * Copies a repeater field to another page
 * Operates on the RepeaterPageArray object e.g. $page->repeater->copyTo($page2)
 *
 * @param HookEvent $event
 *
 */
wire()->addHook('RepeaterPageArray::copyTo', function ($event) {
	$repeater = $event->object;
	$repeaterField = $repeater->getForField();
	$page = $event->arguments(0);
	if(!$page->hasField($repeaterField)) {
		$event->error("Field $repeaterField does not exist on page");
		return;
	}
	$page->of(false);
	foreach ($repeater as $item) {
		$newItem = $page->$repeaterField->getNew();
		foreach($item->getFields() as $f) {
			$newItem->$f = $item->$f;
		}
		$newItem->save();
		$page->$repeaterField->add($newItem);
	}
	$page->save();
});

 

  • Like 2
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...