Jump to content

Need help with $pages->find


RobbieR
 Share

Recommended Posts

Hello

I run into issue with find function.

Is there a way to use find removing page title spaces?

Example: 

$page->title = "505 tt";

// looking for this page
$keyword = "505tt";
$p = $pages->find('template=project, title~=$keyword');

It return no page. Is there a way to find right page?  

At the moment i get all pages and then do loop. Removing title spaces and compare. I think its over kill.

Link to comment
Share on other sites

I don't think there's a straight-forward solution for this. Usually, advanced search requirements like this are covered by external search engines like Lucene, but those might a bit of overkill.

A lean solution would be to create a (hidden) text field, let's call it titlenospace, and add it to all templates you want to search.

Then, in site/ready.php (create the file if not there yet), hook into Pages::saveReady and populate the new field with the whitespace-stripped contents of the title field.

<?php

if($page->template == "admin") {
	wire()->addHookAfter("Pages::saveReady", function(HookEvent $event) {
		$page = $event->arguments(0);
		if($page->template->hasField("titlenospace")) {
			$page->titlenospace = str_replace(' ', '', $page->title);
		}
	});
}

For a multi-language site, the titlenospace field has to be created as TextLanguage and the code gets slightly more verbose.

<?php

if($page->template == "admin") {
	wire()->addHookAfter("Pages::saveReady", function(HookEvent $event) {
		$page = $event->arguments(0);
		if($page->template->hasField("titlenospace")) {
			$page->titlenospace = str_replace(' ', '', $page->title);
			if(wire("languages")) {
				foreach(wire("languages") as $lang) {
					if(!$lang->isDefault()) {
						$page->setLanguageValue($lang, "titlenospace", str_replace(' ', '', $page->getLanguageValue($lang, "title")));
					}
				}
			}
		}
	});
}

The titlenospace field needs to be populated for existing pages (simply saving them should do). Then you can use the field in your selector instead of or in addition to the regular title field.

  • Like 6
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...