Jump to content

Searching through nested repeater items, is there a better way?


cst989
 Share

Recommended Posts

Hi there, recently found myself wanting to search through nested repeater items on a page, for reference they were FAQs, organised into FAQ groups, so:

faqs_group (parent repeater with group title)
   faqs (repeater item with title/body)
   faqs (repeater item with title/body)
   faqs (repeater item with title/body)
faqs_group 
   faqs
   faqs

Etc.

However, when I do a search of these FAQ items, I don't want them grouped anymore, just want to find the FAQ items and display them all.

Firstly I searched using the repeater_faqs template that Processwire generates, that works fine once you add check_access=0 since this template shouldn't normally be searched by regular users (found in another thread on here) - but then I need to narrow it down to just those FAQs on the current page so that the search doesn't find items related to totally different pages in the future.

The only way we could figure out to do this was to loop through all the FAQs on the page, grab their IDs, then limit our search result to these IDs. This is what I ended up with, but I feel like there must be a better way using the API that I missed?

$ids = [];
foreach ($page->faqs_groups as $group){
	foreach($group->faqs as $faq){
		$ids[] = $faq->id;
	}
}
$ids = implode('|',$ids);
$results = $pages->find("id=$ids, title|body*={$input->get->search}, template=repeater_faqs, check_access=0");

 

Link to comment
Share on other sites

10 hours ago, cst989 said:
title|body*={$input->get->search}

You'll want to sanitize search input before using it in a selector string. 🙂

And here's an alternative way you could search across the FAQ items:

$search = $sanitizer->selectorValue($input->get('search'));
$faqs = new PageArray();
foreach($page->faqs_groups as $group) {
	$faqs->add($group->faqs);
}
$results = $faqs->find("title|body*=$search");

 

  • Like 1
  • Thanks 1
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...