Jump to content
MateThemes

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!

Share this post


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

Share this post


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?

Share this post


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.

Share this post


Link to post
Share on other sites

I guess this should do it:

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

 

  • Like 1

Share this post


Link to post
Share on other sites

Unfortunately that doesn't work. "Multidot" selectors can't be used with the | symbol.
 

Share this post


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

Share this post


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

 

Share this post


Link to post
Share on other sites

@Robin S 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?

Share this post


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

Share this post


Link to post
Share on other sites

Cheers @Robin S, this makes sense to me. I did read about the named groups while trying to solve this, but the explanation felt a little short for me. What does naming the groups actually achieve? 

Share this post


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

Share this post


Link to post
Share on other sites

Thank you very much for taking the time to explain it. This does makes things much more clear to me. I'll report back once I've had the time to test this.

Share this post


Link to post
Share on other sites

Hello everyone!

So as far as I understand the discussion, it is not possible to make a repeaterfield searchable in a repeater matrix. Is this right?

Thank you!

Share this post


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

Share this post


Link to post
Share on other sites

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?

Share this post


Link to post
Share on other sites

Anyone? Why wouldn't it search the `textarea` field within the repeaterMatrix?

Share this post


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.

Share this post


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 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!
    • By benbyf
      Hello, and welcome to what I though was either my client being silly and changing things, or some evil doer. Turns out its reproducible and therefore something in Proceswire (I checked my templates and modules but couldnt find anything that would be doing this...). So what is it doing? Check out the video for evidence.
      A repeater field is interacting with a page template and another repeater field somehow to swap the fields in the template and repeater over...
      I have a template called team, and a repeater field called team_repeater with label Team. Some how and for some reason, when I change my fields on repeater called main_menu_links my team template gets those fields and when I try and revert the team template fields to the fields it should have, they get given to the repeater main_menu_links. Also this to say HELP!!!!!
      video: https://www.dropbox.com/s/exkdhc6n7x0xpsa/strange-repeater-PW-mega-bug.mov?dl=0
    • By snobjorn
      I have a website with multiple content types that I want to be accessible through search. I really like the live search on processwire.com, that sorts content types while typing. I tried to find the code to recreate this, with no luck. Does anyone know if this is jquery, specific jquery plugins, json/xml cached files, and what kind of PHP code is used? Any tip that point me in the right direction would be much apperciated.
      The search result listing seems fairly easy to create with sorting through parameters.
    • By Aleksey Popov
      Hi! Is it possible to specify explicitly the parent section when creating a new child page with a single template?
      The idea is to save the user from the possibility of mistakenly choosing a section, but not to create unnecessary identical templates
      What I mean:
      Let's say I've got 2 parent categories with names articles & news. Each of them utilized the same admin-template (category) with the category.php file. Also, I have 2 different templates for child pages (article & news).
      Next, I need to add an article page to the articles category with the "create new" button in admin. At that moment, I must choose the category to place (because both categories use the same template). 
      To runaround this (and create a page right into the exact category without the choosing step) I should create 2 templates for each category, and setup parent-children relations for each pair of templates, right?
      But Is any way to use only the one category template and different children templates and at the same time, explicitly specify which section to use for child pages, thereby removing the process of selecting a child section?
       
      articles (category.php) Article page 1 (page-article.php) Article page 2 (page-article.php) Article page 3 (page-article.php) + Add a new article page here without category chooser news (category.php) News page 1 (page-news.php) News page 2 (page-news.php) News page 3 (page-news.php)  Update: found module  but I can't get it work.
       
×
×
  • Create New...