ProcessWire - Selectors

Aus Wikizone
Wechseln zu: Navigation, Suche

Operatoren

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

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

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

Beispiele

Sortiere Seiten nach Reihenfolge im Seitenbaum

Das funktioniert mit der Sortierung "sort".

$categories = pages('template=template_name,sort=sort');

Große Datenmenge mit findMany() durchsuchen

findMany() - ProcessWire API

Suche nach Seiten die Verweise auf bestimmte andere Seiten enthalten

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

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

$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

Finde Seiten in gewählten Optionen

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

TODO

Seiten finden

$skyscrapers = $pages->find("template=skyscraper, sort=-modified");
foreach($skyscrapers as $skyscraper) {
    echo "<li><a href='$skyscraper->url'>$skyscraper->title</a></li>";
}

Page Reference auf diese Seite

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

Generell gilt PageReferences verhalten sich gleich wie wenn man auf ein PageObject zugreifen würde.

https://processwire.com/talk/topic/1224-selector-and-page-reference-field/

Finde Felder mit

  • Template = POI
  • poi_type.type = "zoo" (PageReference)

Der Filter

$poi = $pages->find(template=poi, poi_type.title='Zoo'); 

Funktioniert nicht.

Stattdessen - holt man zuerst alle Seiten mit dem Titel Zoo und - nimmt diese Menge als Filter für eine Suche im PageReference Feld (poi_type)

$pr = $pages->get("title=Zoo");
$poi = $pages->find("template=poi, poi_type=$pr");

Punkt Syntax

$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

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");

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:

$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

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.