Jump to content

[SOLVED] How to convert this to a Hook?


PWaddict
 Share

Recommended Posts

I would like to auto remove repeater items if a text field inside repeater item is empty.

The below code placed inside the template removes the specific repeater items when someone visits the page. How can make it work in a Hook when the editor saves the page on backend?

$admin_page_name = $pages->get(2)->name;
$repeater_id = $fields->get('my_repeater_field')->id;

$empty_items = $pages->find("template=repeater_my_repeater_field, my_text_field='', parent=/{$admin_page_name}/repeaters/for-field-{$repeater_id}/for-page-{$page->id}/, include=all");

foreach($empty_items as $empty_item) {
	$page->of(false);
	$page->my_repeater_field->remove($empty_item);
	$page->save();
}

 

Link to comment
Share on other sites

I have done something similar before using:

$pages->addHookAfter('saved', function($event) {
	$page = $event->arguments[0];
	// if page template = specific template, then execute desired code
	if($page->template->name == 'mytemplatename') {
		# do something here
	}
}

I just put it in the ready.php file under the "site" folder.

  • Like 1
Link to comment
Share on other sites

Here is how I did it:

$wire->addHookAfter("Pages::save", function(HookEvent $event) {

  $page = $event->arguments[0];
  if($page->template->name != 'my-template') return;

  $admin_page_name = wire("pages")->get(2)->name;
  $repeater_id = wire("fields")->get('my_repeater_field')->id;

  $empty_items = $pages->find("template=repeater_my_repeater_field, my_text_field='', parent=/{$admin_page_name}/repeaters/for-field-{$repeater_id}/for-page-{$page->id}/, include=all");

  if(count($empty_items)) {

    foreach($empty_items as $empty_item) {
    $page->of(false);
    $page->my_repeater_field->remove($empty_item);
    $page->save();
  }
}

 

  • Like 3
Link to comment
Share on other sites

  • PWaddict changed the title to [SOLVED] How to convert this to a Hook?

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...