Showing posts with label LiquidTemplating. Show all posts
Showing posts with label LiquidTemplating. Show all posts

Thursday, May 7, 2026

Liquid code in Power Pages - FetchXML

FetchXML is the native query language of Microsoft Dataverse. If you're building anything serious on the Power Platform — flows, plugins, portals, or canvas apps — you will hit a wall with OData eventually. This guide is the syllabus I wish existed when I started: every feature, every operator, real patterns you'll actually use in production.

1. What is FetchXML

FetchXML is an XML-based query language built specifically for Microsoft Dataverse (formerly Common Data Service / CDS). It's the closest thing Dataverse has to SQL — you write structured XML describing which records you want, and Dataverse translates it internally into the right database query.

It predates OData in the Dynamics ecosystem and remains more powerful for complex scenarios: multi-level joins, aggregates, cross-entity filtering, and paging over large datasets.

When to use FetchXML vs the alternatives

  • FetchXML — complex joins, aggregates, paging over 5,000 records, cross-entity conditions, working inside plugins or C# code
  • OData ($filter) — simple single-entity queries via Web API, quick REST calls, Power Automate "List Rows" without complex joins
  • LINQ (early-bound C#) — type-safe queries in plugin/tool code, good for simple lookups, limited aggregate support

Where FetchXML runs

  • Power Automate — "List rows" action on Dataverse connector → FetchXML input
  • Power Apps — via Collect with a Dataverse table or inside canvas app formulas using the connector
  • Plugins / C# — IOrganizationService.RetrieveMultiple(new FetchExpression(fetchXml))
  • Web API — GET /api/data/v9.2/entity?fetchXml=<encoded xml>
  • XrmToolBox — FetchXML Builder plugin for visual building and live testing
  • Power Pages / Portals — FetchXML-based data lists and liquid templates
<!-- Minimal valid FetchXML -->
<fetch>
  <entity name="account">
    <attribute name="name" />
    <attribute name="emailaddress1" />
  </entity>
</fetch>

2. Basic Structure

Every FetchXML query follows the same skeleton. Learn this once and everything else is layers on top.

The fetch element

AttributeValuesWhat it does
topintegerLimits result count (like SQL TOP). Omit for full result set.
distincttrue / falseRemoves duplicate rows. Essential when using outer joins.
no-locktrue / falseAdds NOLOCK hint. Use for read-heavy reporting queries.
aggregatetrue / falseSwitches the query to aggregate mode (section 6).
pageintegerPage number for paging (section 7).
countintegerPage size for paging. Max 5000.

entity, attribute, order

  • <entity name="logical_name"> — the table you're querying. Always use the logical name (lowercase, prefixed).
  • <attribute name="field_name" /> — columns to return. Omit completely to return all columns (not recommended for production).
  • <order attribute="field_name" descending="false" /> — sort order. Stack multiple for multi-column sort.
<fetch top="50" distinct="true" no-lock="true">
  <entity name="contact">
    <attribute name="fullname" />
    <attribute name="emailaddress1" />
    <attribute name="createdon" />
    <order attribute="createdon" descending="true" />
    <order attribute="fullname" descending="false" />
  </entity>
</fetch>
Tip: Never omit all <attribute> elements in production queries. Selecting all columns is a silent performance killer — you end up fetching columns you never use across potentially thousands of rows.

3. Filtering — <filter> and <condition>

Filters are where FetchXML earns its keep. The <filter> element wraps one or more <condition> elements and can be nested arbitrarily deep.

condition anatomy

<condition attribute="fieldname" operator="eq" value="somevalue" />

Complete Operator Reference

OperatorSQL EquivalentNotes
eq= valueExact match
ne!= valueNot equal
gt> valueGreater than
lt< valueLess than
ge>= valueGreater than or equal
le<= valueLess than or equal
likeLIKE '%val%'Use % wildcard. Leading % kills index — avoid.
not-likeNOT LIKEInverse of like
inIN (v1,v2,v3)Uses <value> child elements
not-inNOT INUses <value> child elements
betweenBETWEEN v1 AND v2Uses two <value> child elements
nullIS NULLNo value attribute needed
not-nullIS NOT NULLNo value attribute needed
eq-useridCurrent user IDNo value needed. Dynamic current user.
ne-useridNot current user
eq-businessidCurrent BU ID
today= CAST(GETDATE() AS DATE)Date fields only
tomorrowTomorrow's date
yesterdayYesterday's date
this-weekCurrent calendar week
this-monthCurrent calendar month
this-yearCurrent year
last-seven-daysRolling 7 days back
last-x-daysRolling N days backRequires value="N"
next-x-daysRolling N days forwardRequires value="N"
last-x-monthsRolling N months backRequires value="N"
next-x-monthsRolling N months forward
onExact dateDate fields, value = YYYY-MM-DD
on-or-before<= date
on-or-after>= date
begins-withLIKE 'val%'Index-safe unlike leading wildcard like
ends-withLIKE '%val'Avoid on large tables
contain-valuesMulti-select option setUses <value> child elements
not-contain-valuesMulti-select exclusion

Examples

<!-- IN operator -->
<condition attribute="statuscode" operator="in">
  <value>1</value>
  <value>2</value>
  <value>290560001</value>
</condition>

<!-- BETWEEN operator -->
<condition attribute="createdon" operator="between">
  <value>2024-01-01</value>
  <value>2024-12-31</value>
</condition>

<!-- Dynamic date operators -->
<condition attribute="modifiedon" operator="last-x-days" value="30" />

<!-- Null check -->
<condition attribute="emailaddress1" operator="null" />

<!-- Current user -->
<condition attribute="ownerid" operator="eq-userid" />

<!-- Like with trailing wildcard only (index-safe) -->
<condition attribute="name" operator="like" value="Contoso%" />

4. AND vs OR Logic

By default, all conditions inside a <filter> are ANDed together. Set type="or" to switch to OR. Nest filters to build complex boolean trees.

<!-- Default AND: active accounts in the US -->
<filter>
  <condition attribute="statecode" operator="eq" value="0" />
  <condition attribute="address1_country" operator="eq" value="United States" />
</filter>
<!-- OR: either status applies -->
<filter type="or">
  <condition attribute="statuscode" operator="eq" value="1" />
  <condition attribute="statuscode" operator="eq" value="290560001" />
</filter>
<!-- Mixed AND + OR nesting:
     (statecode = 0) AND (country = 'US' OR country = 'Canada') -->
<filter type="and">
  <condition attribute="statecode" operator="eq" value="0" />
  <filter type="or">
    <condition attribute="address1_country" operator="eq" value="United States" />
    <condition attribute="address1_country" operator="eq" value="Canada" />
  </filter>
</filter>
<!-- Real pattern: projects that are completed OR cancelled OR have no tasks -->
<fetch>
  <entity name="project">
    <attribute name="name" />
    <attribute name="statuscode" />
    <filter type="and">
      <condition attribute="ownerid" operator="eq-userid" />
      <filter type="or">
        <condition attribute="statuscode" operator="eq" value="290560002" />
        <condition attribute="statuscode" operator="eq" value="290560003" />
        <condition entityname="tsk" attribute="taskid" operator="null" />
      </filter>
    </filter>
    <link-entity name="task" from="regardingobjectid" to="projectid"
                 link-type="outer" alias="tsk">
      <attribute name="taskid" />
    </link-entity>
  </entity>
</fetch>
Watch out: The entityname attribute on a <condition> lets you filter on a joined entity's columns from the parent filter. This only works with outer joins and is how you implement "NOT EXISTS" patterns. The value of entityname must match the alias on the <link-entity>.

5. Link-Entities (Joins)

FetchXML joins are called link-entities. They work like SQL JOINs and can be nested multiple levels deep.

link-type values

link-typeSQL EquivalentWhen to use
innerINNER JOINOnly return parent records that have a matching child. Default if omitted.
outerLEFT OUTER JOINReturn parent records even when no child exists. Required for "not exists" patterns.

Basic inner join

<!-- Contacts and their parent Account name -->
<fetch>
  <entity name="contact">
    <attribute name="fullname" />
    <attribute name="emailaddress1" />
    <link-entity name="account" from="accountid" to="parentcustomerid"
                 link-type="inner" alias="acc">
      <attribute name="name" alias="accountname" />
      <attribute name="telephone1" alias="accountphone" />
    </link-entity>
  </entity>
</fetch>

Multi-level joins

<!-- Three levels deep: Task → Stage → Project -->
<fetch>
  <entity name="task">
    <attribute name="subject" />
    <attribute name="statuscode" />
    <link-entity name="stage" from="stageid" to="stageid"
                 link-type="inner" alias="stg">
      <attribute name="name" alias="stagename" />
      <link-entity name="project" from="projectid" to="projectid"
                   link-type="inner" alias="proj">
        <attribute name="name" alias="projectname" />
        <attribute name="statuscode" alias="projectstatus" />
      </link-entity>
    </link-entity>
  </entity>
</fetch>

Filtering on a joined entity

<!-- Contacts whose account is in a specific industry -->
<fetch>
  <entity name="contact">
    <attribute name="fullname" />
    <link-entity name="account" from="accountid" to="parentcustomerid"
                 link-type="inner" alias="acc">
      <attribute name="name" alias="accountname" />
      <filter>
        <condition attribute="industrycode" operator="eq" value="7" />
      </filter>
    </link-entity>
  </entity>
</fetch>

Cross-entity condition (entityname attribute)

This pattern filters on a linked entity's column from the parent entity's filter block. Most commonly used for "NOT EXISTS" — find parent records where no child row matches.

<!-- Accounts with NO contacts -->
<fetch distinct="true">
  <entity name="account">
    <attribute name="name" />
    <filter>
      <condition entityname="con" attribute="contactid" operator="null" />
    </filter>
    <link-entity name="contact" from="parentcustomerid" to="accountid"
                 link-type="outer" alias="con">
      <attribute name="contactid" />
    </link-entity>
  </entity>
</fetch>
Rule: Cross-entity conditions (entityname=) always require the join to be link-type="outer". An inner join would already exclude the non-matching rows before the NULL check runs.

6. Aggregate Queries

Set aggregate="true" on <fetch> to switch to aggregate mode. In this mode, every <attribute> must declare an aggregate function or be a groupby column.

Aggregate functions

FunctionDescription
countCount of all rows (including nulls)
countcolumnCount of non-null values in a column
sumSum of numeric column
avgAverage of numeric column
minMinimum value
maxMaximum value
<!-- Count contacts per account -->
<fetch aggregate="true">
  <entity name="contact">
    <attribute name="contactid" aggregate="count" alias="contactcount" />
    <attribute name="parentcustomerid" groupby="true" alias="accountid" />
  </entity>
</fetch>
<!-- Sum and average of estimated revenue grouped by industry -->
<fetch aggregate="true">
  <entity name="opportunity">
    <attribute name="estimatedvalue" aggregate="sum" alias="totalrevenue" />
    <attribute name="estimatedvalue" aggregate="avg" alias="avgrevenue" />
    <attribute name="opportunityid" aggregate="count" alias="dealcount" />
    <attribute name="industrycode" groupby="true" alias="industry" />
    <filter>
      <condition attribute="statecode" operator="eq" value="0" />
    </filter>
  </entity>
</fetch>
<!-- Distinct count: unique companies with open cases -->
<fetch aggregate="true">
  <entity name="incident">
    <attribute name="customerid" aggregate="countcolumn" distinct="true" alias="uniquecustomers" />
    <filter>
      <condition attribute="statecode" operator="eq" value="0" />
    </filter>
  </entity>
</fetch>

Grouping by date parts

<!-- Cases created per month -->
<fetch aggregate="true">
  <entity name="incident">
    <attribute name="incidentid" aggregate="count" alias="casecount" />
    <attribute name="createdon" groupby="true" dategrouping="month" alias="createmonth" />
    <attribute name="createdon" groupby="true" dategrouping="year" alias="createyear" />
    <order alias="createyear" descending="false" />
    <order alias="createmonth" descending="false" />
  </entity>
</fetch>
Note: Aggregate FetchXML results are capped at 50,000 groups. For reporting over very large datasets, consider Azure Synapse Link or Dataverse long-term data export instead.

7. Paging

Dataverse returns a maximum of 5,000 records per request. For anything larger you must page through results using either simple page numbering or paging cookies.

Simple page/count attributes

<!-- Page 2, 100 records per page -->
<fetch page="2" count="100">
  <entity name="contact">
    <attribute name="fullname" />
    <attribute name="createdon" />
    <order attribute="createdon" descending="true" />
  </entity>
</fetch>

Paging cookies (correct approach for large datasets)

Simple page numbering degrades at scale because the database still scans from the beginning every time. Paging cookies pass a server-side bookmark that picks up exactly where the previous page ended — far more efficient.

The response from Dataverse includes a @Microsoft.Dynamics.CRM.fetchxmlpagingcookie annotation. Decode it and inject it into the next request:

<!-- First request: no cookie -->
<fetch page="1" count="5000">
  <entity name="contact">
    <attribute name="fullname" />
    <order attribute="contactid" descending="false" />
  </entity>
</fetch>

<!-- Subsequent requests: inject the decoded cookie -->
<fetch page="2" count="5000"
  paging-cookie="&lt;cookie page=&quot;1&quot;&gt;&lt;contactid ... /&gt;&lt;/cookie&gt;">
  <entity name="contact">
    <attribute name="fullname" />
    <order attribute="contactid" descending="false" />
  </entity>
</fetch>
Important: Always include an <order> on a unique field (like the primary key) when paging. Without a deterministic sort order, you can get duplicate or skipped records across pages.

Paging in C# (plugin or tool)

// C# paging loop example
string fetchXml = @"<fetch count='5000'>
  <entity name='contact'>
    <attribute name='fullname' />
    <order attribute='contactid' />
  </entity>
</fetch>";

var allRecords = new List<Entity>();
int pageNumber = 1;
string pagingCookie = null;

while (true)
{
    string pagedFetch = PatchFetchXmlPage(fetchXml, pageNumber, pagingCookie);
    var result = service.RetrieveMultiple(new FetchExpression(pagedFetch));
    allRecords.AddRange(result.Entities);

    if (!result.MoreRecords) break;

    pagingCookie = result.PagingCookie;
    pageNumber++;
}

8. FetchXML in Power Automate

The Dataverse connector's List rows action accepts a FetchXML query directly. This unlocks joins, aggregates, and paging that you simply cannot do with OData filter expressions.

Basic setup

  1. Add action: Microsoft Dataverse → List rows
  2. Set Table Name to your entity
  3. Expand Advanced options
  4. Paste your FetchXML into the Fetch Xml Query field
<fetch top="500" no-lock="true">
  <entity name="contact">
    <attribute name="fullname" />
    <attribute name="emailaddress1" />
    <filter>
      <condition attribute="statecode" operator="eq" value="0" />
    </filter>
  </entity>
</fetch>

Injecting dynamic values safely

In Power Automate, FetchXML is a string. You can inject dynamic expressions using @{expression} syntax. The critical rule: never inject user-controlled input directly — always validate or use GUIDs from trigger/action outputs.

<!-- Safe: injecting a trigger GUID value -->
<fetch>
  <entity name="task">
    <attribute name="subject" />
    <attribute name="statuscode" />
    <filter>
      <condition attribute="regardingobjectid" operator="eq"
        value="@{triggerOutputs()?['body/accountid']}" />
      <condition attribute="createdon" operator="last-x-days"
        value="@{variables('DaysBack')}" />
    </filter>
  </entity>
</fetch>

Dynamic IN clause from an array variable

<!-- Step 1: Build <value> tags using Select action -->
<!-- Select "from": array of IDs, "map": concat('<value>', item(), '</value>') -->

<!-- Step 2: Join them and inject into FetchXML -->
<fetch>
  <entity name="project">
    <attribute name="name" />
    <filter>
      <condition attribute="projectid" operator="in">
        @{join(body('Select_ID_values'), '')}
      </condition>
    </filter>
  </entity>
</fetch>

Handling paging in Power Automate

The List Rows action does not auto-page. Use a Do Until loop: check the response for @odata.nextLink or use the paging cookie from the response headers to fetch the next batch.

Tip: For flows processing large volumes, consider moving paging logic to an Azure Function or plugin. Power Automate's 30-day / 30-second action limits make deep paging expensive.

9. FetchXML in Plugins / C#

Inside a Dataverse plugin or any code using IOrganizationService, pass your FetchXML to RetrieveMultiple via a FetchExpression.

Basic retrieval

string fetchXml = @"
<fetch top='50'>
  <entity name='contact'>
    <attribute name='fullname' />
    <attribute name='emailaddress1' />
    <filter>
      <condition attribute='statecode' operator='eq' value='0' />
    </filter>
  </entity>
</fetch>";

EntityCollection results = service.RetrieveMultiple(new FetchExpression(fetchXml));

foreach (Entity entity in results.Entities)
{
    string name = entity.GetAttributeValue<string>("fullname");
    string email = entity.GetAttributeValue<string>("emailaddress1");
}

Reading aliased join attributes

When you alias an attribute from a joined entity, it comes back in the Entity as an AliasedValue.

// FetchXML has: <attribute name="name" alias="accountname" /> on the link-entity
var aliasedValue = entity.GetAttributeValue<AliasedValue>("accountname");
string accountName = aliasedValue?.Value as string;

Reading aggregate results

// FetchXML aggregate result: alias="contactcount"
var aliasedCount = entity.GetAttributeValue<AliasedValue>("contactcount");
int count = Convert.ToInt32(aliasedCount?.Value);

Building FetchXML dynamically in C#

// Use XElement for safe construction — no string concatenation
var fetch = new XElement("fetch", new XAttribute("top", 100),
    new XElement("entity", new XAttribute("name", "contact"),
        new XElement("attribute", new XAttribute("name", "fullname")),
        new XElement("filter",
            new XElement("condition",
                new XAttribute("attribute", "statecode"),
                new XAttribute("operator", "eq"),
                new XAttribute("value", "0")
            )
        )
    )
);

string fetchXml = fetch.ToString();
var results = service.RetrieveMultiple(new FetchExpression(fetchXml));

10. FetchXML via Web API

You can execute FetchXML directly against the Dataverse Web API by passing it as a URL query parameter. This is useful for integrations, testing from Postman, or server-side code calling the API directly.

Endpoint pattern

GET https://<org>.api.crm.dynamics.com/api/data/v9.2/<entity_plural>?fetchXml=<url-encoded-xml>

URL-encode your FetchXML

<!-- Raw FetchXML -->
<fetch top="10">
  <entity name="contact">
    <attribute name="fullname" />
    <filter>
      <condition attribute="statecode" operator="eq" value="0" />
    </filter>
  </entity>
</fetch>

<!-- URL encoded (key characters) -->
<    →  %3C
>    →  %3E
"    →  %22
/    →  %2F
=    →  %3D

Full example in JavaScript

const fetchXml = `<fetch top="10">
  <entity name="contact">
    <attribute name="fullname" />
    <filter><condition attribute="statecode" operator="eq" value="0" /></filter>
  </entity>
</fetch>`;

const encoded = encodeURIComponent(fetchXml);
const url = `${orgUrl}/api/data/v9.2/contacts?fetchXml=${encoded}`;

const response = await fetch(url, {
  headers: {
    'Authorization': `Bearer ${accessToken}`,
    'OData-MaxVersion': '4.0',
    'OData-Version': '4.0',
    'Accept': 'application/json'
  }
});

const data = await response.json();
console.log(data.value); // array of records

Request formatted values

To get the display label of option sets (formatted values) in the response, add a Prefer header:

Prefer: odata.include-annotations="OData.Community.Display.V1.FormattedValue"

Formatted values then appear in the response as fieldname@OData.Community.Display.V1.FormattedValue.

11. XrmToolBox: FetchXML Builder

FetchXML Builder (by Jonas Rapp) is the fastest way to build, test, and debug FetchXML queries against a live environment. Every serious Dataverse developer should have it installed.

Key features to use

  • Visual query builder — drag-and-drop entities and fields, set filters via dropdowns. Good starting point even if you'll hand-edit the XML.
  • Execute and preview — run the query and see results instantly against your connected environment. No need to deploy a flow or plugin to test.
  • View as SQL — converts your FetchXML to approximate T-SQL. Useful for understanding what's happening under the hood and for writing the equivalent SQL for reporting.
  • Copy as code — exports the query as ready-to-use C#, JavaScript, or Power Automate-compatible string.
  • Aggregate mode toggle — switches the builder into aggregate mode with a checkbox.
  • Paging cookie test — lets you page through results directly in the tool.

Workflow tip

  1. Build the query visually in FetchXML Builder
  2. Switch to XML view and refine edge cases (nested filters, cross-entity conditions)
  3. Execute and validate results against real data
  4. Copy the final XML into your flow, plugin, or API call
Tip: FetchXML Builder also supports the no-lock hint and shows row counts per page. Use it to benchmark query performance before committing to production code.

12. Common Real-World Patterns

Pattern 1: Find records with no related records (NOT EXISTS)

<!-- Accounts with zero contacts -->
<fetch distinct="true">
  <entity name="account">
    <attribute name="name" />
    <attribute name="accountid" />
    <filter>
      <condition entityname="con" attribute="contactid" operator="null" />
    </filter>
    <link-entity name="contact" from="parentcustomerid" to="accountid"
                 link-type="outer" alias="con">
      <attribute name="contactid" />
    </link-entity>
  </entity>
</fetch>

Pattern 2: Get the latest record per group

<!-- Most recent case per customer -->
<fetch aggregate="true">
  <entity name="incident">
    <attribute name="customerid" groupby="true" alias="customerid" />
    <attribute name="createdon" aggregate="max" alias="latestcase" />
  </entity>
</fetch>

Pattern 3: Multi-condition OR across linked entities

<!-- Projects that are complete OR cancelled OR have stages with no tasks -->
<fetch distinct="true" no-lock="true">
  <entity name="project">
    <attribute name="name" />
    <attribute name="statuscode" />
    <filter type="and">
      <condition attribute="retailerid" operator="eq"
        value="abf8e77a-845b-f011-bec1-6045bda966da" />
      <filter type="or">
        <condition attribute="statuscode" operator="eq" value="290560003" />
        <condition attribute="statuscode" operator="eq" value="290560002" />
        <condition entityname="tsk" attribute="taskid" operator="null" />
      </filter>
    </filter>
    <link-entity name="stage" from="projectid" to="projectid"
                 link-type="outer" alias="stg">
      <link-entity name="task" from="stageid" to="stageid"
                   link-type="outer" alias="tsk">
        <attribute name="taskid" />
      </link-entity>
    </link-entity>
  </entity>
</fetch>

Pattern 4: Hierarchy query — tasks for a specific project via stages

<!-- All tasks under a project by traversing Project → Stage → Task -->
<fetch>
  <entity name="task">
    <attribute name="subject" />
    <attribute name="statuscode" />
    <attribute name="ownerid" />
    <link-entity name="stage" from="stageid" to="stageid"
                 link-type="inner" alias="stg">
      <attribute name="name" alias="stagename" />
      <link-entity name="project" from="projectid" to="projectid"
                   link-type="inner" alias="proj">
        <attribute name="name" alias="projectname" />
        <filter>
          <condition attribute="projectid" operator="eq"
            value="3fa85f64-5717-4562-b3fc-2c963f66afa6" />
        </filter>
      </link-entity>
    </link-entity>
    <filter>
      <condition attribute="statecode" operator="eq" value="0" />
    </filter>
  </entity>
</fetch>

Pattern 5: Active records modified in the last N days, owned by current user

<fetch top="200">
  <entity name="opportunity">
    <attribute name="name" />
    <attribute name="estimatedvalue" />
    <attribute name="modifiedon" />
    <filter>
      <condition attribute="statecode" operator="eq" value="0" />
      <condition attribute="ownerid" operator="eq-userid" />
      <condition attribute="modifiedon" operator="last-x-days" value="14" />
    </filter>
    <order attribute="modifiedon" descending="true" />
  </entity>
</fetch>

Pattern 6: Count of records per status with a join condition

<!-- Task count per project, only for active projects -->
<fetch aggregate="true">
  <entity name="task">
    <attribute name="taskid" aggregate="count" alias="taskcount" />
    <link-entity name="stage" from="stageid" to="stageid"
                 link-type="inner" alias="stg">
      <link-entity name="project" from="projectid" to="projectid"
                   link-type="inner" alias="proj">
        <attribute name="projectid" groupby="true" alias="projectid" />
        <attribute name="name" groupby="true" alias="projectname" />
        <filter>
          <condition attribute="statecode" operator="eq" value="0" />
        </filter>
      </link-entity>
    </link-entity>
  </entity>
</fetch>

13. Performance Tips

1. Never use a leading wildcard in LIKE

<!-- BAD: forces a full table scan -->
<condition attribute="name" operator="like" value="%contoso%" />

<!-- GOOD: index-seekable -->
<condition attribute="name" operator="like" value="contoso%" />
<!-- Or use begins-with explicitly -->
<condition attribute="name" operator="begins-with" value="contoso" />

2. Always use no-lock on read-only reporting queries

<fetch no-lock="true">
  <!-- Adds NOLOCK hint. Prevents blocking on busy tables.
       Only use for reporting — not for business-critical transactional reads. -->
</fetch>

3. Select only the columns you need

<!-- BAD: returns all columns -->
<entity name="contact">
  <!-- no attribute elements = SELECT * -->
</entity>

<!-- GOOD: return only what you use -->
<entity name="contact">
  <attribute name="fullname" />
  <attribute name="emailaddress1" />
</entity>

4. Filter as early as possible — push filters to the lowest join level

<!-- Filter on the join entity directly, not at the top -->
<link-entity name="account" from="accountid" to="parentcustomerid"
             link-type="inner" alias="acc">
  <filter>
    <!-- This runs during the join, not after -->
    <condition attribute="statecode" operator="eq" value="0" />
  </filter>
</link-entity>

5. Use top and paging — never retrieve all records speculatively

<!-- Always bound your queries in automation flows -->
<fetch top="5000" no-lock="true">
  <entity name="contact">
    <attribute name="fullname" />
  </entity>
</fetch>

6. Avoid deeply nested joins unless necessary

Each additional join level multiplies the SQL complexity. If you're going 4+ levels deep, consider whether a Dataverse Custom API or pre-computed rollup field could reduce query depth.

7. Use distinct only when you have to

distinct="true" forces a DISTINCT on the SQL side which means sorting the entire result set. Only use it when outer joins actually produce duplicates that matter for your output.

8. Index-backed fields filter faster

Dataverse automatically indexes primary keys, lookup fields, and some system fields like statecode, statuscode, ownerid, createdon, and modifiedon. Filtering on custom text fields without enabling a custom index will always be slower.

14. FetchXML vs OData

CapabilityFetchXMLOData ($filter)
Simple single-entity queries✅✅ (simpler syntax)
Multi-level joins✅❌ (expand limited to 1 level)
Outer joins / NOT EXISTS✅❌
Aggregate functions (sum, count, avg)✅❌
Group by with date parts✅❌
Dynamic date operators (last-x-days, this-week)✅❌
Cross-entity conditions (entityname=)✅❌
Paging with cookies✅✅ (@odata.nextLink)
Readable / writeable by non-developers❌ (verbose XML)✅ (concise URL params)
Works in Power Automate List Rows✅✅
Works in Canvas App formula barLimited✅
Direct URL testing (Postman, browser)⚠️ (URL-encode required)✅ (natural params)
Formatted value annotations✅ (via API header)✅ (via API header)
Tool support (FetchXML Builder)✅ (excellent)❌
NOLOCK hint✅❌

Decision rule

  • Use OData for simple filters on a single table, quick API tests, Canvas App formulas.
  • Use FetchXML for anything involving joins, aggregates, dynamic dates, NOT EXISTS, or paging beyond page 1 of a large dataset.
  • In plugins and C# code, prefer FetchXML — it's more predictable than LINQ and gives you full control over what the database executes.

Quick Reference Cheat Sheet

fetch attributes

AttributePurpose
top="N"Limit result count
distinct="true"Remove duplicate rows
no-lock="true"NOLOCK hint for read queries
aggregate="true"Enable aggregate mode
page="N"Page number
count="N"Page size (max 5000)
paging-cookie="..."Server-side cursor for efficient paging

Comparison operators

OperatorMeaning
eq / neEqual / Not equal
gt / ltGreater than / Less than
ge / leGreater or equal / Less or equal
like / not-likeString pattern match (% wildcard)
begins-withIndex-safe prefix match
in / not-inSet membership (use <value> children)
betweenRange (two <value> children)
null / not-nullIS NULL / IS NOT NULL

Dynamic date operators

OperatorNotes
today / yesterday / tomorrowNo value needed
this-week / this-month / this-yearNo value needed
last-seven-daysNo value needed
last-x-days / next-x-daysvalue="N" required
last-x-months / next-x-monthsvalue="N" required
on / on-or-before / on-or-aftervalue = YYYY-MM-DD

Aggregate functions

FunctionUsage
countRow count including nulls
countcolumnNon-null value count
sumNumeric sum
avgNumeric average
min / maxMin / Max value
groupby="true"Group by this column (no aggregate function)
dategroupingValues: day, week, month, quarter, year

link-entity

AttributeValues / Notes
nameLogical name of the entity to join
fromField on the child entity
toField on the parent entity
link-typeinner (default) or outer
aliasRequired for accessing attributes and cross-entity conditions

Cross-entity condition (NOT EXISTS)

<filter>
  <condition entityname="alias" attribute="pkfield" operator="null" />
</filter>
<link-entity ... link-type="outer" alias="alias">
  <attribute name="pkfield" />
</link-entity>

Skeleton query

<fetch top="500" distinct="false" no-lock="true">
  <entity name="entity_logical_name">
    <attribute name="field1" />
    <attribute name="field2" />
    <order attribute="field1" descending="false" />
    <filter type="and">
      <condition attribute="statecode" operator="eq" value="0" />
    </filter>
    <link-entity name="related_entity" from="fk_field" to="pk_field"
                 link-type="inner" alias="rel">
      <attribute name="name" alias="relatedname" />
    </link-entity>
  </entity>
</fetch>

Friday, April 24, 2026

Power Pages Complete Guide

 

Power Pages Complete Guide

From Basics to Advanced — Web API, Auth, Liquid, Scenarios & Cheat Sheet


Table of Contents

  1. Basic Questions
  2. Security & Access
  3. Data & Forms
  4. Customization & Code
  5. Advanced — Web API
  6. Advanced — Custom Authentication
  7. Advanced — Performance Tuning
  8. Advanced — ALM & CI/CD
  9. Scenario-Based — Troubleshooting
  10. Scenario-Based — Web API Debugging
  11. Scenario-Based — Portal Design
  12. Scenario-Based — Security Scenarios
  13. Liquid Templating — Advanced Patterns
  14. Liquid Templating — Web Templates
  15. Liquid Templating — Performance
  16. Liquid Templating — Gotchas & Traps
  17. Liquid Cheat Sheet

1. Basic Questions

What is Microsoft Power Pages?

Power Pages is a low-code SaaS platform for building secure, data-driven external-facing websites. It is part of the Microsoft Power Platform and connects to Dataverse as its backend data store.


What are the main components of a Power Pages site?

Pages, Web templates, Table lists, Table forms, Web roles, Site settings, Content snippets, and Entity permissions. Together they control layout, data access, and security.


What is Dataverse and why is it important in Power Pages?

Dataverse is the cloud data platform that backs Power Pages. All data rendered on the portal — tables, forms, lists — is stored and retrieved from Dataverse. Role-based security on Dataverse tables controls what portal users can see or edit.


What is the difference between Power Pages and Power Apps portals?

Power Pages is the rebranded and evolved version of Power Apps portals (announced 2022). It adds a dedicated design studio, Pages workspace, Copilot features, and a new standalone licensing model, while retaining all portal functionality.


What tools are used to build Power Pages sites?

Three main tools:

  1. Design Studio — WYSIWYG low-code editor in browser.
  2. Power Pages Management App — advanced configuration in model-driven app.
  3. Power Platform CLI / VS Code extension — code-first development and ALM.

What are Content Snippets?

Content Snippets are reusable text/HTML fragments managed in the portal back-end. They allow non-developers to edit labels, messages, and static text across the site without touching templates. Referenced in Liquid as {% snippets['snippet_name'] %}.


What are Site Settings and give two examples?

Site Settings are key-value configuration pairs that control portal behavior. Examples:

  • Authentication/Registration/Enabled — enables/disables user self-registration.
  • Webapi/<tablename>/enabled — enables the Web API for a specific table.

2. Security & Access

What are Web Roles in Power Pages?

Web Roles group portal users and control what they can access. Every authenticated user is assigned one or more web roles. Two built-in roles exist: Authenticated Users (all logged-in users) and Anonymous Users (not logged in).


What are Table Permissions and why are they critical?

Table Permissions define CRUD access on Dataverse tables for a specific web role. Without proper table permissions, users see no data even if the page is accessible. They support scopes: Global, Contact, Account, Parent, and Self.


What is the difference between Page-level security and Table Permissions?

  • Page-level security controls who can navigate to a page (via web role on the page).
  • Table permissions control what data a user can read/write from Dataverse.

Both layers must be configured for secure, functional data access.


What authentication providers does Power Pages support?

Azure AD (Entra ID), Azure AD B2C, SAML 2.0, OpenID Connect, OAuth 2.0 providers (Google, Facebook, LinkedIn, Twitter), and local identity (email + password). Multiple providers can be enabled simultaneously.


3. Data & Forms

What is a Table List (Entity List)?

A Table List renders rows from a Dataverse table on a page as a grid or gallery. It supports filtering, sorting, searching, and actions like create/edit/delete (subject to table permissions).


What is a Table Form (Basic Form) vs a Multi-step Form (Advanced Form)?

  • Table Form (Basic Form): Single-step form bound to one Dataverse form. Used for simple create/edit/read operations.
  • Multi-step Form (Advanced Form): Wizard-style form spanning multiple steps/tables. Supports conditional branching and sequential data capture.

How does Power Pages handle file attachments in forms?

Files are stored as Notes (annotations) attached to the Dataverse record, or via SharePoint integration. You must enable the attachment option on the form and grant the Notes table permissions to the relevant web role.


4. Customization & Code

What is Liquid in Power Pages?

Liquid is an open-source templating language used in Power Pages web templates and content snippets to dynamically render data, conditional content, and loops. It allows server-side access to Dataverse data without custom code.

Example:

{% entitylist id: page.adx_entitylist.id %}

How can you integrate Power Automate with Power Pages?

Power Automate flows can be triggered from portal forms using the Power Pages connector (cloud flows) or by using the Web API. Common use case: send email notifications when a form is submitted.


What is the Power Pages Web API?

A RESTful API that enables client-side JavaScript to perform CRUD operations on Dataverse tables directly from the portal without a page postback. It respects table permissions. Endpoint pattern: /_api/<tablename>.


How do you deploy or migrate a Power Pages site between environments?

Using Power Platform solutions — package the portal components into a solution and deploy via Solution import, or use the Power Platform CLI commands:

pac paportal download
pac paportal upload

with source control for CI/CD.


How does caching work in Power Pages?

Power Pages caches portal metadata (templates, settings, entity lists) server-side. Changes made in the management app may not reflect immediately. Clear cache via:

<siteurl>/_services/about

or by restarting the portal from the Power Platform admin center.


5. Advanced — Web API

How do you enable the Web API for a specific table?

Create two Site Settings:

  • Webapi/<tablename>/enabled → true
  • Webapi/<tablename>/fields → comma-separated column names (or * for all)

Then grant the appropriate Table Permission (Read/Write/Create/Delete) to the web role. Without both, the API returns 403.


What HTTP methods does the Power Pages Web API support?

  • GET — read records (supports $filter, $select, $orderby, $top, $expand)
  • POST — create a record
  • PATCH — update an existing record
  • DELETE — delete a record

Base URL pattern: /_api/<tablename>(guid)

Note: PUT is not supported.


How is CSRF protection handled in Web API calls?

All write operations (POST, PATCH, DELETE) require an anti-forgery token sent in the request header as __RequestVerificationToken. Retrieve it via:

$('[name=__RequestVerificationToken]').val()
// or from:
/_api/antiforgery/token

Tip: Forgetting the anti-forgery token is the #1 reason Web API writes fail silently in demos.


How do you filter and expand related records using the Web API?

/_api/contacts?$filter=firstname eq 'John'
&$select=fullname,emailaddress1
&$expand=parentcustomerid_account($select=name)
&$top=10

Expanding requires Table Permissions on the related table too.


Can anonymous users call the Power Pages Web API?

Yes, but only if Table Permissions with the required privilege are assigned to the Anonymous Users web role. By default no permissions exist for anonymous users, so all API calls return 403.


What are the limitations of the Power Pages Web API compared to Dataverse Web API?

  • No batch requests ($batch not supported)
  • No executing actions or functions directly
  • No metadata endpoint (/$metadata)
  • Field access restricted to columns listed in the fields site setting
  • Rate limits apply (portal-level throttling)
  • No server-side pagination tokens — use $top and $skip

6. Advanced — Custom Authentication

How do you configure Azure AD B2C as an identity provider?

Register an app in Azure AD B2C, create user flows (sign-up/sign-in). Then set Site Settings:

  • Authentication/OpenIdConnect/AzureADB2C/Authority → B2C tenant URL
  • Authentication/OpenIdConnect/AzureADB2C/ClientId → app client ID
  • Authentication/OpenIdConnect/AzureADB2C/RedirectUri → portal callback URL

Add the redirect URI to the B2C app registration's allowed redirect URIs.


What is contact mapping and why is it important?

When a user authenticates, Power Pages maps the external identity to a Dataverse Contact record. This mapping determines what data the user can access. Without a matching Contact, the user may authenticate but have no portal profile or table-permission scope.


How do you implement invitation-based registration?

Create an Invitation record in Dataverse linked to the Contact, set expiry and type (single/group). Send the invitation link to the user. When they redeem it, a portal identity is created and linked to the Contact.


What is the difference between local identity and external identity providers?

  • Local identity: credentials stored within Power Pages using ASP.NET Identity. Supports email confirmation, password reset, and lockout.
  • External providers (Azure AD, B2C, Google, etc.): authentication is delegated via OAuth/OIDC. Power Pages only receives a token and maps it to a Contact — it never stores passwords.

How do you implement MFA on Power Pages?

Power Pages itself does not provide MFA — delegate auth to an external provider that supports MFA (Azure AD Conditional Access or Azure AD B2C MFA user flows). The portal trusts the token issued after MFA is satisfied.

Tip: The correct answer is always — push MFA to the identity provider, never try to build it inside the portal.


7. Advanced — Performance Tuning

What causes slow portal page loads and how do you diagnose them?

Common causes: excessive Liquid Dataverse queries, large unbounded table lists, unoptimised fetchXML, heavy JavaScript bundles, cache misses.

Diagnose using:

  • Browser DevTools Network tab
  • /_services/about — check cache state
  • Azure Application Insights (if configured)
  • Power Pages telemetry in the admin centre

How does server-side caching work and how do you control it?

Power Pages caches portal metadata in memory. To clear:

  • Navigate to <site>/_services/about → click Clear cache
  • Restart the portal from Power Platform admin centre

For live data, use the Web API client-side instead of server-side Liquid queries.


How do you optimise a slow Table List?

  • Enable pagination — set a sensible page size (25–50)
  • Use $select to fetch only required columns
  • Add filters so the Dataverse query is targeted
  • Add Dataverse indexes on columns used in filter/sort
  • Avoid expanding many lookups in a single list view
  • Consider replacing with a client-side Web API call + JS rendering

How do you implement CDN for Power Pages assets?

Power Pages has a built-in Azure CDN integration. Enable it in the Power Platform admin centre under portal settings. Once enabled, static assets (CSS, JS, images in web files) are served from the CDN edge. Custom domain + SSL is required before CDN can be enabled.


8. Advanced — ALM & CI/CD

How do you use Power Platform CLI to manage Power Pages in source control?

# Download site content
pac paportal download --path ./portal --webSiteId <guid>

# Upload to target environment
pac paportal upload --path ./portal

# Auth with service principal
pac auth create

How do you handle environment-specific configuration during deployment?

Use deployment settings files (deploymentSettings.json) with the Power Platform Build Tools or CLI. These files override Site Setting values per environment (dev/test/prod) at import time — keeping secrets and environment URLs out of source control.


How do you automate Power Pages deployment in Azure DevOps?

  1. Power Platform Tool Installer
  2. Power Platform Export Solution (from source env)
  3. Commit to repo
  4. Power Platform Import Solution (to target env)
  5. pac paportal upload step via CLI task for portal content files

Use a service principal with System Administrator role on the target environment.


9. Scenario-Based — Troubleshooting

Scenario: User logs in but sees no data in the Table List. No error shown.

Diagnose in order:

  1. Confirm the user's web role via the Contact record in Portal Management App.
  2. Check Table Permissions for that web role — verify Read privilege is granted.
  3. Check the scope. If scope is Contact or Account, the parent relationship record must exist and be linked correctly.
  4. Clear the portal cache at /_services/about.
  5. Check if the Table List has a filter that excludes records for this user.

Root cause 90% of the time: Missing Table Permission or wrong scope.


Scenario: Form submission silently fails — page reloads, no record created.

  1. Open DevTools → Network tab → re-submit. Look for a non-200 POST response.
  2. Check Table Permissions — web role must have Create privilege.
  3. Check if required Dataverse fields are missing from the portal form.
  4. Verify form mode is set to Insert, not Edit or ReadOnly.
  5. Check console for JS errors blocking submission.
  6. Check for Dataverse business rules blocking create.

Tip: Add ?debug to the URL to surface additional error detail.


Scenario: After deploying a solution, portal still shows old content.

This is a portal metadata cache issue. Fix:

  1. Navigate to <portalurl>/_services/about
  2. Click Clear cache
  3. If unresponsive, restart from Power Platform Admin Centre → Environments → Resources → Portals → Restart
  4. For CI/CD, add a cache-clear step post-deployment.

Scenario: User can edit records they should not be able to.

  1. Check if the user has a second web role with Write/Edit permission.
  2. Check Table Permissions on Authenticated Users built-in role — if Write is there, every logged-in user inherits it.
  3. Confirm scope — Global scope incorrectly set allows editing all records.

Warning: Never rely solely on hiding the Edit button. Always enforce at the Table Permission level — UI controls are bypassable via direct URL.


10. Scenario-Based — Web API Debugging

Scenario: Web API POST returns 403 Forbidden.

  1. Confirm Site Setting Webapi/<tablename>/enabled is true (exact logical name, case-sensitive).
  2. Confirm Webapi/<tablename>/fields lists the columns being written, or is *.
  3. Confirm the user's web role has a Table Permission with Create privilege.
  4. Check request headers — POST/PATCH/DELETE require __RequestVerificationToken. Missing token = 403.
  5. Clear portal cache.
  6. Test with Global-scope permission temporarily to isolate scope vs. permission issues.

Key distinction: 403 on GET = missing Read permission. 403 on POST = missing Create permission OR missing anti-forgery token.


Scenario: Web API GET returns empty array but records exist in Dataverse.

Empty array (not 403) means the API is enabled and Read permission exists — but scope is filtering records out.

  1. Check Table Permission scope. Contact scope only returns records linked to the logged-in Contact.
  2. Verify the relationship column is populated on the records.
  3. Try Global scope temporarily in dev to confirm.

Scenario: PATCH request succeeds but one field is always ignored.

  1. Check Webapi/<tablename>/fields — if it's a list (not *), confirm the field is included.
  2. Check Dataverse Field Security Profiles — update silently dropped if field-level security restricts it.
  3. Check for Dataverse business rules or plugins resetting the field.
  4. Verify you're sending the correct logical field name (lowercase, publisher prefix).

Scenario: Works in dev, returns 403 in production.

  1. Compare Site Settings between environments — enabled and fields settings may not have been deployed to prod.
  2. Compare Table Permissions — if not in the solution, they need to be recreated in prod.
  3. Check web roles — the Contact record in prod may not have the same web role assigned.
  4. Clear cache in prod.

Root cause: Environment parity issues. Always include Table Permissions and Site Settings in your solution or deployment checklist.


11. Scenario-Based — Portal Design

Design: Multi-role portal — customers see own cases, partners see account cases, admins see all.

Create three web roles with Table Permissions on the Case table:

Role Scope Privilege
Customer Contact (customerid) Read
Partner Account (customerid) Read
Admin Global Full CRUD

Use a single Table List on one page — the data returned automatically filters by scope. No code needed for the filtering logic.

Key insight: One page + one table list + three scopes = three different views automatically.


Design: Multi-step onboarding form spanning three tables.

Use a Multi-step Form (Advanced Form):

  1. Step 1: Account table, mode = Insert
  2. Step 2: Contact table, mode = Insert, auto-populate Account lookup from step 1
  3. Step 3: Custom subscription table, mode = Insert, pre-populate Account lookup via Referenced Entity
  4. Grant Table Permission Create on all three tables for the relevant web role.

Design: Real-time data dashboard (records reflect within seconds without page reload).

Server-side Liquid/Table Lists cannot do real-time — they render at page load only.

Use the Power Pages Web API client-side:

setInterval(async () => {
  const res = await fetch('/_api/cr123_orders?$filter=...');
  const data = await res.json();
  // update DOM with data.value
}, 5000);

Tip: Polling every 5–10 seconds handles most "real-time" business requirements without additional infrastructure.


Design: Anonymous lead capture form — no login, no data visible.

  1. Basic Table Form on Lead table, mode = Insert, no authentication required.
  2. Grant Anonymous Users web role a Table Permission with only Create privilege — no Read, Write, or Delete.
  3. No Table List on any anonymous page.
  4. Add CAPTCHA via custom Liquid/JS integration (Google reCAPTCHA).
  5. Set Authentication/Registration/Enabled to false if no self-registration needed.

12. Scenario-Based — Security Scenarios

Scenario: Pen test finds users can access other users' records by manipulating the GUID in the URL.

Fix: Change Table Permission scope from Global to Contact.

With Contact scope, fetching a record not linked to the user's Contact returns 403 — even with the correct GUID.

Warning: Global Read scope is the single most common security misconfiguration in Power Pages portals. Default to Contact or Account scope unless Global is explicitly required.


Scenario: Prevent portal from being used as open relay to spam Dataverse.

  1. Ensure only authenticated users have Create permission.
  2. Add CAPTCHA on public forms.
  3. Use Power Automate to detect unusual create volume.
  4. Dataverse API limits apply — 6000 requests per 5 minutes per user.
  5. Route public form submissions through a Power Automate HTTP trigger for extra validation.

Scenario: Company A must never see Company B data (multi-tenant portal).

  1. Ensure every Contact is linked to the correct parent Account.
  2. Ensure all data records have a lookup to the Account.
  3. Set all Table Permissions to Account scope.
  4. Use Parent scope for child records (e.g., Order Lines linked to Orders).

Tip: Account scope is the correct architecture for B2B multi-tenant portals. Contact scope works for B2C (individual consumer) portals.


Scenario: Sensitive columns (salary, SSN) must never be exposed via the Web API.

  1. In Site Setting Webapi/<tablename>/fields, explicitly list only safe columns — never use * on sensitive tables.
  2. Apply Dataverse Field Security Profiles to sensitive columns as a second layer.
  3. Only add permitted fields to the Dataverse form used by the portal.

Warning: Using Webapi/table/fields = * on a table with sensitive data is a critical misconfiguration. Always use an explicit allowlist.


13. Liquid Templating — Advanced Patterns

What is the difference between {% assign %} and {% capture %}?

  • assign stores a simple value or object reference.
  • capture renders a block of Liquid/HTML into a string variable.
{% assign username = user.fullname %}

{% capture welcome_msg %}
  <p>Welcome back, {{ user.fullname }}!</p>
{% endcapture %}
{{ welcome_msg }}

How do you query Dataverse records using fetchxml in Liquid?

{% fetchxml my_cases %}
<fetch top="10">
  <entity name="incident">
    <attribute name="title"/>
    <attribute name="statecode"/>
    <filter>
      <condition attribute="customerid"
        operator="eq" value="{{ user.id }}"/>
    </filter>
  </entity>
</fetch>
{% endfetchxml %}

{% for case in my_cases.results.entities %}
  <p>{{ case.title }} — {{ case.statecode.label }}</p>
{% endfor %}

How do you access the currently logged-in user's details?

{% if user %}
  Hello, {{ user.fullname }}
  Contact ID: {{ user.id }}
  Email: {{ user.emailaddress1 }}
  Account: {{ user.parentcustomerid.name }}
{% else %}
  <a href="/signin">Please sign in</a>
{% endif %}

Tip: user.roles returns the collection of web roles. Use user.roles | where: 'name', 'Admin' | first to check for a specific role.


How do you conditionally show content based on web role?

{% assign is_partner = user.roles
    | where: 'name', 'Partner'
    | first %}

{% if is_partner %}
  <a href="/partner-dashboard">Partner portal</a>
{% endif %}

Warning: This controls UI rendering only — it does not replace Table Permissions.


How do you read URL query string parameters in Liquid?

{% comment %} URL: /orders?status=active&page=2 {% endcomment %}

{{ request.params['status'] }}   → active
{{ request.params['page'] }}     → 2

Security Note: Never use raw query string values directly in fetchxml conditions without validation.


14. Liquid Templating — Web Templates

What is a Web Template and how does it differ from a Page Template?

  • Web Template: contains the actual Liquid + HTML markup (the code layer).
  • Page Template: configuration record referencing a Web Template, defining how it is used.

Chain: Web Page → Page Template → Web Template


How do you create a reusable component across multiple pages?

{%- comment -%} Web Template: "case-card" {%- endcomment -%}
<div class="card">
  <h3>{{ case.title }}</h3>
  <p>{{ case.statecode.label }}</p>
</div>

{%- comment -%} Parent Template {%- endcomment -%}
{% for case in my_cases.results.entities %}
  {% include 'case-card' %}
{% endfor %}

How do you pass parameters into an included Web Template?

{% include 'alert-banner'
    message: 'Your submission was received.'
    type: 'success' %}

{%- comment -%} Web Template: "alert-banner" {%- endcomment -%}
<div class="alert alert-{{ type }}">
  {{ message }}
</div>

What is the block and extends pattern in Web Templates?

{%- comment -%} Base layout Web Template {%- endcomment -%}
<html>
  <body>
    <header>{% block header %}Default header{% endblock %}</header>
    <main>{% block content %}{% endblock %}</main>
    <footer>{% block footer %}Default footer{% endblock %}</footer>
  </body>
</html>

{%- comment -%} Child Web Template {%- endcomment -%}
{% extends 'base-layout' %}
{% block content %}
  <h1>My Page Content</h1>
{% endblock %}

15. Liquid Templating — Performance

Why is putting multiple fetchxml blocks on one page a performance problem?

Each {% fetchxml %} is a synchronous round-trip to Dataverse during server-side rendering. Five fetchxml blocks = five blocking Dataverse calls before the user sees anything.

Fixes:

  • Merge related queries using link-entity fetchxml.
  • Move non-critical data fetches client-side using the Web API.
  • Cache expensive results in a Content Snippet updated by a flow.
  • Always use top in fetchxml — never fetch unbounded result sets.

Target: 1–2 server-side queries max per page.


What is the N+1 fetchxml anti-pattern?

{%- comment -%} NEVER do this {%- endcomment -%}
{% for order in orders.results.entities %}
  {% fetchxml lines %}
    <fetch><entity name="salesorderdetail">
      <filter><condition attribute="salesorderid"
        operator="eq" value="{{ order.id }}"/>
      </filter>
    </entity></fetch>
  {% endfetchxml %}
{% endfor %}

Fix: Use <link-entity> in a single fetchxml query.


How do you use link-entity in fetchxml to avoid multiple queries?

{% fetchxml orders_with_account %}
<fetch top="20">
  <entity name="salesorder">
    <attribute name="name"/>
    <attribute name="totalamount"/>
    <link-entity name="account"
      from="accountid" to="customerid"
      alias="acct">
      <attribute name="name"/>
    </link-entity>
  </entity>
</fetch>
{% endfetchxml %}

{% for o in orders_with_account.results.entities %}
  {{ o.name }} — {{ o['acct.name'] }}
{% endfor %}

16. Liquid Templating — Gotchas & Traps

Why does {{ value | default: 'N/A' }} sometimes still output blank?

The default filter only triggers when the value is nil, false, or "". If the Dataverse field returns an empty object (e.g., a lookup), default does not fire.

{% comment %} Safe pattern for lookups {% endcomment %}
{% if entity.parentcustomerid %}
  {{ entity.parentcustomerid.name }}
{% else %}
  N/A
{% endif %}

Why does modifying a variable inside a {% for %} loop not persist after the loop ends?

Liquid has block scoping — variables assigned inside a for loop do not leak out to the parent scope.

{% assign total = 0 %}
{% for item in items %}
  {% assign total = total | plus: item.amount %}
{% endfor %}
{{ total }}  ← always outputs 0!

Fix: Use fetchxml aggregate functions or calculate client-side with JavaScript.


How do you output a literal {{ or {% without Liquid interpreting it?

{% raw %}
  Vue template: {{ message }}
  Angular binding: {{ user.name }}
  Handlebars: {{#each items}}
{% endraw %}

Essential when embedding JavaScript frameworks (Vue, Angular, Handlebars) inside a Web Template.


Why does {% include 'my-template' %} silently render nothing?

Three common causes:

  1. The Web Template name is incorrect — names are case-sensitive.
  2. The included template has a Liquid error — Liquid silently swallows errors in includes.
  3. The included template references variables not in scope at the point of inclusion.

Liquid fetchxml returns empty but XrmToolBox shows records. Why?

The portal executes fetchxml in the context of the portal application user — not as an admin.

  1. Table Permissions: the web role lacks Read permission on the table.
  2. Record ownership: with Contact scope, no records are linked to the current Contact.
  3. Business Unit security: the portal application user's Dataverse role may not have org-level read.

Warning: Always test fetchxml in the browser as a portal user, not as an admin in XrmToolBox.


17. Liquid Cheat Sheet

Global Objects

Object Description Key Properties
user Logged-in Contact record. null for anonymous. .fullname, .id, .emailaddress1, .parentcustomerid.name, .roles
request Current HTTP request .url, .path, .params['key']
page Current web page record .title, .url, .parent.title
website Portal website record .name, .id
sitemarkers Named page pointers sitemarkers['Name'].url
settings Site Settings values settings['Key/Name']
snippets Content Snippets snippets['Snippet/Name']
weblinks Web link sets (nav menus) weblinks['Set Name'].weblinks

Essential Tags

Tag Purpose
{% fetchxml result %}...{% endfetchxml %} Query Dataverse. Results in result.results.entities
{% include 'template-name' key: val %} Include another Web Template with optional params
{% extends 'layout' %} Inherit from a base layout template
{% block name %}...{% endblock %} Define/override a named block region
{% assign var = value %} Store a value in a variable
{% capture var %}...{% endcapture %} Render Liquid block into a string variable
{% raw %}...{% endraw %} Output {{ }} literally — for Vue/Angular/Handlebars
{% unless condition %} Render when condition is false
{% for item in collection %} Loop over a collection
{% if / elsif / else / endif %} Conditional rendering

Essential Filters

Filter Example Output
date {{ date | date: "%d %b %Y" }} 18 Apr 2025
where user.roles | where: 'name', 'Admin' Filtered array
first / last collection | first First/last item
map roles | map: 'name' Array of names
join arr | join: ', ' A, B, C
size entities | size Count
truncate text | truncate: 80 Shortened string
default value | default: 'N/A' Fallback (strings/nil only)
downcase / upcase email | downcase Normalised case
replace str | replace: 'a','b' Substituted string
plus / minus / times / divided_by 10 | plus: 5 Arithmetic result

Critical Patterns to Memorise

{% comment %} Role check {% endcomment %}
{% assign is_admin = user.roles | where: 'name', 'Admin' | first %}
{% if is_admin %}...{% endif %}

{% comment %} Null-safe lookup {% endcomment %}
{% if entity.parentcustomerid %}
  {{ entity.parentcustomerid.name }}
{% endif %}

{% comment %} Whitelist URL params {% endcomment %}
{% assign allowed = 'active,inactive' | split: ',' %}
{% assign status = request.params['status'] %}
{% if allowed contains status %}
  use {{ status }} safely
{% endif %}

{% comment %} link-entity JOIN (avoid N+1) {% endcomment %}
<link-entity name="account" from="accountid"
  to="customerid" alias="acct">
  <attribute name="name"/>
</link-entity>
{{ entity['acct.name'] }}

Top 3 Traps

  1. Loop scope — {% assign %} inside {% for %} does NOT persist after the loop.
  2. default filter — fails silently on empty lookup objects. Use {% if %} guards instead.
  3. fetchxml inside a loop — causes N+1 Dataverse queries. Always use link-entity for related data.


Featured Post

Provisioning an SMTP AUTH Service Account for On-Prem Apps (Hybrid Exchange + PowerShell 7)

Provisioning an SMTP AUTH Service Account for On-Prem Apps (Hybrid Exchange + PowerShell 7) Complete Script (PowerShell 7 compatible) <# ...

Popular posts