ProcessWire - Selectors: Unterschied zwischen den Versionen
Steff (Diskussion | Beiträge) |
|||
| (36 dazwischenliegende Versionen von 6 Benutzern werden nicht angezeigt) | |||
| Zeile 75: | Zeile 75: | ||
== Owner Attribut == | == Owner Attribut == | ||
| − | Nützlich bei Pagereferences, wenn auf die Seite verweisende Seiten gefunden und gleichzeitig gefiltert werden sollen. | + | Nützlich bei '''Pagereferences''', wenn '''auf die Seite verweisende Seiten''' gefunden und '''gleichzeitig gefiltert''' werden sollen. |
https://processwire.com/blog/posts/processwire-3.0.95-core-updates/ | https://processwire.com/blog/posts/processwire-3.0.95-core-updates/ | ||
<syntaxhighlight lang="php"> | <syntaxhighlight lang="php"> | ||
| Zeile 93: | Zeile 93: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
| + | |||
| + | == Kombinierte Abfragen und Subselektoren == | ||
| + | Da man auch Seiten im Selektor übergeben kann, kann man relativ einfach kombinierte Abfragen über '''mehrere Templates''', oder auch über '''parents''' etc. machen. Mit Subselektoren kann man das noch abkürzen. | ||
| + | |||
| + | '''Kombinierte Abfrage''' | ||
| + | <pre> | ||
| + | $companies = $pages->find("template=company, locations>5, locations.title%=Finland"); | ||
| + | $items = $pages->find("template=product, company=$companies"); | ||
| + | </pre> | ||
| + | '''Mit Subselektoren''' | ||
| + | $items = $pages->find("template=product, company=[locations>5, locations.title%=Finland]"); | ||
| + | |||
| + | == OR / AND == | ||
| + | OR funktioniert über | ||
| + | |||
| + | '''Feldwert a oder Feldwert b''' | ||
| + | firstname=Mike|Steve | ||
| + | |||
| + | '''Feldwert a und Feldwert b''' | ||
| + | height>500, height<=1000 | ||
| + | |||
| + | '''In Feld a oder in Feld b''' | ||
| + | body|sidebar*=carbonated | ||
| + | |||
| + | === OR Groups === | ||
| + | '''(Bedingung a, Bedingung b),(Bedingung c)''' | ||
| + | Wenn man Klammern nutzt muss nur eine der Klammern zutreffen. | ||
| + | |||
| + | Beispiel "product" Seiten in stock, UND entweder in featured date range, ODER highlighted checkbox checked. | ||
| + | |||
| + | <syntaxhighlight lang="php"> | ||
| + | $items = $pages->find("template=product, stock>0, (featured_from<=today, featured_to>=today), (highlighted=1)"); | ||
| + | </syntaxhighlight> | ||
| + | Die Klammern kennzeichnen Optionale Bedingungen. '''Es muss also nur eine der Klammern zutreffen.''' | ||
| + | |||
| + | Wenn man mehrere Oder-Gruppen benötigt kann man so vorgehen: | ||
| + | foo=(selector1), bar=(selector2), foo=(selector3), bar=(selector4) | ||
| + | Hier gehören alle foo zusammen und alle bar. Sprich es muss '''selector1 ODER selector3 UND selector2 ODER selector4''' erfüllt sein. | ||
| + | |||
| + | https://processwire.com/docs/selectors/#or-selectors1 | ||
| + | |||
| + | === Selektoren und RepeaterMatrix === | ||
| + | '''Beispiel TV Altötting''' | ||
| + | <syntaxhighlight lang="php"> | ||
| + | //BEISPIEL: $results = $pages->find("template=matrix_page,matrix_main.body%=$q"); // name des matrix items weglassen | ||
| + | //$selector = "template=".implode('|',$pageTemplates).", layout_blocks.body~*=".$val; // findet einspalter aber keine in | ||
| + | //$selector = "template=".implode('|',$pageTemplates).", layout_blocks.r_grid.body~*=".$val; // findet mehrspalter aber keine einspalter | ||
| + | // dot notation not allowed with or so we have to use or groups or bracket notation: | ||
| + | $selector = "template=".implode('|',$pageTemplates).", (layout_blocks.body~*=".$val."),(layout_blocks.text~*=".$val."),(layout_blocks.headline~*=".$val."),(layout_blocks.r_grid.body~*=".$val.")"; // findet mehrspalter aber keine einspalter | ||
| + | bd($selector,"selector for content"); | ||
| + | $matches = $pages->find($selector); | ||
| + | |||
| + | $searchResultMarkup .= "<h5>Suche im Seiteninhalt [$matches->count]</h5>"; | ||
| + | if($matches->count) { | ||
| + | $searchResultMarkup .= renderNav($matches); | ||
| + | } else { | ||
| + | $searchResultMarkup .= "<p>Keine Seiteninhalte mit diesem Suchbegriff gefunden.</p>"; | ||
| + | } | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | == Anzahl beschränken mit limit und start == | ||
| + | limit=50 // 50 or fewer results | ||
| + | start=50, limit=50 //50 (or less) results starting at the 51st (results 51–100). | ||
| + | |||
| + | If you are using a limit selector with pages, and your template has page-numbers (pagination) turned on, ProcessWire will automatically set the "start" selector according to the current page/pagination number. So when it comes to pagination, you don't usually have to think about anything other than the "limit" selector. | ||
| + | |||
| + | |||
| + | == Array Selectors == | ||
| + | https://processwire.com/blog/posts/processwire-3.0.13-selector-upgrades-and-new-form-builder-version/#building-a-selector-string-with-user-input-example | ||
| + | |||
| + | === Selektoren als assoziative Arrays === | ||
| + | |||
| + | Anstatt von Selector Strings kann man seit PW 3.0.13 auch Arrays nutzen.:d of a string: | ||
| + | <syntaxhighlight lang="php"> | ||
| + | $results = $pages->find([ | ||
| + | 'template' => ['basic-page', 'product'], | ||
| + | 'title|body%=' => $sanitizer->text($input->get('q')), | ||
| + | 'categories' => $sanitizer->intArray($input->get('categories')), | ||
| + | 'sort' => '-created' | ||
| + | ]); | ||
| + | </syntaxhighlight> | ||
| + | Erläuterung: | ||
| + | |||
| + | Die ''$sanitizer->selectorValue()'' Methode um Text zu sanitizen der in Selektoren geht ist nicht mehr notwendig. Du solltest immer noch User Input sanitizen, aber man kann sich die sanierung für die Selektoren sparen. | ||
| + | Werte können Arrays sein. Im Beispiel werden Arrays für 'template' and 'categories' items genutzt. | ||
| + | |||
| + | Der "=" Operator wird für alle Selektoren Elemente angenommen, solange man nicht einen anderen Operator anhängt. Wie bei '''title|body%=''' zu sehen. | ||
| + | |||
| + | === Selektoren als reguläre Arrays === | ||
| + | Man kann auch ein reguläres (nicht assoziatives Array nutzen: | ||
| + | <syntaxhighlight lang="php"> | ||
| + | $results = $pages->find([ | ||
| + | ['template', ['basic-page', 'product']], | ||
| + | ['title|body', '%=', $input->get('q'), 'text'], | ||
| + | ['categories', '=', $input->get('categories'), 'int'], | ||
| + | ['sort', '-created'] | ||
| + | ]); | ||
| + | </syntaxhighlight> | ||
| + | Hier werden die Selektorenteile als Array im Array übergeben. Das Format ist folgendes:f those arrays can use any of the following formats: | ||
| + | <pre> | ||
| + | [field, value] | ||
| + | [field, operator, value] | ||
| + | [field, operator, value, sanitizer] | ||
| + | [field, operator, value, whitelist] | ||
| + | </pre> | ||
| + | |||
| + | * The field element can be specified as a single field name, pipe "|" separated field names, or an array of field name(s). | ||
| + | * The operator can be any operator. If none is specified, then equals "=" is assumed (which you can do if only specifying a field and value). | ||
| + | * The value can be a string, number or array of either. | ||
| + | * The sanitizer can be any $sanitizer method name that you want the value to pass through before being used in the selector. | ||
| + | * When a whitelist (array) is specified for the sanitizer, the selector will throw an Exception if the given value (or values) are not present in the whitelist array. | ||
| + | |||
| + | Beide Array Formate (assoziativ, regulär) kann man theoretisch sogar mischen. | ||
| + | |||
| + | == Owner Selector == | ||
| + | https://processwire.com/blog/posts/processwire-3.0.95-core-updates/ | ||
| + | Mit Owner Selektoren kannst du Verknüpfungen die über PageTable pages, Page fields oder Repeater fields realisiert werden effizient durchsuchen, ohne Schleifen zu benutzen. | ||
| + | |||
| + | Es dauert etwas bis man das Konzept verstanden hat aber es ist extrem effektiv. | ||
| + | |||
| + | Eine zeitaufwändige Suche über eine Schleife wie diese: | ||
| + | <syntaxhighlight lang="php"> | ||
| + | $members = $pages->find("template=member, age>50"); | ||
| + | foreach($members as $m) { | ||
| + | $items = $m->memberships->find("club='Golf Club X', mtype=GOLD"); | ||
| + | foreach($items as $membership) { | ||
| + | // add to excel or other export, etc. | ||
| + | } | ||
| + | } | ||
| + | </syntaxhighlight> | ||
| + | wird dann einfach zu: | ||
| + | <syntaxhighlight lang="php"> | ||
| + | $items = $pages->find("club='Golf Club X', mtype=GOLD, memberships.owner.age>50"); | ||
| + | foreach($items as $membership) { | ||
| + | // add to excel or other export, etc. | ||
| + | } | ||
| + | </syntaxhighlight> | ||
| + | Anstatt über template=member zuerst alle Members zu durchlaufen und diese dann weiter nach Mitgliedschaften zu filtern geht man den Weg anders herum. Man nimmt das Feld das man sucht und schaut über den owner Selector wo es überall Referenziert wird. Also eine Art Rückwärtssuche. | ||
== Beispiele == | == Beispiele == | ||
| + | === Datum === | ||
| + | Per Default nutzt PW das Datum als Timestamp. Um z.B. alle | ||
| + | |||
| + | For recieving page of today, you would have to create a start and end time range and use them in the selector. | ||
| + | <syntaxhighlight lang="php"> | ||
| + | $start = strtotime( date('Y-m-d') . " 00:00:00"); | ||
| + | $end = strtotime( date('Y-m-d') . " 23:59:59"); | ||
| + | $items = $pages->find("template=linkmain,publishdate>=$start,publishdate<=$end,sort=-userid"); | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | Beispiel | ||
| + | <syntaxhighlight lang="php"> | ||
| + | $startDate = '2023-01-01'; | ||
| + | $endDate = '2023-03-31'; | ||
| + | $start = $startDate . ' 00:00:00'; | ||
| + | $end = $endDate . ' 23:59:59'; | ||
| + | $paidInvoices = pages("template=invoice, invoice_paid=1, invoice_date>=$start, invoice_date<=$end"); | ||
| + | </syntaxhighlight> | ||
| + | Todo Beispiele mit wire()-> Datumsfunktionen | ||
| + | |||
| + | === Parents === | ||
| + | To specify that matches should have a '''specific parent''', specify the parent's path, object or ID. First is an example of using the parent's path: | ||
| + | https://processwire.com/docs/selectors/#finding2 | ||
| + | parent=/path/to/parent/ | ||
| + | parent=$parent | ||
| + | parent=123 | ||
| + | parent=$parent1|$parent2|$parent3 | ||
| + | |||
| + | ==== Parents bei Repeatern oder RepeaterMatrix ==== | ||
| + | https://wiki.stephanschlegel.de/index.php?title=ProcessWire_-_Snippets#Parent_von_Repeater_oder_RepeaterMatrix_finden | ||
| + | |||
=== Sortiere Seiten nach Reihenfolge im Seitenbaum === | === Sortiere Seiten nach Reihenfolge im Seitenbaum === | ||
Das funktioniert mit der Sortierung "sort". | Das funktioniert mit der Sortierung "sort". | ||
| Zeile 183: | Zeile 352: | ||
=== Suche in PageReference Feldern === | === Suche in PageReference Feldern === | ||
| − | Generell gilt PageReferences verhalten sich gleich wie wenn man auf ein | + | Generell gilt PageReferences verhalten sich gleich wie wenn man auf ein Page-Object zugreifen würde. |
https://processwire.com/talk/topic/1224-selector-and-page-reference-field/ | https://processwire.com/talk/topic/1224-selector-and-page-reference-field/ | ||
| − | Finde | + | |
| − | * Template | + | '''Beispiel:''' Finde alle Point of Interest Seiten die eine Referenz auf die Kategorie "Zoo" haben |
| − | * poi_type | + | * Template '''poi''' (Point of Interest) |
| + | ** Feld '''poi_type''' (PageReference) referenziert auf Seiten mit dem Template type | ||
| + | * Template '''type''' | ||
| + | |||
Der Filter | Der Filter | ||
$poi = $pages->find(template=poi, poi_type.title='Zoo'); | $poi = $pages->find(template=poi, poi_type.title='Zoo'); | ||
| − | Funktioniert nicht | + | Funktioniert nicht! |
Stattdessen | Stattdessen | ||
| − | + | # holt man zuerst alle type-Seiten mit dem Titel Zoo | |
| − | + | # Dieses PageArray kann man direkt als Filter für eine Suche in den POIs nutzen. | |
| + | |||
| + | <syntaxhighlight lang="php"> | ||
| + | $pr = $pages->get("title=Zoo"); | ||
| + | $poi = $pages->find("template=poi, poi_type=$pr"); | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | '''Beispiel 2''' | ||
| + | <syntaxhighlight lang="php"> | ||
| + | $prs = $pages->find("title=Zoo|Themepark|Museum"); // maybe also use the name or id | ||
| + | $poi = $pages->find("template=poi, poi_type=$prs"); | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | ACHTUNG Hier ist es wichtig im ersten Selektor find zu verwenden. Get würde nur den ersten Treffer ausspucken, während find ein PageArray mit allen Ergebnissen zurückgibt. | ||
| − | + | '''Beispiel 3''' | |
| − | + | <syntaxhighlight lang="php"> | |
| + | $invoicesNotSent = $pages->find('template=invoice,invoice_sent=false'); | ||
| + | $selector = "template=order,(invoice=$invoicesNotSent),(padinvoice=)"; | ||
| + | $ordersWithoutInvoiceOrInvoiceNotSent = $pages->find( $selector ); | ||
| + | </syntaxhighlight> | ||
=== Punkt Syntax === | === Punkt Syntax === | ||
| Zeile 229: | Zeile 418: | ||
$items = $users->find("roles=superuser"); | $items = $users->find("roles=superuser"); | ||
| − | == | + | === Suche alle Kinder / alle Elternseiten === |
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
<syntaxhighlight lang="php"> | <syntaxhighlight lang="php"> | ||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | + | /** | |
| + | * get children categories for a category for a product | ||
| + | * | ||
| + | * Page $p category page | ||
| + | * int $maxDepth | ||
| + | */ | ||
| + | function getChildren($p, $maxDepth=3){ | ||
| + | $children = new PageArray; | ||
| + | $children->add($p); // add parent category | ||
| + | if ($p->hasChildren() && $maxDepth > 1){ | ||
| + | $children->add( $p->children('template=category') ); | ||
| + | foreach($p->children as $c){ | ||
| + | $grandchildren = getChildren($c, $maxDepth-1); | ||
| + | $children->add($grandchildren); | ||
| + | } | ||
| + | $children->sort('title'); | ||
| + | return $children; | ||
| + | }else return false; | ||
| + | } | ||
| − | == | + | /** |
| − | + | * get filter Categories for a item this includes all parent categories | |
| − | + | * @return string use as class for the isotope item | |
| − | $ | + | * */ |
| − | + | function getFilters($item,$prefix='cat'){ | |
| − | + | // we need to fetch $item categories + parent categories | |
| − | + | $filters = array(); | |
| − | + | $allCategories = new Pagearray; | |
| − | + | $categories = $item->categories; | |
| + | // for each category add category + parent categories to allCategories | ||
| + | foreach($categories as $category){ | ||
| + | $allCategories->add( $category ); | ||
| + | $allCategories->add( $category->parents('template=category') ); | ||
| + | } | ||
| + | foreach($allCategories as $c){ | ||
| + | $filters[]= $prefix.$c->id; | ||
| + | } | ||
| + | return implode(' ',$filters); | ||
| + | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | + | === Schneller CSV-Export von Selector-Ergebnissen === | |
| − | + | [[ProcessWire - schneller CSV-Export]] | |
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
| − | |||
Aktuelle Version vom 17. Juni 2025, 08:17 Uhr
Operatoren[Bearbeiten]
http://cheatsheet.processwire.com/selectors/selector-operators/
Selector Operators
= Equal to (any_field=any_value)
!= Not equal to (any_field!=any_value)
< Less than (any_field
> Greater than any_field>any_value
<= Less than or equal to (any_field<=any_value)
>= Greater than or equal to (any_field>=any_value)
*= Contains the exact word or phrase (any_field*=any_value)
~= Contains all the words (any_field~=any_value)
%= Contains the exact word or phrase (using slower SQL LIKE) [v2.1] (any_field%=any_value)
^= Contains the exact word or phrase at the beginning of the field [v2.1] (any_field^=any_value)
$= Contains the exact word or phrase at the end of the field [v2.1] (any_field$=any_value)
Neue Operatoren ab 3.0.160[Bearbeiten]
List of new operators available as of ProcessWire 3.0.160
Here's a list of new operators available as of 3.0.160, along with brief explanation of what each operator does and how it differs from other similar operators.
Contains words partial (~*=) Like existing match words (~=) operator, except that this one matches partial words as well.
Contains words live (~~=) Like match words, except that the last word in the query is treated as a partial match.
Contains words like (~%=) Matches all words in the query, in full or in part.
Contains words and expand (~+=) Like match words operator, but with the added power of the query expansion feature supported by MySQL fulltext indexes.
Contains any words (~|=) One or more of the words must match; this is similar to splitting the query with pipe (|) characters, but often easier to use, and better optimized.
Contains any partial words (~|*=) Similar to the previous operator, except that this one also provides partial matches.
Contains any words like (~|%=) Similar to the previous two operators, but uses LIKE query behind the scenes instead of the fulltext index.
Contains phrase and expand (*+=) Variation of the phrase match operator (*=) with added query expansion support.
Contains match (**=) This operator works much like the MATCH/AGAINST feature of MySQL fulltext indexes.
Contains match and expand (**+=) Otherwise identical to previous operator, except for the added query expansion.
Advanced text search (#=) This operator adds support for special characters, such as "+" for "must match", "-" for "must not match", and "*" for specifying partial matches.
Owner Attribut[Bearbeiten]
Nützlich bei Pagereferences, wenn auf die Seite verweisende Seiten gefunden und gleichzeitig gefiltert werden sollen.
https://processwire.com/blog/posts/processwire-3.0.95-core-updates/
$members = $pages->find("template=member, age>50");
foreach($members as $m) {
$items = $m->memberships->find("club='Golf Club X', mtype=GOLD");
foreach($items as $membership) {
// add to excel or other export, etc.
}
}
Ineffektiv bei vielen Datensätzen ->
$items = $pages->find("club='Golf Club X', mtype=GOLD, memberships.owner.age>50");
foreach($items as $membership) {
// add to excel or other export, etc.
}
Kombinierte Abfragen und Subselektoren[Bearbeiten]
Da man auch Seiten im Selektor übergeben kann, kann man relativ einfach kombinierte Abfragen über mehrere Templates, oder auch über parents etc. machen. Mit Subselektoren kann man das noch abkürzen.
Kombinierte Abfrage
$companies = $pages->find("template=company, locations>5, locations.title%=Finland");
$items = $pages->find("template=product, company=$companies");
Mit Subselektoren
$items = $pages->find("template=product, company=[locations>5, locations.title%=Finland]");
OR / AND[Bearbeiten]
OR funktioniert über
Feldwert a oder Feldwert b
firstname=Mike|Steve
Feldwert a und Feldwert b
height>500, height<=1000
In Feld a oder in Feld b
body|sidebar*=carbonated
OR Groups[Bearbeiten]
(Bedingung a, Bedingung b),(Bedingung c) Wenn man Klammern nutzt muss nur eine der Klammern zutreffen.
Beispiel "product" Seiten in stock, UND entweder in featured date range, ODER highlighted checkbox checked.
$items = $pages->find("template=product, stock>0, (featured_from<=today, featured_to>=today), (highlighted=1)");
Die Klammern kennzeichnen Optionale Bedingungen. Es muss also nur eine der Klammern zutreffen.
Wenn man mehrere Oder-Gruppen benötigt kann man so vorgehen:
foo=(selector1), bar=(selector2), foo=(selector3), bar=(selector4)
Hier gehören alle foo zusammen und alle bar. Sprich es muss selector1 ODER selector3 UND selector2 ODER selector4 erfüllt sein.
https://processwire.com/docs/selectors/#or-selectors1
Selektoren und RepeaterMatrix[Bearbeiten]
Beispiel TV Altötting
//BEISPIEL: $results = $pages->find("template=matrix_page,matrix_main.body%=$q"); // name des matrix items weglassen
//$selector = "template=".implode('|',$pageTemplates).", layout_blocks.body~*=".$val; // findet einspalter aber keine in
//$selector = "template=".implode('|',$pageTemplates).", layout_blocks.r_grid.body~*=".$val; // findet mehrspalter aber keine einspalter
// dot notation not allowed with or so we have to use or groups or bracket notation:
$selector = "template=".implode('|',$pageTemplates).", (layout_blocks.body~*=".$val."),(layout_blocks.text~*=".$val."),(layout_blocks.headline~*=".$val."),(layout_blocks.r_grid.body~*=".$val.")"; // findet mehrspalter aber keine einspalter
bd($selector,"selector for content");
$matches = $pages->find($selector);
$searchResultMarkup .= "<h5>Suche im Seiteninhalt [$matches->count]</h5>";
if($matches->count) {
$searchResultMarkup .= renderNav($matches);
} else {
$searchResultMarkup .= "<p>Keine Seiteninhalte mit diesem Suchbegriff gefunden.</p>";
}
Anzahl beschränken mit limit und start[Bearbeiten]
limit=50 // 50 or fewer results start=50, limit=50 //50 (or less) results starting at the 51st (results 51–100).
If you are using a limit selector with pages, and your template has page-numbers (pagination) turned on, ProcessWire will automatically set the "start" selector according to the current page/pagination number. So when it comes to pagination, you don't usually have to think about anything other than the "limit" selector.
Array Selectors[Bearbeiten]
Selektoren als assoziative Arrays[Bearbeiten]
Anstatt von Selector Strings kann man seit PW 3.0.13 auch Arrays nutzen.:d of a string:
$results = $pages->find([
'template' => ['basic-page', 'product'],
'title|body%=' => $sanitizer->text($input->get('q')),
'categories' => $sanitizer->intArray($input->get('categories')),
'sort' => '-created'
]);
Erläuterung:
Die $sanitizer->selectorValue() Methode um Text zu sanitizen der in Selektoren geht ist nicht mehr notwendig. Du solltest immer noch User Input sanitizen, aber man kann sich die sanierung für die Selektoren sparen. Werte können Arrays sein. Im Beispiel werden Arrays für 'template' and 'categories' items genutzt.
Der "=" Operator wird für alle Selektoren Elemente angenommen, solange man nicht einen anderen Operator anhängt. Wie bei title|body%= zu sehen.
Selektoren als reguläre Arrays[Bearbeiten]
Man kann auch ein reguläres (nicht assoziatives Array nutzen:
$results = $pages->find([
['template', ['basic-page', 'product']],
['title|body', '%=', $input->get('q'), 'text'],
['categories', '=', $input->get('categories'), 'int'],
['sort', '-created']
]);
Hier werden die Selektorenteile als Array im Array übergeben. Das Format ist folgendes:f those arrays can use any of the following formats:
[field, value]
[field, operator, value]
[field, operator, value, sanitizer]
[field, operator, value, whitelist]
- The field element can be specified as a single field name, pipe "|" separated field names, or an array of field name(s).
- The operator can be any operator. If none is specified, then equals "=" is assumed (which you can do if only specifying a field and value).
- The value can be a string, number or array of either.
- The sanitizer can be any $sanitizer method name that you want the value to pass through before being used in the selector.
- When a whitelist (array) is specified for the sanitizer, the selector will throw an Exception if the given value (or values) are not present in the whitelist array.
Beide Array Formate (assoziativ, regulär) kann man theoretisch sogar mischen.
Owner Selector[Bearbeiten]
https://processwire.com/blog/posts/processwire-3.0.95-core-updates/
Mit Owner Selektoren kannst du Verknüpfungen die über PageTable pages, Page fields oder Repeater fields realisiert werden effizient durchsuchen, ohne Schleifen zu benutzen.
Es dauert etwas bis man das Konzept verstanden hat aber es ist extrem effektiv.
Eine zeitaufwändige Suche über eine Schleife wie diese:
$members = $pages->find("template=member, age>50");
foreach($members as $m) {
$items = $m->memberships->find("club='Golf Club X', mtype=GOLD");
foreach($items as $membership) {
// add to excel or other export, etc.
}
}
wird dann einfach zu:
$items = $pages->find("club='Golf Club X', mtype=GOLD, memberships.owner.age>50");
foreach($items as $membership) {
// add to excel or other export, etc.
}
Anstatt über template=member zuerst alle Members zu durchlaufen und diese dann weiter nach Mitgliedschaften zu filtern geht man den Weg anders herum. Man nimmt das Feld das man sucht und schaut über den owner Selector wo es überall Referenziert wird. Also eine Art Rückwärtssuche.
Beispiele[Bearbeiten]
Datum[Bearbeiten]
Per Default nutzt PW das Datum als Timestamp. Um z.B. alle
For recieving page of today, you would have to create a start and end time range and use them in the selector.
$start = strtotime( date('Y-m-d') . " 00:00:00");
$end = strtotime( date('Y-m-d') . " 23:59:59");
$items = $pages->find("template=linkmain,publishdate>=$start,publishdate<=$end,sort=-userid");
Beispiel
$startDate = '2023-01-01';
$endDate = '2023-03-31';
$start = $startDate . ' 00:00:00';
$end = $endDate . ' 23:59:59';
$paidInvoices = pages("template=invoice, invoice_paid=1, invoice_date>=$start, invoice_date<=$end");
Todo Beispiele mit wire()-> Datumsfunktionen
Parents[Bearbeiten]
To specify that matches should have a specific parent, specify the parent's path, object or ID. First is an example of using the parent's path:
https://processwire.com/docs/selectors/#finding2 parent=/path/to/parent/ parent=$parent parent=123 parent=$parent1|$parent2|$parent3
Parents bei Repeatern oder RepeaterMatrix[Bearbeiten]
https://wiki.stephanschlegel.de/index.php?title=ProcessWire_-_Snippets#Parent_von_Repeater_oder_RepeaterMatrix_finden
Sortiere Seiten nach Reihenfolge im Seitenbaum[Bearbeiten]
Das funktioniert mit der Sortierung "sort".
$categories = pages('template=template_name,sort=sort');
Große Datenmenge mit findMany() durchsuchen[Bearbeiten]
findMany() - ProcessWire API
Suche nach Seiten die Verweise auf bestimmte andere Seiten enthalten[Bearbeiten]
https://processwire.com/talk/topic/5414-selector-find-page-reference-help/
Es sollen Seiten gefunden werden die mit einer Page Reference auf eine andere Seite verweisen. Am einfachsten geht das wenn man nicht wie man zuerst vermutet nach der Seiten ID sucht, sondern wenn man direkt nach der Seite sucht
team_name=$page
Suche nach Phrasen in Daten die in Seitenverweise enthalten sind[Bearbeiten]
https://processwire.com/talk/topic/570-searching-page-reference-fields/
Es sollen Seiten gefunden werden, die Verweise auf andere Seiten enthalten. Beispielsweise enthalten Personen (Eltern) Links zu Notfalladressen die separat angelegt sind. Nun soll Nach Eltern gesucht werden, die eine bestimmte Notfalladresse enthalten. Gesucht wird nach einer Phrase im Notfalladrdessen Namen).
Lösung: Es wird in zwei Schritten gesucht.
1. Suche nach Kontakten mit dem Search Term im body und die dem template emergency-contact entsprechen
$contacts = $pages->find("body*='search term', template=emergency-contact");
2. Seiten die diesen Kontakten entsprechen
$parents = $pages->find("emergency-contacts=$contacts");
Selektoren in Option Fieldtypes[Bearbeiten]
$optionsfield // return id (string)
$optionsfield->id; // return id (int)
$optionsfield->title; // return string USE THIS or
$optionsfield->value; // return empty string or value (if your option settings like '1=value|title')
// dot syntax in selector string
$pages->find('optionsfield.id=2');
Selektoren für Multiple Options[Bearbeiten]
Finde Seiten in gewählten Optionen[Bearbeiten]
Nehmen wir an wir haben Seiten mit dem Template tag und ein Template product, das wiederum ein PageReference Feld 'tags' hat bei dem man ein oder mehrere Tags auswählen kann.
1. Seiten die eines oder mehr der gewählten Tags haben.
$myTags = array();
// find product pages which fit all options
$tags = array();
foreach($page->tag_selector as $tag) {
$tags[] = $tag->name;
}
$items = $items->find('template=product,tags.name=' . implode('|',$tags) );
//bd($items);
2. Seiten die alle gewählten Tags haben oder mindestens einen (mit Schalter)
$or = $page->opt_1;
if(count($page->tag_selector)){
$myTags = array();
$tags = array();
foreach($page->tag_selector as $tag) {
if ($or) $tags[] = $tag->name;
else $tags[] = 'tag.name='.$tag->name;
}
if ($or) $items = pages()->find('template=product,tags.name=' . implode('|',$tags) ); //OR
else $items = pages()->find('template=product,'.implode(',',$tags)); // AND
bd($items);
Seiten finden[Bearbeiten]
$skyscrapers = $pages->find("template=skyscraper, sort=-modified");
foreach($skyscrapers as $skyscraper) {
echo "<li><a href='$skyscraper->url'>$skyscraper->title</a></li>";
}
Rekursiv suchen[Bearbeiten]
$pages->find("parent={$cat->children}, limit=$limit, sort=-date, sort=title"); // expands to something like "parent=1234|1235|1236|1237|...|1507|1508"
Page Reference auf diese Seite[Bearbeiten]
https://processwire.com/talk/topic/1071-page-fieldtype-two-way-relation/
echo $pages->find("field1=$page")->render();
If the page isn't part of the front-end site, then I'll remove view access from its template. Or if it is part of the front-end, but I don't want to show the relations, then this:
if($page->editable()) echo $pages->find("field1=$page")->render();
Though I almost always integrate these relation-revealing pages into the site structure, as it's rare that this information doesn't have some value to the site's users too. This is an example of one that locates all pages referencing it in a field called 'country':
https://www.tripsite.com/countries/croatia/
Suche in PageReference Feldern[Bearbeiten]
Generell gilt PageReferences verhalten sich gleich wie wenn man auf ein Page-Object zugreifen würde.
https://processwire.com/talk/topic/1224-selector-and-page-reference-field/
Beispiel: Finde alle Point of Interest Seiten die eine Referenz auf die Kategorie "Zoo" haben
- Template poi (Point of Interest)
- Feld poi_type (PageReference) referenziert auf Seiten mit dem Template type
- Template type
Der Filter
$poi = $pages->find(template=poi, poi_type.title='Zoo');
Funktioniert nicht!
Stattdessen
- holt man zuerst alle type-Seiten mit dem Titel Zoo
- Dieses PageArray kann man direkt als Filter für eine Suche in den POIs nutzen.
$pr = $pages->get("title=Zoo");
$poi = $pages->find("template=poi, poi_type=$pr");
Beispiel 2
$prs = $pages->find("title=Zoo|Themepark|Museum"); // maybe also use the name or id
$poi = $pages->find("template=poi, poi_type=$prs");
ACHTUNG Hier ist es wichtig im ersten Selektor find zu verwenden. Get würde nur den ersten Treffer ausspucken, während find ein PageArray mit allen Ergebnissen zurückgibt.
Beispiel 3
$invoicesNotSent = $pages->find('template=invoice,invoice_sent=false');
$selector = "template=order,(invoice=$invoicesNotSent),(padinvoice=)";
$ordersWithoutInvoiceOrInvoiceNotSent = $pages->find( $selector );
Punkt Syntax[Bearbeiten]
$architects = $pages->find("template=architect, city.title=Chicago");
$buildings = $pages->find("architect=$architects");
That's easy enough, but wouldn't it be nicer if you could just do this?
$buildings = $pages->find("architect.city.title=Chicago");
$buildings = $pages->find("architect.city.state.abbr=IL");
Broadening further, perhaps we want buildings from all architects in the USA:
$buildings = $pages->find("architect.city.state.country.abbr=USA");
Or perhaps both USA and Canada:
$buildings = $pages->find("architect.city.state.country.abbr=USA|CA");
User[Bearbeiten]
http://cheatsheet.processwire.com/users/users-methods/users-find-selector/
Find all users whose email address ENDS with processwire.com and create a link to email them
$items = $users->find("email$=processwire.com");
foreach($items as $item) {
echo "<li><a href='mailto:{$item->email}'>{$item->name}</a></li>";
}
Find all users who have "fred" anywhere in their name
$items = $users->find("name*=fred");
Find all users who have the "superuser" role
$items = $users->find("roles=superuser");
Suche alle Kinder / alle Elternseiten[Bearbeiten]
/**
* get children categories for a category for a product
*
* Page $p category page
* int $maxDepth
*/
function getChildren($p, $maxDepth=3){
$children = new PageArray;
$children->add($p); // add parent category
if ($p->hasChildren() && $maxDepth > 1){
$children->add( $p->children('template=category') );
foreach($p->children as $c){
$grandchildren = getChildren($c, $maxDepth-1);
$children->add($grandchildren);
}
$children->sort('title');
return $children;
}else return false;
}
/**
* get filter Categories for a item this includes all parent categories
* @return string use as class for the isotope item
* */
function getFilters($item,$prefix='cat'){
// we need to fetch $item categories + parent categories
$filters = array();
$allCategories = new Pagearray;
$categories = $item->categories;
// for each category add category + parent categories to allCategories
foreach($categories as $category){
$allCategories->add( $category );
$allCategories->add( $category->parents('template=category') );
}
foreach($allCategories as $c){
$filters[]= $prefix.$c->id;
}
return implode(' ',$filters);
}
Schneller CSV-Export von Selector-Ergebnissen[Bearbeiten]
ProcessWire - schneller CSV-Export