A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.
Canvas App YAML — Power Fx Formulas, Events and Data
Formula patterns for state, events, reusable logic, and mock data.
Contents
- State management
- Conditional logic
- String operations
- Table operations
- Date and time formatting
- Event handling
- Named formulas and user defined functions
- Mock data collections
- Formula rules of thumb
- Troubleshooting
State management
# Initialize variables on screen load
OnVisible: |-
=Set(variable1, "initial value");
Set(variable2, 0);
Set(variable3, false)
# Update state on interaction
OnSelect: |-
=Set(counter, counter + 1);
Set(status, "updated")
Set() creates app-wide variables; UpdateContext() creates screen-scoped ones. A value
that resets on navigation was created with UpdateContext; a value that unexpectedly
persists across screens was created with Set.
Conditional logic
# Simple conditional
Text: =If(isActive, "Active", "Inactive")
# Nested conditionals
Text: =If(status = "complete",
"Done!",
If(status = "pending",
"In Progress",
"Not Started"))
# Boolean expressions
Visible: =isEnabled && !isHidden
DisplayMode: =If(gameOver || alreadyPlayed, DisplayMode.Disabled, DisplayMode.Edit)
String operations
# Concatenation
Text: =firstName & " " & lastName
# Not equal (empty string)
Visible: =searchText <> ""
# Equal (case-sensitive)
Visible: =selectedOption = "Option1"
Any value containing : must be quoted at the YAML level — see
${PLUGIN_ROOT}/references/YamlSyntax.md.
Table operations
& concatenates text; it does not combine tables. To prepend or append a record
to an existing table, pass the record and table to Table() in the desired order:
Table({FieldName: "Value"}, ExistingTable)
Table(ExistingTable, {FieldName: "Value"})
The added record must use the table's expected column names and types. Table()
returns a table; it does not modify the existing table or collection.
Date and time formatting
Format specifiers are lower case (mm for month, not MM):
# "dddd, mmmm d, yyyy" -> "Monday, January 1, 2024"
Text: =Text(varDate, "dddd, mmmm d, yyyy")
# "hh:mm:ss" -> "14:30:00"
Text: =Text(Now(), "hh:mm:ss")
Sort by time semantics, not display text
Do not sort user-facing time strings directly. Lexicographic ordering puts values such as
"2:00 PM" before "9:00 AM" and allows padded, non-padded, 12-hour, 24-hour, and blank
values to mix silently.
Prefer a typed Date/Time column and sort that field directly. When a local/mock source must
store text, validate the same input that is written and persist a separate zero-padded
24-hour sort key. One direct form uses an outer blank guard and an IfError whose successful
expression writes Text(TimeValue(the same input), "HH:mm") to the declared source field.
When using staged variables or other control flow, trace the same live input through
validation, normalization, the field write and the sort binding; unrelated parsing tokens
are not evidence of correct ordering.
OnSelect: |-
=If(
IsBlank(Trim(txtStart.Text)),
Notify("Time is required"),
IfError(
Patch(
colMeetings,
First(colMeetings),
{StartSortKey: Text(TimeValue(Trim(txtStart.Text)), "HH:mm")}
),
Notify("Enter a valid time")
)
)
Items: =SortByColumns(colMeetings, "StartSortKey", SortOrder.Ascending)
Keep the original display value separate when the requested presentation is 12-hour time. The plan must name accepted input forms and the visible invalid/blank behavior. Do not claim free-form time input is valid merely because one seed format sorts correctly.
Event handling
Platform confirmation with Confirm
Confirm(message [, options]) displays a platform-provided confirmation dialog from a behavior formula such as OnSelect. It returns true when the user confirms and false when the user cancels. The message is required. The options record and each of its text fields (Title, Subtitle, ConfirmButton, CancelButton) are optional:
Confirm("Remove this item?")
Confirm(
"Remove this item?",
{
Title: "Remove confirmation",
Subtitle: "This action can't be undone.",
ConfirmButton: "Remove",
CancelButton: "Cancel"
}
)
Use the result as the condition of If: put the mutation only in the affirmative branch, and leave canonical data unchanged on cancellation. Capture the target's stable identity before prompting so the confirmed action uses the same target named in the dialog. Confirmation is consent to attempt the operation, not evidence that the mutation succeeded.
This is a Power Fx capability, not a control to discover with describe_control. It does not require a custom modal container, overlay stacking, or app-authored focus-trap state. Consult this section before declaring confirmation infeasible from control descriptions alone. Do not infer target-player support, keyboard dismissal, focus trapping, or focus return from a clean compile; keep unobserved runtime behavior explicitly unverified.
Guard clauses
OnSelect: |-
=If(gameOver || pos1 <> "",
false, # Do nothing if condition met
Set(pos1, currentPlayer); # Otherwise execute logic
UpdateGameState()
)
Sequential operations
OnSelect: |-
=Set(pos1, currentPlayer);
Set(gameOver, CheckWinCondition());
Set(currentPlayer, If(currentPlayer = "X", "O", "X"))
Close every data mutation loop
An action that changes data must say so, and must leave the form in a clean state. Two defects show up constantly in generated apps: a quantity silently changes with no acknowledgement, and a validation message stays on screen after the record it complained about was successfully saved.
OnSelect: |-
=With(
{
targetId: ThisItem.ID,
nextQuantity: ThisItem.Quantity - varAdjustBy
},
Set(
varLastInventoryMutation,
Patch(
colInventory,
LookUp(colInventory, ID = targetId),
{Quantity: nextQuantity}
)
);
Set(varInventoryReceiptVisible, true);
Set(varAdjustBy, 0)
)
Capture the returned record, changed stable ID, or deletion snapshot before resetting inputs or navigating. Bind an in-screen receipt to that captured value.
Use
Notify(...)only as supplemental feedback. It does not prove persistence or the resulting values.Reset inputs only after the successful source operation and captured receipt state.
Read the target record from the source by immutable ID. Do not patch by display name and do not inspect a stale
ThisItemafter mutation.Derive validation text and submit availability directly from the current input values:
# Validation message Visible: =IsBlank(Trim(NameInput.Value)) # Submit action DisplayMode: =If(IsBlank(Trim(NameInput.Value)), DisplayMode.Disabled, DisplayMode.Edit)When validation must wait until the first submit attempt, combine one attempt flag with the current invalid expression:
Visible: =varSubmitAttempted && IsBlank(...). Do not maintain separate validity flags or clear them from every input'sOnChange; correcting the input must make the formula false declaratively.
Canonical local-collection mutation patterns
Create and capture the record before resetting inputs:
OnSelect: |-
=If(
!IsBlank(Trim(txtName.Value)),
Set(
varLastRecord,
Patch(
colRecords,
Defaults(colRecords),
{
ID: GUID(),
Name: Trim(txtName.Value),
Category: varSelectedCategory,
Status: "Pending"
}
)
);
Set(varLastAction, "Created");
Set(varReceiptVisible, true);
Reset(txtName)
)
Edit the selected stable ID and preserve fields not present in the change record:
OnSelect: |-
=Set(
varLastRecord,
Patch(
colRecords,
LookUp(colRecords, ID = varEditRecordId),
{
Name: Trim(txtName.Value),
Category: varSelectedCategory
}
)
);
Set(varLastAction, "Updated");
Set(varReceiptVisible, true);
Set(varEditMode, false)
Apply an eligible status transition and capture the resulting record:
OnSelect: |-
=With(
{targetId: ThisItem.ID},
If(
LookUp(colRecords, ID = targetId).Status = "Pending",
Set(
varLastRecord,
Patch(
colRecords,
LookUp(colRecords, ID = targetId),
{Status: "Approved"}
)
);
Set(varLastAction, "Approved");
Set(varReceiptVisible, true)
)
)
Capture a deletion snapshot before removing the source row:
OnSelect: |-
=With(
{targetId: ThisItem.ID},
Set(varDeletedRecord, LookUp(colRecords, ID = targetId));
RemoveIf(colRecords, ID = targetId);
Set(varLastAction, "Deleted");
Set(varDeleteReceiptVisible, true)
)
The receipt renders the captured identity, action, and proof-set values. The list, badge, filter, metric, or leaderboard separately reads colRecords, so the immediate proof and downstream state agree.
Selector and filter bindings
Treat a selector as four coupled formulas: option source, visible option text, committed selected value, and consumer predicate. Use the exact selected-value property returned by describe_control; do not guess it.
For six or fewer static choices, prefer visible choice buttons or radio controls. They avoid an inaccessible or uncommitted dropdown state and make the active filter visible. A category filter can set varCategoryFilter directly, while the gallery reads:
Items: |-
=Filter(
colRecords,
varCategoryFilter = "All" || Category = varCategoryFilter
)
The clear action restores "All". Seed or create at least two matching records and one non-matching record so the planned Given/When/Then scenario can prove inclusion, exclusion, and reset.
Toggle once, report the same next value
Do not mutate a record and then inspect that same ThisItem to infer what happened.
Compute the next value once and use it for both the write and the confirmation:
OnSelect: |-
=With(
{
member: ThisItem,
nextCheckedIn: !ThisItem.CheckedIn
},
Patch(colMembers, member, {CheckedIn: nextCheckedIn});
Notify(
member.Name & If(nextCheckedIn, " checked in", " marked not ready"),
NotificationType.Success
)
)
Named formulas and user defined functions
Define reusable logic in App.Formulas — constants, complex calculations, and anything
shared across controls or screens.
App:
Properties:
Formulas: |-
=// Named constants
MaxItems = 100;
ColorPrimary = RGBA(52, 120, 246, 1);
// Functions with parameters
GetStatusColor(status: Text): Color =
If(
status = "complete", Color.Green,
status = "pending", Color.Yellow,
Color.Gray
);
TogglePlayer(current: Text): Text =
If(current = "X", "O", "X");
Mock data collections
When an app references external data that is not yet connected, populate collections with
ClearCollect in App.OnStart.
For a small, read-only table used by only one control, keep it local instead:
Items: |-
=[
{Title: "Draft"},
{Title: "Review"},
{Title: "Publish"}
]
Use an App.OnStart collection when several screens share the records or interactions
add, edit or remove rows. Never ClearCollect fixed display data in a screen's
OnVisible; that couples rendering to navigation and reruns the seed every visit.
When a collection must exist with a known record type but start empty, create one typed record and clear it immediately:
OnStart: |-
=ClearCollect(
colTasks,
{
ID: GUID(),
Title: "",
Hours: 0
}
);
Clear(colTasks)
Use this recipe only when downstream formulas require an empty collection with stable
field types before any real record is created or loaded. ClearCollect(colTasks, {})
does not establish the intended field schema, while ClearCollect establishes concrete
GUID, Text, and Number fields and Clear(colTasks) then leaves the typed
collection empty.
Keep mock data compact. App.OnStart runs before the first screen paints and its
entire text is serialized into the saved app, so oversized seed data slows startup and
bloats the document.
- ✅ 5–8 rows per collection — enough to make galleries, filters, and empty states look real
- ✅ Descriptions of one short sentence (roughly 60–100 characters)
- ❌ Paragraph-length prose per row
- ❌ Dozens of rows to "look full" — a gallery reads the same with 6 rows
If a screen needs more variety, vary the field values, not the row count.
The collection schemas defined here resolve app-wide, so a single wrong field name in
App.pa.yaml fails every screen that binds to it. Compile App.pa.yaml on its own before
any screen is written.
Formula rules of thumb
- ✅ Initialize screen interaction state in
OnVisibleand app-wide state inApp.OnStart - ✅ Derive responsive layout directly from current width
- ✅ Use descriptive variable names
- ✅ Keep state updates sequential with semicolons
- ✅ Use guard clauses to prevent invalid operations
- ✅ Keep formulas readable with proper indentation
- ❌ Don't create deeply nested
Ifstatements - ❌ Don't store breakpoints, column counts or page widths in variables
- ❌ Never call
NavigatefromApp.OnStartor the start screen'sOnVisible
Troubleshooting
Formula doesn't update the UI: the value is not stored in a variable — use
Set().A variable resets when you navigate: it was created with
UpdateContextwhere you neededSet. A value that unexpectedly persists is the reverse.Dozens of unrelated
Name isn't validor'.' operator cannot be used on Error valueserrors: almost always cascading from anApp.pa.yamlfailure. FixAppfirst, then re-compile.Navigate is not permitted in OnStart: setApp.StartScreeninstead.No type found for variable 'x'. Ensure that it is Set to a non-Blank value somewhere in the app.: you wroteSet(x, Blank())— or seeded a mock collection column withBlank()and nothing else. Power Fx infers a variable's type from the values assigned to it, andBlank()carries no type. An empty string ("") is a typed Text value and does not cause this error. Seed the variable with a typed literal, or set it from real data after the collection exists:// WRONG — no type to infer Set(varSelectedTask, Blank()); // RIGHT — the record type comes from the collection ClearCollect(colTasks, {Id: 1, Title: "Draft agenda", Hours: 2}); Set(varSelectedTask, First(colTasks));When the variable genuinely starts empty, still type it first and clear it after:
Set(varSelectedTask, First(colTasks)); Set(varSelectedTask, Blank());