Jump to content

Add Repeater Matrix Fields to Search Selector


Recommended Posts

Hello everyone!

I am trying to add my repeater matrix fields to the search selector, but unfortunately nothing seems to work for me.

I have following search code in my search.php:

<?php namespace ProcessWire;

// look for a GET variable named 'q' and sanitize it
$q = input()->get('q');

// sanitize to text, which removes markup, newlines, too long, etc.
$q = sanitizer()->text($q);

// did $q have anything in it after sanitizing to text?
if($q) {

	// Make the search query appear in the top-right search box.
	// Always entity encode any user input that also gets output
	echo '<input id="search-query" value="' . sanitizer()->entities($q) . '">';

	// Sanitize for placement within a selector string. This is important for any 
	// values that you plan to bundle in a selector string like we are doing here.
	// It quotes them when necessary, and removes characters that might cause issues.
	$q = sanitizer()->selectorValue($q);

	// Search the title and body fields for our query text.
	// Limit the results to 50 pages. The has_parent!=2 excludes irrelevant admin
	// pages from the search, for when an admin user performs a search. 
	$selector = "title|body~=$q, limit=50, has_parent!=2";

	// Find pages that match the selector
	$matches = pages()->find($selector);
	
} else {
	$matches = array();
}

// unset the variable that we no longer need, since it can contain user input
unset($q);

?>
<main pw-replace='main'>
	<?php include('./includes/_pageheadersearch.php'); ?>

	<div id='content-body' class='uk-section uk-section-large uk-section-large'>
		<div class='uk-container uk-container-small'>
			<?php
			// did we find any matches?
			if(count($matches)) {
				// yes we did, render them
				echo ukAlert(sprintf(_n('Found %d page', 'Found %d pages', $matches->count), $matches->count), "default", "check");
				echo ukDescriptionListPages($matches);
			} else {
				// we didn't find any
				echo ukAlert(__('Sorry, no results were found'), "danger", "warning");
			}
			?>
		</div>
	</div>
</main>

I have tried to add my fields to the selector code (repeater_matrix.aboutsblock_repeaters.mytextfield) . But I didn't get any results.

What I am doing wrong?

Thanks for your help!

Link to post
Share on other sites

You could check if one of the newer fieldtype selectors work for you:

https://processwire.com/blog/posts/processwire-3.0.91-core-updates/

I just quickly did a test: It seems if you omit the matrix-fieldname, it works, e.g.

If I have a matrix field called matrix, and inside it is a body field with a matrix-name "richtext":

matrix.richtext.body%=keyword // doesn't work

matrix.body%=keyword // works

$res = $pages->find("matrix.body%=fräsen");
if($res->count) {
    echo '<ul>';
    foreach($res as $match) {
        echo "<li><a href='{$match->url}'>{$match->title}</a></li>";
    }
echo '</ul>';
} else {
    echo "<p>No results found.</p>";
}

 

matrix-gotcha.PNG

  • Like 1
Link to post
Share on other sites

Thank you for your answer.

It seems like the problem is, that the field is in a repeater matrix and then in a repeater.

The hierarchy is:

- repeater_matrix
  -- aboutusblock_repeater
  ---- textfield

Could that be?

Link to post
Share on other sites

I'm going to jump on this train as well. I've got a matrix with repeater inside and then a body field, just like MateThemes example above.

This works

title|headline|lead|body%=$q

Also this works

matrix.repeater_field.body%=$q

But if I combine both like so, it wont return anything

$selector .= ", title|headline|lead|body%=$q";
$selector .= ", matrix.repeater_field.body%=$q;

If I try to enclose each line in parenthesis it returns every single page on the website, even if the search word is something that doesn't exist on the site

$selector .= ", (title|headline|lead|body%=$q)";
$selector .= ", (matrix.repeaters.body%=$q)";

So I'm kinda almost there, but not quite.

Link to post
Share on other sites

Hmm yes, I just tried it out myself and saw this msg: Exception: Multi-dot 'a.b.c' type selectors may not be used with OR '|' fields on line: 896 in /wire/core/PageFinder.php 😞

Guess you'd have to do two separate queries then, one for regular fields, and one for Matrix fields (?). I guess you could file an issue @ Github, if it isn't mentioned already.

edit: Just found this related thread: 

 

Edited by dragan
added link
Link to post
Share on other sites
On 4/25/2019 at 9:14 PM, Hurme said:

If I try to enclose each line in parenthesis it returns every single page on the website, even if the search word is something that doesn't exist on the site

Maybe you made a typo somewhere in your selector - the OR-group syntax is working for me:

2019-04-29_232222.png.022de0e098bd5488d3cece209e98b84e.png

 

Link to post
Share on other sites
9 hours ago, Hurme said:

What happens if you have multiple pages, where some of the pages have the matrix and some don't? Does it still work for you?

There are multiple pages existing in the example above, so yes it does work.

I saw your post in the other thread - the problem is that you are using a single unnamed OR-group for all your selectors. Only one parenthesised selector in the OR-group has to match. So when you do...

$selector = "(template=home|basic-page|product-category, status!=hidden), (template=news-item|product-page)";

...this means that any unhidden page with the home, basic-page or product-category template and any page with the news-item or product-page template will match regardless of any other selectors you later add to the same OR-group. Have another look at the documentation for OR-groups and try giving names to the different OR-groups for template and field values.

  • Like 1
Link to post
Share on other sites
2 hours ago, Hurme said:

What does naming the groups actually achieve?

It tells PW that there is more than one OR-group in the selector string. It's all about specifying what has to match in order for the whole selector string to match - remember that for every OR-group only one selector in the group has to match.

So previously you were doing this...

// Templates
$selector = "(template=home|basic-page|product-category, status!=hidden), (template=news-item|product-page)";
// Fields
$selector .= ", (title|headline|lead|body%=$q), (content_matrix.columns.body%=$q, content_matrix.columns.count>0)";

...which we can represent as this...

// Templates
$selector = "(template selector 1), (template selector 2)";
// Fields
$selector .= ", (field selector 1), (field selector 2)";

...and it is the same thing as...

// Templates
$selector = "foo=(template selector 1), foo=(template selector 2)";
// Fields
$selector .= ", foo=(field selector 1), foo=(field selector 2)";

...which is saying "find any pages that match template selector 1 OR template selector 2 OR field selector 1 OR field selector 2". So this will match a lot of pages that you don't actually want to match.

Whereas this...

// Templates
$selector = "foo=(template selector 1), foo=(template selector 2)";
// Fields
$selector .= ", bar=(field selector 1), bar=(field selector 2)";

...is saying "find any pages that match (template selector 1 OR template selector 2) AND (field selector 1 OR field selector 2)".

  • Like 2
Link to post
Share on other sites

@Robin S It works fine now, thanks for your help. Ryan basically gave the same advice in another thread so it should be doubly fixed now. 😉
 
@MateThemes It works just fine.

You'll want to write it like this:

$pages->find("matrix_field.repeater_field.regular_field%=$searchquery, matrix_field.repeater_field.count>0");

Note that you'll want to leave out matrix type. The count part at the end is to make sure it only returns pages that actually have content in them (seems to be a bug and I haven't checked if it's been fixed yet or not).

Link to post
Share on other sites
  • 1 year later...

Sorry to bring this old thread up but felt it was better than posting a new one? Maybe not. Anyway... I'm having a similar issue when it comes to searching a textarea field in a repeaterMatrix.

$fieldsToSearch = 'name|title|text|textA|textarea|projectsCategories.title|projectsClients.title|aboutPressCategories.title|aboutPressClients.title';
$templatesToSearch = 'projectsSingle|shopSingle|typeSingle|typeCustomSingle|typeCustomSingleB|aboutPressSingle|repeater_modulesA';

$results = $pages->find("$fieldsToSearch%=$searchQuery, template=$templatesToSearch, sort=sort, check_access=0");

This is all working but it doesn't seem to include the repeaterMatrix field `modulesA` in the search as when I search for a word that is within the `repeater_modulesA` template within the field `textarea` it doesn't return the page. If it did I would then need to check the returned item's template and return the `getForPage()` to link to the page it's on.

Any thoughts on why it's not returning anything?

Link to post
Share on other sites

I've always included a "path" to the field when including fields inside a repeaters or matrix fields. I'm not actually sure if it's really needed or if I've just been too meticulous about it.

matrix_field.regular_field|matrix_field.repeater_field.regular_field

Perhaps repeaters and matrix fields having their own template has something to do with it.

Link to post
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
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By donatas
      Hello,
      how would I do a multi-language website search with just a selector?
      I have many multi-lang fields and I want to do a search through all of them at once and through all of their language values.
      Is there a "selector way" of doing this? Maybe something like `title|title:de|title:it`? It seems I have seen this somewhere a long time ago but can't find in any documentation or forum search...
      Or the only way of doing it is by running separate searches for each language with output formatting off and then consolidating it all in one single results array?
      Because I still want to give users a result, even if it is in another language than current $user. Visitors mostly will be searching for specific terms that are very similar in all languages, but might be not used in one language version of a single page, for example. Or the user might not have switched language tohis prefered and did the search first, etc.. (many use cases in my situation)
      Example:
      $pages->find('title~='.$q) - maybe different operator is needed? /en/search/?q=visit = 1 results /it/search/?q=visit = 0 results Thanks for any advice!
    • By humanafterall
      Hi,
      I would like to set an admin template to 'https only' as recommended in the Processwire security docs.
      However if I do this it forces this setting locally too, resulting in https://localhost requests which result in an error page.
      Is there a simple way round this? Setting https for templates in the config?
      Thanks!
    • By sebr
      Hi
      In my search page, I used a selector like this :
      $searchQuery = $sanitizer->entities($input->get('q')); $searchQuery = $sanitizer->selectorValue($searchQuery); $selector = 'title|subtitle|summary|html_body_noimg~=' . $searchQuery; $matches = $pages->find($selector); I don't have the same results if $searchQuery contains accent or not.
      For example,
      with « bâtiment » I have no result with « batiment » I have onea result : « Les bâtiments et les smart-city » Normally I should have the same results? How can I do that ?
      Thanks for your help
    • By Chris Bennett
      Hi all, I am going round and round in circles and would greatly appreciate if anyone can point me in the right direction.
      I am sure I am doing something dumb, or missing something I should know, but don't. Story of my life 😉

      Playing round with a module and my basic problem is I want to upload an image and also use InputfieldMarkup and other Inputfields.
      Going back and forth between trying an api generated page defining Fieldgroup, Template, Fields, Page and the InputfieldWrapper method.

      InputfieldWrapper method works great for all the markup stuff, but I just can't wrap my head around what I need to do to save the image to the database.
      Can generate a Field for it (thanks to the api investigations) but not sure what I need to do to link the Inputfield to that. Tried a lot of stuff from various threads, of varying dates without luck.
      Undoubtedly not helped by me not knowing enough.

      Defining Fieldgroup etc through the api seems nice and clean and works great for the images but I can't wrap my head around how/if I can add/append/hook the InputfieldWrapper/InputfieldMarkup stuff I'd like to include on that template as well. Not even sure if it should be where it is on ___install with the Fieldtype stuff or later on . Not getting Tracy errors, just nothing seems to happen.
      If anyone has any ideas or can point me in the right direction, that would be great because at the moment I am stumbling round in the dark.
       
      public function ___install() { parent::___install(); $page = $this->pages->get('name='.self::PAGE_NAME); if (!$page->id) { // Create fieldgroup, template, fields and page // Create new fieldgroup $fmFieldgroup = new Fieldgroup(); $fmFieldgroup->name = MODULE_NAME.'-fieldgroup'; $fmFieldgroup->add($this->fields->get('title')); // needed title field $fmFieldgroup->save(); // Create new template using the fieldgroup $fmTemplate = new Template(); $fmTemplate->name = MODULE_NAME; $fmTemplate->fieldgroup = $fmFieldgroup; $fmTemplate->noSettings = 1; $fmTemplate->noChildren = 1; $fmTemplate->allowNewPages = 0; $fmTemplate->tabContent = MODULE_NAME; $fmTemplate->noChangeTemplate = 1; $fmTemplate->setIcon(ICON); $fmTemplate->save(); // Favicon source $fmField = new Field(); $fmField->type = $this->modules->get("FieldtypeImage"); $fmField->name = 'fmFavicon'; $fmField->label = 'Favicon'; $fmField->focusMode = 'off'; $fmField->gridMode = 'grid'; $fmField->extensions = 'svg png'; $fmField->columnWidth = 50; $fmField->collapsed = Inputfield::collapsedNever; $fmField->setIcon(ICON); $fmField->addTag(MODULE_NAME); $fmField->save(); $fmFieldgroup->add($fmField); // Favicon Silhouette source $fmField = new Field(); $fmField->type = $this->modules->get("FieldtypeImage"); $fmField->name = 'fmFaviconSilhouette'; $fmField->label = 'SVG Silhouette'; $fmField->notes = 'When creating a silhouette/mask svg version for Safari Pinned Tabs and Windows Tiles, we recommend setting your viewbox for 0 0 16 16, as this is what Apple requires. In many cases, the easiest way to do this in something like illustrator is a sacrificial rectangle with no fill, and no stroke at 16 x 16. This forces the desired viewbox and can then be discarded easily using something as simple as notepad. Easy is good, especially when you get the result you want without a lot of hassle.'; $fmField->focusMode = 'off'; $fmField->extensions = 'svg'; $fmField->columnWidth = 50; $fmField->collapsed = Inputfield::collapsedNever; $fmField->setIcon(ICON); $fmField->addTag(MODULE_NAME); $fmField->save(); $fmFieldgroup->add($fmField); // Create: Open Settings Tab $tabOpener = new Field(); $tabOpener->type = new FieldtypeFieldsetTabOpen(); $tabOpener->name = 'fmTab1'; $tabOpener->label = "Favicon Settings"; $tabOpener->collapsed = Inputfield::collapsedNever; $tabOpener->addTag(MODULE_NAME); $tabOpener->save(); // Create: Close Settings Tab $tabCloser = new Field(); $tabCloser->type = new FieldtypeFieldsetClose; $tabCloser->name = 'fmTab1' . FieldtypeFieldsetTabOpen::fieldsetCloseIdentifier; $tabCloser->label = "Close open tab"; $tabCloser->addTag(MODULE_NAME); $tabCloser->save(); // Create: Opens wrapper for Favicon Folder Name $filesOpener = new Field(); $filesOpener->type = new FieldtypeFieldsetOpen(); $filesOpener->name = 'fmOpenFolderName'; $filesOpener->label = 'Wrap Folder Name'; $filesOpener->class = 'inline'; $filesOpener->collapsed = Inputfield::collapsedNever; $filesOpener->addTag(MODULE_NAME); $filesOpener->save(); // Create: Close wrapper for Favicon Folder Name $filesCloser = new Field(); $filesCloser->type = new FieldtypeFieldsetClose(); $filesCloser->name = 'fmOpenFolderName' . FieldtypeFieldsetOpen::fieldsetCloseIdentifier; $filesCloser->label = "Close open fieldset"; $filesCloser->addTag(MODULE_NAME); $filesCloser->save(); // Create Favicon Folder Name $fmField = new Field(); $fmField->type = $this->modules->get("FieldtypeText"); $fmField->name = 'folderName'; $fmField->label = 'Favicon Folder:'; $fmField->description = $this->config->urls->files; $fmField->placeholder = 'Destination Folder for your generated favicons, webmanifest and browserconfig'; $fmField->columnWidth = 100; $fmField->collapsed = Inputfield::collapsedNever; $fmField->setIcon('folder'); $fmField->addTag(MODULE_NAME); $fmField->save(); $fmFieldgroup->add($tabOpener); $fmFieldgroup->add($filesOpener); $fmFieldgroup->add($fmField); $fmFieldgroup->add($filesCloser); $fmFieldgroup->add($tabCloser); $fmFieldgroup->save(); /////////////////////////////////////////////////////////////// // Experimental Markup Tests $wrapperFaviconMagic = new InputfieldWrapper(); $wrapperFaviconMagic->attr('id','faviconMagicWrapper'); $wrapperFaviconMagic->attr('title',$this->_('Favicon Magic')); // field show info what $field = $this->modules->get('InputfieldMarkup'); $field->name = 'use'; $field->label = __('How do I use it?'); $field->collapsed = Inputfield::collapsedNever; $field->icon('info'); $field->attr('value', 'Does this even begin to vaguely work?'); $field->columnWidth = 50; $wrapperFaviconMagic->add($field); $fmTemplate->fields->add($wrapperFaviconMagic); $fmTemplate->fields->save(); ///////////////////////////////////////////////////////////// // Create page $page = $this->wire( new Page() ); $page->template = MODULE_NAME; $page->parent = $this->wire('pages')->get('/'); $page->addStatus(Page::statusHidden); $page->title = 'Favicons'; $page->name = self::PAGE_NAME; $page->process = $this; $page->save(); } }  
    • By michelangelo
      Hello guys, I am building a sort of an archive. Relatively simple, although I have about 8000 records, each with 15 fields (text, int, images, url). I created a crude search system with a form (emulating the famous Skyscrapper example) to filter through the system. Everything works but it is quite slow... I have 2 questions which are related:

      1. How can I search through the database?
      2. What is a good practice to display many records like these?
      -----------------------------------------
      1. I am retrieving the results with
      $songs = $pages->findMany('template=nk-song'); Then I do a foreach to render them all. I am unsure if that is a good way. If I render all of them on the page, it creates thousands of divs with a bit of text, and this can take a while (10s-15s).
       
      2. This one is even worse :D as every time I retrieve my desired records with something like this:
      $page->find("field_to_search_through~=my_query_string") I get between 20 and 200, but when I render them I am creating iframes with YouTube videos and that can take up to 10s to finish. I "solved" it by only loading the iframes if they are in view with IntersectionObserver on the client-side. But I feel there is a more precise PHP / ProcessWire approach.
       
      Just to clarify, I started doing all of this custom rendering and querying because tools like ElasticSearch or SearchEngine were a bit complicated and I needed a simple to retrieve information and then display it in my own way.
      Thank you!
×
×
  • Create New...