Skip to content

Instantly share code, notes, and snippets.

@vgrem
Created June 8, 2023 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vgrem/7a9d06814edb93277234991f47ca22bf to your computer and use it in GitHub Desktop.
Save vgrem/7a9d06814edb93277234991f47ca22bf to your computer and use it in GitHub Desktop.
The example demonstrates how to retrieve and filter items by Managed Metadata field (column) value
<?php
require_once './vendor/autoload.php';
$settings = include('./settings.php');
use Office365\Runtime\Auth\ClientCredential;
use Office365\SharePoint\CamlQuery;
use Office365\SharePoint\ClientContext;
$credentials = new ClientCredential($settings['ClientId'], $settings['ClientSecret']);
$siteUrl = $settings['TeamSiteUrl'];
/**
* The example demonstrates how to retrieve and filter items by Managed Metadata field (column)
* Three options are considered:
* 1) filter with OData filter query option
* 2) filter with CAML query <-- note: recommended and tested on my env
* 3) client side filtering
*/
$ctx = (new ClientContext($siteUrl))->withCredentials($credentials);
$listTitle = "Documents";
$list = $ctx->getWeb()->getLists()->getByTitle($listTitle);
//Option 1: filter with OData filter query option
//As we discussed: this option will NOT work since filtering by managed metadata is not supported by OData in SharePoint API
//The next line will throw the exception
//$items = $list->getItems()->filter("Module eq 'Finland'")->get()->executeQuery();
//Option 2: filter with CAML query
//This approach should work as expected. We utilize CAML query which supports filtering by Managed Metadata field
//
$qry = new CamlQuery();
$qry->ViewXml = <<<XML
<View Scope='RecursiveAll'>
<Query><Where><Eq><FieldRef Name="Module" /><Value Type="TaxonomyFieldType">Finland</Value></Eq></Where></Query>
<RowLimit Paged="TRUE">1000</RowLimit>
</View>
XML;
$items = $list->getItems($qry)->executeQuery();
/**
* Managed Metadata field value is represented as array in the following format:
* {
Label="Finland"
TermGuid="--guid goes here--"
WssId=-1
}
*/
foreach ($items as $item){
print($item->getProperty("Module")["Label"] . "\r\n"); //print label
}
//Option 3: filter with CAML query
//I would suggest to utilize option 2 instead :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment