Professional Documents
Culture Documents
Power Fx is the low-code language that will be used across Microsoft Power Platform.
It's a general-purpose, strong-typed, declarative, and functional programming language.
Power Fx is expressed in human-friendly text. It's a low-code language that makers can
work with directly in an Excel-like formula bar or Visual Studio Code text window. The
"low" in low-code is due to the concise and simple nature of the language, making
common programming tasks easy for both makers and developers. It enables the full
spectrum of development from no-code for those who have never programmed before
to "pro-code" for the seasoned professional, with no learning or rewriting cliffs in
between, enabling diverse teams to collaborate and save time and expense.
7 Note
Microsoft Power Fx is the new name for the formula language for canvas apps
in Power Apps. This overview and associated articles are a work in progress as
we extract the language from canvas apps, integrate it with other Microsoft
Power Platform products, and make it available as open source. To learn more
about and experience the language today, start with Get started with
formulas in canvas apps in the Power Apps documentation and sign up for a
free Power Apps trial .
In this article, we refer to makers when we describe a feature that might be
used at either end of the programming skill spectrum. We refer to the user as
a developer if the feature is more advanced and is likely beyond the scope of a
typical Excel user.
Also, Power Fx offers imperative logic when needed. Worksheets don't typically have
buttons that can submit changes to a database, but apps often do. The same expression
language is used for both declarative and imperative logic.
Power Fx will be made available as open-source software. It's currently integrated into
canvas apps, and we're in the process of extracting it from Power Apps for use in other
Microsoft Power Platform products and as open source. More information: Microsoft
Power Fx on GitHub
This article is an overview of the language and its design principles. To learn more about
Power Fx, see the following articles:
Data types
Operators and identifiers
Tables
Variables
Imperative logic
Global support
Expression grammar
YAML formula grammar
Think spreadsheet
What if you could build an app as easily as you build a worksheet in Excel?
These were the questions that inspired the creation of Power Apps and Power Fx.
Hundreds of millions of people create worksheets with Excel every day; let's bring them
app creation that's easy and uses Excel concepts that they already know. By breaking
Power Fx out of Power Apps, we're going to answer these questions for building
automation, or a virtual agent, or other domains.
All programming languages, including Power Fx, have expressions: a way to represent a
calculation over numbers, strings, or other data types. For example, mass *
acceleration in most languages expresses multiplication of mass and acceleration . The
Power Fx takes this a step further. An expression by itself says nothing about what it's
calculating. It's up to the maker to place it in a variable or pass it to a function. In Power
Fx, instead of only writing an expression that has no specific meaning, you write a
formula that binds the expression to an identifier. You write force = mass *
acceleration as a formula for calculating force . As mass or acceleration changes,
For example, this formula from Stack Overflow searches a string in reverse order. In
Excel, it looks like the following image.
Power Fx works with this same formula, with the cell references replaced with control
property references:
As the Input control value is changed, the Label control automatically recalculates the
formula and shows the new value. There are no OnChange event handlers here, as would
be common in other languages.
Another example that uses a formula for the Fill color of the screen. As the sliders that
control Red, Green, and Blue are changed, the background color automatically changes
as it's being recalculated.
There are no OnChange events for the slider controls, as would be common in other
languages. There's no way to explicitly set the Fill property value at all. If the color
isn't working as expected, you need to look at this one formula to understand why it
isn't working. You don't need to search through the app to find a piece of code that sets
the property at an unexpected time; there is no time element. The correct formula
values are always maintained.
As the sliders are set to a dark color, the labels for Red, Green, and Blue change to white
to compensate. This is done through a simple formula on the Color property for each
label control.
What's great about this is that it's isolated from what's happening for the Fill color:
these are two entirely different calculations. Instead of large monolithic procedures,
Power Fx logic is typically made up of lots of smaller formulas that are independent. This
makes them easier to understand and enables enhancements without disturbing
existing logic.
Power Fx is a declarative language, just as Excel is. The maker defines what behavior
they want, but it's up to the system to determine and optimize how and when to
accomplish it. To make that practical, most work is done through pure functions without
side effects, making Power Fx also a functional language (again, just as Excel is).
Always live
A defining aspect of worksheets is that they're always live, and changes are reflected
instantaneously. There is no compile or run mode in a worksheet. When a formula is
modified or a value is entered, the worksheet is immediately recalculated to reflect the
changes. Any errors that are detected are surfaced immediately, and don't interfere with
the rest of the worksheet.
The same thing is implemented with Power Fx. An incremental compiler is used to
continuously keep the program in sync with the data it's operating on. Changes are
automatically propagated through the program's graph, affecting the results of
dependent calculations, which might drive properties on controls such as color or
position. The incremental compiler also provides a rich formula editing experience with
IntelliSense, suggestions, autocomplete, and type checking.
In the animation below, the order number is displayed in a label control dependent on
the slider control, even though there are two errors on the labels below it. The app is
very much alive and interactive. The first attempt at fixing the formula by entering
.InvalidName results in an immediate red line and error displayed, as it should, but the
app keeps running.
When .Employee is entered, this causes the Data pane to add the Employees table,
metadata for this table is retrieved, and suggestions for columns are immediately
offered. We just walked across a relationship from one table to another, and the system
made the needed adjustments to the app's references. The same thing happens when
adding a .Customer .
After each change, the slider continues with its last value and any variables retain their
value. Throughout, the order number has continued to be displayed in the top label as it
should. The app has been live, processing real data, the entire time. We can save it, walk
away, and others can open and use it just like Excel. There is no build step, no compile,
there's only a publish step to determine which version of the app is ready for users.
Low code
Power Fx describes business logic in concise, yet powerful, formulas. Most logic can be
reduced to a single line, with plenty of expressiveness and control for more complex
needs. The goal is to keep to a minimum the number of concepts a maker needs to
understand—ideally, no more than an Excel user would already know.
For example, to look up the first name of an employee for an order, you write the Power
Fx as shown in the following animation. Beyond Excel concepts, the only added concept
used here is the dot "." notation for drilling into a data structure, in this case
.Employee.'First Name' . The animation shows the mapping between the parts of the
Power Fx formula and the concepts that need to be explicitly coded in the equivalent
JavaScript.
Let's look more in-depth at all the things that Power Fx is doing for us and the freedom
it has to optimize because the formula was declarative:
Local and remote: Power Fx uses the same syntax and functions for data that's
local in-memory and remote in a database or service. The user need not think
about this distinction. Power Fx automatically delegates what it can to the server,
to process filters and sorts there more efficiently.
Relational data: Orders and Customers are two different tables, with a many-to-
one relationship. The OData query requires an "$expand" with knowledge of the
foreign key, similar to a Join in SQL. The formula has none of this; in fact, database
keys are another concept the maker doesn't need to know about. The maker can
use simple dot notation to access the entire graph of relationships from a record.
Projection: When writing a query, many developers write select * from table ,
which brings back all the columns of data. Power Fx analyzes all the columns that
are used through the entire app, even across formula dependencies. Projection is
automatically optimized and, again, a maker doesn't need to know what
"projection" means.
Retrieve only what is needed: In this example, the LookUp function implies that
only one record should be retrieved and that's all that's returned. If more records
are requested by using the Filter function—for which thousands of records
might qualify—only a single page of data is returned at a time, on the order of 100
records per page. The user must gesture through a gallery or data table to see
more data, and it will automatically be brought in for them. The maker can reason
about large sets of data without needing to think about limiting data requests to
manageable chunks.
Runs only when needed: We defined a formula for the Text property of the label
control. As the variable selected changes, the LookUp is automatically recalculated
and the label is updated. The maker didn't need to write an OnChange handler for
Selection, and didn't need to remember that this label is dependent upon it. This is
declarative programming, as discussed earlier: the maker specified what they
wanted to have in the label, not how or when it should be fetched. If this label isn't
visible because it's on a screen that isn't visible, or its Visible property is false, we
can defer this calculation until the label is visible and effectively eliminate it if that
rarely happens.
Excel syntax translation: Excel is used by many users, most of whom know that the
ampersand (&) is used for string concatenation. JavaScript uses a plus sign (+), and
other languages use a dot (.).
Display names and localization: First Name is used in the Power Fx formula while
nwind_firstname is used in the JavaScript equivalent. In Microsoft Dataverse and
SharePoint, there's a display name for columns and tables in addition to a unique
logical name. The display names are often much more user-friendly, as in this case,
but they have another important quality in that they can be localized. If you have a
multilingual team, each team member can see table and field names in their own
language. In all use cases, Power Fx makes sure that the correct logical name is
sent to the database automatically.
No code
You don't have to read and write Power Fx to start expressing logic. There are lots of
customizations and logic that can be expressed through simple switches and UI builders.
These no-code tools have been built to read and write Power Fx to ensure that there's
plenty of headroom for someone to take it further, while acknowledging that no-code
tools will never offer all the expressiveness of the full language. Even when used with
no-code builders, the formula bar is front and center in Power Apps to educate the
maker about what's being done on their behalf so they can begin to learn Power Fx.
Let's take a look at some examples. In Power Apps, the property panel provides no-code
switches and knobs for the properties of the controls. In practice, most property values
are static. You can use the color builder to change the background color of the Gallery .
Notice that the formula bar reflects this change, updating the formula to a different
RGBA call. At any time, you can go to the formula bar and take this a step further—in this
example, by using ColorFade to adjust the color. The color property still appears in the
properties panel, but an fx icon appears on hover and you're directed to the formula
bar. This fully works in two ways: removing the ColorFade call returns the color to
something the property panel can understand, and you can use it again to set a color.
Here's a more complicated example. The gallery shows a list of employees from
Dataverse. Dataverse provides views over table data. We can select one of these views
and the formula is changed to use the Filter function with this view name. The two
drop-down menus can be used to dial in the correct table and view without touching
the formula bar. But let's say you want to go further and add a sort. We can do that in
the formula bar, and the property panel again shows an fx icon and directs
modifications to the formula bar. And again, if we simplify the formula to something the
property panel can read and write, it again can be used.
These have been simple examples. We believe Power Fx makes a great language for
describing no-code interactions. It is concise, powerful, and easy to parse, and provides
the headroom that is so often needed with "no cliffs" up to low-code.
Pro code
Low-code makers sometimes build things that require the help of an expert or are taken
over by a professional developer to maintain and enhance. Professionals also appreciate
that low-code development can be easier, faster, and less costly than building a
professional tool. Not every situation requires the full power of Visual Studio.
Simple
Power Fx is designed to target the maker audience, whose members haven't been
trained as developers. Wherever possible, we use the knowledge that this audience
would already know or can pick up quickly. The number of concepts required to be
successful is kept to a minimum.
Being simple is also good for developers. For the developer audience, we aim to be a
low-code language that cuts down the time required to build a solution.
Excel consistency
Microsoft Power Fx language borrows heavily from the Excel formula language. We seek
to take advantage of Excel knowledge and experience from the many makers who also
use Excel. Types, operators, and function semantics are as close to Excel as possible.
If Excel doesn't have an answer, we next look to SQL. After Excel, SQL is the next most
commonly used declarative language and can provide guidance on data operations and
strong typing that Excel doesn't.
Declarative
The maker describes what they want their logic to do, not exactly how or when to do it.
This allows the compiler to optimize by performing operations in parallel, deferring work
until needed, and pre-fetching and reusing cached data.
For example, in an Excel worksheet, the author defines the relationships among cells but
Excel decides when and in what order formulas are evaluated. Similarly, formulas in an
app can be thought of as "recalc-ing" as needed based on user actions, database
changes, or timer events.
Functional
We favor pure functions that don't have side effects. This results in logic that's easier to
understand and gives the compiler the most freedom to optimize.
Unlike Excel, apps by their nature do mutate state—for example, apps have buttons that
save changes to the record in a database. Some functions, therefore, do have side
effects, although we limit this as much as is practical.
Composition
Where possible, the functionality that's added composes well with existing functionality.
Powerful functions can be decomposed into smaller parts that can be more easily used
independently.
For example, a Gallery control doesn't have separate Sort and Filter properties.
Instead, the Sort and Filter functions are composed together into a single Items
property. The UI for expressing Sort and Filter behavior is layered on top of the
Items property by using a two-way editor for this property.
Strongly typed
The types of all the values are known at compile time. This allows for the early detection
of errors and rich suggestions while authoring.
Polymorphic types are supported, but before they can be used, their type must be
pinned to a static type and that type must be known at compile time. The IsType and
AsType functions are provided for testing and casting types.
Type inference
Types are derived from their use without being declared. For example, setting a variable
to a number results in the variable's type being established as a number.
The choice of decimal separator has a cascading impact on the list separator, used for
function call arguments, and the chaining operator.
Not object-oriented
Excel isn't object-oriented, and neither is Power Fx. For example, in some languages, the
length of a string is expressed as a property of the string, such as "Hello World".length
in JavaScript. Excel and Power Fx instead express this in terms of a function, as Len(
"Hello World" ) .
Components with properties and methods are object-oriented and Power Fx easily
works with them. But where possible, we prefer a functional approach.
Extensible
Makers can create their components and functions by using Power Fx itself. Developers
can create their components and functions by writing JavaScript.
Developer friendly
Although makers are our primary target, we try to be developer-friendly wherever
possible. If it doesn't conflict with the design principles described previously, we do
things in a way that a developer will appreciate. For example, Excel has no capability for
adding comments, so we use C-like line and inline comments.
Language evolution
Evolving programming languages is both necessary and tricky. Everyone—rightfully—is
concerned that a change, no matter how well-intentioned, might break existing code
and require users to learn a new pattern. Power Fx takes backward compatibility
seriously, but we also strongly believe that we won't always get it right the first time and
we'll collectively learn what's best as a community. We must evolve, and Power Fx
designed support for language evolution from the very beginning.
A language version stamp is included with every Power Fx document that's saved. If we
want to make an incompatible change, we'll write what we call a "back compat
converter" that rewrites the formula automatically the next time it's edited. If the change
is something major that we need to educate the user about, we'll also display a message
with a link to the docs. Using this facility, we can still load apps that were built with the
preview versions of Power Apps from many years ago, despite all the changes that have
occurred since then.
For example, we introduced the ShowError function to display an error banner with a
red background.
Users loved it, but they also asked us for a way to show a success banner (green
background) or an informational banner (blue background). So, we came up with a more
generic Notify function that takes a second argument for the kind of notification. We
could have just added Notify and kept ShowError the way it was, but instead we
replaced ShowError with Notify . We removed a function that had previously been in
production and replaced it with something else. Because there would have been two
ways to do the same thing, this would have caused confusion—especially for new users
—and, most importantly it would have added complexity. Nobody complained,
everybody appreciated the change and then moved on to their next Notify feature.
This is how the same app looks when loaded into the latest version of Power Apps. No
action was required by the user to make this transformation happen, it occurred
automatically when the app was opened.
With this facility, Power Fx can evolve faster and more aggressively than most
programming languages.
No undefined value
Some languages, such as JavaScript, use the concept of an undefined value for
uninitialized variables or missing properties. For simplicity's sake, we've avoided this
concept. Instances that would be undefined in other languages are treated as either an
error or a blank value. For example, all uninitialized variables start with a blank value. All
data types can take on the value of blank.
Related articles
Data types
Tables
Variables
Imperative logic
Global support
Expression grammar
7 Note
Configure your canvas app with formulas that not only calculate values and perform
other tasks (as they do in Excel) but also respond to user input (as an app requires).
In Excel, you build formulas that, for example, populate cells and create tables and
charts.
In Power Apps, you build similar formulas as you configure controls instead of
cells. In addition, you build formulas that apply specifically to apps instead of
spreadsheets.
For example, you build a formula to determine how your app responds when users
select a button, adjust a slider, or provide other input. These formulas might show a
different screen, update a data source that's external to the app, or create a table that
contains a subset of the data in an existing table.
You can use formulas for a wide variety of scenarios. For example, you can use your
device's GPS, a map control, and a formula that uses Location.Latitude and
Location.Longitude to display your current location. As you move, the map
automatically tracks your location.
This topic provides only an overview of working with formulas. Browse the formula
reference for more details and the complete list of functions, operators, and other
building blocks you can use.
Prerequisites
Sign up for Power Apps, and then sign in by providing the same credentials that
you used to sign up.
Learn how to configure a control in Power Apps.
a. Property list: Each control and screen has a set of properties. Use this list to
select a specific property.
b. Formula: The formula to be calculated for this property, made up of values,
operators, and functions.
c. Selected control: In the formula bar, you can see and edit properties for the
selected control or for the screen if no controls are selected.
3. Set the value of the Text property to "Hello World" by typing that string,
surrounded by double quotes, into the formula bar:
The label reflects this new value as you type it. The screen may show yellow
exclamation-point icons while you type. These icons indicate errors, but they'll go
away when you finish entering a valid value. For example, a string without double
quotation marks on both ends isn't valid.
In Excel, you can show a number, such as 42, by typing it into a cell or by typing a
formula that resolves to that number, such as =SUM(30,12). In Power Apps, you
can achieve the same effect by setting the Text property of a control, such as a
label, to 42 or Sum(30,12). The cell and the label will always show that number
regardless of what else changes in the worksheet or the app.
7 Note
In Power Apps, you don't precede a formula with an equals sign or a plus sign
as you do in Excel. The formula bar treats anything you type there as a
formula by default. You also don't surround a formula with double quotation
marks ("), as you did earlier to specify a string of text.
4. In the Text property of the label, replace "Hello World" with Sum(1,2,3).
While you type, the formula bar helps you by showing the description and the
expected arguments for this function. As with the final double quotation mark in
"Hello World", the screen shows red cross to indicate an error until you type the
final parenthesis of this formula:
Regardless of what numbers you type in the text-input controls, the label always shows
the sum of those numbers because its Text property is set to this formula:
TextInput1 + TextInput2
In Excel, you can use conditional-formatting formulas to show, for example, negative
values in red. In Power Apps, you can use formulas to determine not only the primary
value of a control but also properties such as formatting. In the next example, a formula
for the Color property of the label automatically shows negative values in red. The If
function should look very familiar from Excel:
1. Remove the controls from the previous procedures, or create a blank app as you
did previously, and add three slider controls to it:
2. Arrange the sliders so they don't overlap, add three labels, and configure them to
show Red, Green, and Blue:
3. Set the Max property of each slider to 255, which is the maximum value of a color
component for the RGBA function.
4. Select the screen by selecting away from any control, and then set the screen's Fill
property to this formula:
5. Adjust the sliders, and see how your changes affect the background color by
running the app.
As each slider changes, the formula that contains the RGBA function is
recalculated, which immediately changes how the screen appears.
Manage app behavior
You can use formulas not only to perform calculations and change appearance but also
to take action. For example, you can set the OnSelect property of a button to a formula
that includes the Navigate function. When a user selects that button, the screen that
you specify in the formula appears.
You can use some functions, such as Navigate and Collect, only in behavior formulas.
The formula reference calls out if you can use a function only in this context.
You can take more than one action in a behavior formula if you separate functions with
a semi-colon (;). For example, you might want to update a context variable, push data to
a data source, and finally navigate to another screen.
View a list of properties by category
The properties list shows properties alphabetically, but you can also view all the
properties of a control, organized by category, if you select the Advanced option on the
View tab from the right-side of the screen:
You can edit formulas directly within this view. With the control selector at the top of the
pane, you can quickly find a control to work with. And with the property search, you can
quickly find a property of that control.
Initially, this view shows the most important properties. To reveal all the properties, click
the down arrow at the bottom of the pane. Each control has a long list of properties that
govern all aspects of the control's behavior and appearance. You can scroll through the
list or search for a property by typing in the box at the top of the pane.
Formula syntax
As you type a formula in the formula bar, different syntax elements appear in different
colors to improve readability and help you understand long formulas. Here is the color
code list in Power Apps.
See also
Use Find and Replace capability in the formula bar
Operators and Identifiers
Article • 02/23/2023 • 12 minutes to read
7 Note
Microsoft Power Fx is the new name for the canvas apps formula language. These
articles are work in progress as we extract the language from canvas apps, integrate
it with other Microsoft Power Platform products, and make it available as open
source. Start with the Microsoft Power Fx Overview for an introduction to the
language.
The operators in Microsoft Power Fx are described below. Some of these operators are
dependent on the language of the author. See Global apps for more information.
. Property Slider1.Value
Extracts a property from a table control,
Selector Color.Red or enumeration. For backward
compatibility, ! can be used.
.
Decimal 1.23 Separator between whole and fractional
language separator parts of a number. The character
dependent depends on the language.
* 2*3 Multiplication
& String "hello" & " " & Makes multiple strings appear
concatenation "world" continuous
operator
&& or And Logical Price < 100 && Logical conjunction, equivalent to the
operators Slider1.Value = 20
And function
or Price < 100 And
Slider1.Value = 20
! or Not !(Price < 100) or Not Logical negation, equivalent to the Not
(Price < 100) function
,
List separator If(X < 10, "Low", Separates:
[language "Good")
arguments in function calls
dependent] { X: 12, Y: 32 }
fields in a record
[ 1, 2, 3 ] records in a table
;
Formula Collect(T, A); Separate invocations of functions in
[language chaining Navigate(S1, "") behavior properties. The chaining
dependent] operator depends on the language.
1. Create or import a collection named Inventory, and show it in a gallery, as the first
procedure in Show images and text in a gallery describes.
The gallery shows only Europa because only its name contains the letter that you
specified in the case that you specified.
ThisItem Gallery control
The default name for the current record in a Gallery or form
Edit form control
control.
Display form control
ThisRecord ForAll, Filter, With, The default name for the current record in ForAll and other
Sum and other record scope functions.
record scope
functions
As name Gallery control
Defines a name for the current record, replacing default
ForAll, Filter, With, ThisItem or ThisRecord. Use As to make formulas easier to
Sum and other understand and resolve ambiguity when nesting.
record scope
functions
ThisItem operator
For example, in the following Gallery control, the Items property is set to the Employees
data source (such as the Employees entity included with the Northwind Traders sample):
Power Apps
Employees
The first item in the gallery is a template that is replicated for each employee. In the
template, the formula for the picture uses ThisItem to refer to the current item:
Power Apps
ThisItem.Picture
Power Apps
ThisRecord operator
ThisRecord is used in functions that have a record scope. For example, we can use the
Filter function with our gallery's Items property to only show first names that being with
M:
Power Apps
ThisRecord is optional and implied by using the fields directly, for example, in this case,
we could have written:
Power Apps
Although optional, using ThisRecord can make formulas easier to understand and may
be required in ambiguous situations where a field name may also be a relationship
name. ThisRecord is optional while ThisItem is always required.
Use ThisRecord to reference the whole record with Patch, Collect, and other record
scope functions. For example, the following formula sets the status for all inactive
employees to active:
Power Apps
ForAll( InactiveEmployees,
As operator
Use the As operator to name a record in a gallery or record scope function, overriding
the default ThisItem or ThisRecord. Naming the record can make your formulas easier
to understand and may be required in nested situations to access records in other
scopes.
For example, you can modify the Items property of our gallery to use As to identify that
we are working with an Employee:
Power Apps
Employees As Employee
The formulas for the picture and name are adjusted to use this name for the current
record:
Power Apps
Employee.Picture
Power Apps
Employee.'First Name' & " " & Employee.'Last Name'
As can also be used with record scope functions to replace the default name
ThisRecord. We can apply this to our previous example to clarify the record we are
working with:
Power Apps
When nesting galleries and record scope functions, ThisItem and ThisRecord always
refers to the inner most scope, leaving records in outer scopes unavailable. Use As to
make all record scopes available by giving each a unique name.
For example, this formula produces a chessboard pattern as a text string by nesting two
ForAll functions:
Power Apps
Concat(
Concat(
),
Value
) & Char(10)
),
Value
A similar example is possible with nested Gallery controls instead of ForAll functions.
Let's start with the vertical gallery for the Rank. This gallery control will have an Items
formula of:
Power Apps
Sequence(8) as Rank
Within this gallery, we'll place a horizontal gallery for the File, that will be replicated for
each Rank, with an Items property of:
Power Apps
Sequence(8) as File
And finally, within this gallery, we'll add a Label control that will be replicated for each
File and each Rank. We'll size it to fill the entire space and use the Fill property to
provide the color with this formula:
Power Apps
Method Description
By Any control can be referenced by name from anywhere within the app.
control
name For example, Label1.Fill refers to the fill property of the control who's name is Label1.
Self It's often convenient to reference another property of the same control when writing a
operator formula. Instead of using an absolute reference by name, it's easier and more portable
to use a relative reference to oneself. The Self operator provides that easy access to
the current control.
For example, Self.Fill refers to the fill color of the current control.
Parent Some controls host other controls, such as the Screen and Gallery controls. The
operator hosting control of the controls within it is called the parent. Like the Self operator, the
Parent operator provides an easy relative reference to the container control.
For example, Parent.Fill refers to the fill property of the control that is the container for
the current control.
Self and Parent are operators and not properties on the controls themselves. Referring
to Parent.Parent, Self.Parent or Parent.Self is not supported.
Identifier names
The names of variables, data sources, columns, and other objects can contain any
Unicode .
Use single quotes around a name that contains a space or other special character.
Use two single quotes together to represent one single quote in the name. Names that
do not contain special characters do not require single quotes.
Here are some example column names you might encounter in a table, and how they
are represented in a formula:
SimpleName SimpleName
NameWith123Numbers NameWith123Numbers
Logical name - A name that is guaranteed to be unique, does not change after
being created, usually does not allow spaces or other special characters, and is not
localized into different languages. As a result, the name can be cryptic. These
names are used by professional developers. For example, cra3a_customfield. This
name may also be referred to as schema name or just name.
Display name - A name that is user-friendly and intended to be seen by end users.
This name may not be unique, may change over time, may contain spaces and any
Unicode character, and may be localized into different languages. Corresponding
to the example above, the display name may be Custom Field with space in
between the words.
Since display names are easier to understand, Power Fx will suggest them as choices and
not suggest logical names. Although logical names are not suggested, they can still be
used if typed indirectly.
For example, imagine you have added a Custom Field to an entity in Dataverse. A
logical name will be assigned for you by the system, which you can modify only when
creating the field. The result would look similar to:
When authoring a reference to a field of Accounts, the suggestion will be made to use
'Custom Field' since this is the display name. The single quotes must be used because
this name has a space in it:
After selecting the suggestion, 'Custom Field' is shown in the formula bar and the data is
retrieved:
Although it is not suggested, we could also use the logical name for this field. This will
result in the same data being retrieved. No single quotes are required since this name
does not contain spaces or special characters:
Behind the scenes, a mapping is maintained between the display names seen in
formulas and the underlying logical names. Since logical names must be used to interact
with the data source, this mapping is used to convert from the current display name to
the logical name automatically and that is what is seen in the network traffic. This
mapping is also used to convert back to logical names to switch into new display names,
for example, if a display name changes or a maker in a different language edits the app.
7 Note
Logical names are not translated when moving an app between environments. For
Dataverse system entity and field names, this should not be a problem as logical
names are consistent across environments. But any custom fields, such as
cra3a_customfield in this example above, may have a different environment prefix
(cra3a in this case). Display names are preferred as they can be matched against
display names in the new environment.
Name disambiguation
Since display names are not unique, the same display name may appear more than once
in the same entity. When this happens, the logical name will be added to the end of the
display name in parenthesis for one of more of the conflicting names. Building on the
example above, if there was a second field with the same display name of Custom Field
with a logical name of cra3a_customfieldalt then the suggestions would show:
Name disambiguation strings are added in other situations where name conflicts occur,
such as the names of entities, option sets, and other Dataverse items.
Disambiguation operator
Some functions create record scopes for accessing the fields of table while processing
each record, such as Filter, AddColumns, and Sum. Field names added with the record
scope override the same names from elsewhere in the app. When this happens, you can
still access values from outside the record scope with the @ disambiguation operator:
To access values from nested record scopes, use the @ operator with the name of
the table being operated upon using this pattern:
Table[@FieldName]
To access global values, such as data sources, collections, and context variables,
use the pattern [@ObjectName] (without a table designation).
7 Note
Microsoft Power Fx is the new name for the canvas apps formula language. These
articles are work in progress as we extract the language from canvas apps, integrate
it with other Microsoft Power Platform products, and make it available as open
source. Start with the Microsoft Power Fx Overview for an introduction to the
language.
Information flows through an app in small, discrete values, very much like the cells of a
spreadsheet. For example, data in a Birthday field and an Anniversary field would both
flow through as a Date value that includes the year, the month, and the day. The app
knows how to format these values, constrain input to what is appropriate for each, and
share the values with a database. Birthdays differ from anniversaries to people, but the
system handles them in exactly the same manner. In this case, Date is an example of a
data type .
This article provides details for the data types that canvas apps support. When an app
connects to an external data source, each data type in that source is mapped to a data
type for canvas apps.
DateTime A date with a time, in the time zone of DateTimeValue( "May 16, 2019 1:23:09 PM"
the app's user. )
Data Description Examples
type
GUID( "123e4567-e89b-12d3-a456-
426655440000" )
Media A URI text string to a video or audio MyVideo added as an app resource
recording. "https://northwindtraders.com/intro.mp4"
"appres://blobmanager/3ba411c..."
-4.567
8.903e121
Time A time without a date, in the time zone Time( 11, 23, 45 )
of the app's user.
Many of these data types are similar and have the same underlying representation, such
as a Hyperlink field being treated as Text. The additional data types provide better
default experiences in forms and other controls.
Blank
All data types can have a value of blank (in other words, no value). The term "null" is
often used in databases for this concept.
Use the Blank function with the Set or Patch function to set a variable or field to blank.
For example, Set( x, Blank() ) removes any value in the global variable x.
Test for a blank value by using the IsBlank function. Replace possible blank values with
non-blank values by using the Coalesce function.
Because all data types support blank, the Boolean and Two option data types effectively
have three possible values.
Power Apps
results in a banner when the button is pressed, where the first and last double quotes
are omitted (as they delimit the text string) and the repeated double quotes around
Hello, World! are replaced with a single double quote:
Single quotation marks are used for identifier names that contain special characters and
have no special significance within a text string.
String interpolation
Use string interpolation to embed formulas within a text string. This is often easier to
work with and visualize the output than using the Concatenate function or & operator.
Prefix the text string with a dollar sign $ and enclose the formula to be embedded with
curly braces { }. To include a curly brace in the text string, use repeated curly braces: {{ or
}}. String interpolation can be used anywhere a standard text string can be used.
For example, consider this formula with global variables Apples set to 3 and Bananas set
to 4:
Power Apps
This formula returns the text string We have 3 apples, 4 bananas, yielding 7 fruit total.
The variables Apples and Bananas are inserted in the text replacing the curly braces,
along with the result of the mathematical formula Apples+Bananas. Spaces and other
characters around the curly braces are preserved as they are.
Embedded formulas can include any functions or operators. All that is requires is that
the result of the formula can be coerced to a text string. For example, this formula will
insert NickName if it's supplied, or the FirstName if not, in a greeting:
Power Apps
If NickName is set to "Joe", then this formula produces the text string Welcome Joe, it's
great to meet you!. But if NickName is blank and FirstName is "Joseph", then this
formula produces Dear Joseph, great to meet you! instead.
String interpolation can include standard text strings in the embedded formula. For
example, if neither NickName nor FirstName were supplied, we could still provide
"Friend" as a substitute:
Power Apps
String interpolations can even be nested. Consider this example where First, Middle, and
Last names are combined into a greeting. Even if one or two of these values are blank,
the correct number of spaces will be between the name parts. If none of the parts are
provided, the inner string interpolation will collapse to an empty string, and be replaced
by the Coalesce function by "Friend".
Power Apps
Power Apps
"Line 1
Line 2
Line 3"
The above formula results in three lines shown in the label control:
Power Apps
$"Line {1}
Line {1+1}
Line {1+1+1}"
To use this resource in an app, specify it in the Image property of an Image control:
For example, the Image property of an image control accepts not only app resources
but also links to images on the web, such as "https://northwindtraders.com/logo.jpg".
The property also accepts inline images that use the data URI scheme , as in this
example:
Power Apps
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAFAQMAAACtnVQoAAAABlBMV
EUAAAB0J3UMNU6VAAAAAXRSTlMAQObYZgAAABRJREFUCNdjUGJgCGVg6GgAkkA2AA8/AffqCEBsA
AAAAElFTkSuQmCC"
You can show the most recent image captured in a Camera control if you set the Image
property of an image control to the Photo property of the camera control. The app
holds the image in memory, and the Photo property of the camera control returns a URI
reference to the image. For example, you might take a picture, and the camera's Photo
property could return "appres://blobmanager/7b12ffa2ea4547e5b3812cb1c7b0a2a0/1".
You use a URI to reference an image or another media file stored in a database. That
way, the app doesn't retrieve the actual data until it's actually needed. For example, an
attachment in a Microsoft Dataverse table might return
"appres://datasources/Contacts/table/..." As in the camera example, you can display
this image by setting the Image property of an image control to this reference, which
retrieves the binary data.
When you save a media data type, such as an image, to a database, the app sends the
actual image or media data, not the URI reference.
Size limits
As text strings and URIs, these data types have no preset limit on their length.
The binary data that these data types reference also has no preset limit on size. For
example, an image captured through the camera control that's now referenced as
"appres://..." can be as large and high resolution as the device's camera can muster. The
resolution, frame rate, and other attributes of media files aren't limited by the data type,
but specific controls for playing and capturing media may have their own limitations.
However, all data sizes are subject to the amount of available memory in the app.
Browsers running on a desktop computer typically support more than 100 megabytes of
data. However, the amount of available memory on a device such as a phone might be
far lower, typically in the range 30-70 megabytes. To determine whether your app will
run within these limits, test common scenarios on all devices on which it should run.
As a best practice, hold data in memory only as long as necessary. Upload images to a
database as soon as you can; download images only when the app's user requests them.
Canvas apps can exactly represent whole numbers (or integers) between –
9,007,199,254,740,991 (–(253 – 1)) and 9,007,199,254,740,991 (253 – 1), inclusive. This
range is larger than the 32-bit (or 4-byte) integer data types that databases commonly
use. However, canvas apps can't represent 64-bit (or 8-byte) integer data types. You
might want to store the number in a text field or use a calculated column to make a
copy of the number in a text field, so that it's mapped into a Text data type in the
canvas app. In this manner, you can hold, display, and enter these values, as well as
comparing them to determine whether they're equal; however, you can't perform
numerical calculations on them in this form.
Database systems often store currencies and perform calculations by using decimal
math, which offers a smaller range but greater control over the precision. By default,
canvas apps map currencies in and out of floating-point values; therefore, the result
might differ from calculations that are done in a native decimal data type. If this type of
discrepancy will cause problems, you might want to work with these values as Text, just
as you might with large integers described earlier in this section.
Time zones
Date/time values fall in these categories:
User local: These values are stored in UTC (Coordinated Universal Time) , but the
app user's time zone affects how the app shows these values and how the app user
specifies them. As an example, the same moment appears differently to a user in
Canada than it does to a user in Japan.
Time zone independent: The app shows these values the same way and the app
user specifies them the same way, regardless of time zone. The same moment
appears the same way to a user in Canada as it does to a user in Japan. App
authors who don't expect their apps to run in different time zones use these values
because they're simpler overall.
Date/time Value stored in the Value displayed and Value displayed and
type database entered 7 hours west of entered 4 hours east of
UTC UTC
For User local date/times, canvas apps use the time zone of the browser or device, but
model-driven apps use the user's setting in Dataverse. These settings typically match,
but results will differ if these settings differ.
Use the DateAdd and TimeZoneInformation functions to convert local time to UTC and
back again. See the examples at the end of the documentation for these functions.
Numeric equivalents
Canvas apps hold and calculate all date/time values, whether User local or Time zone
independent in UTC. The app translates the values based on the app user's time zone
when showing them and when the app user specifies them.
When a canvas app reads a Time zone independent value from a data source or writes
such a value to a data source, the app automatically adjusts the value to compensate for
the time zone of the app's user. The app then treats the value as a UTC value, consistent
with all other date/time values in the app. Because of this compensation, the original
Time zone independent value appears when the app adjusts the UTC value for the app
user's time zone.
You can observe this behavior more closely by using the Value function to access the
underlying numerical value for a date/time value. This function returns the date/time
value as the number of milliseconds since January 1, 1970 00:00:00.000 UTC.
Because every date/time value is held in UTC, the formula Value( Date( 1970, 1, 1 ) )
won't return zero in most parts of the world because the Date function returns a date in
UTC. For example, the formula would return 28,800,000 in a time zone that's offset from
UTC by eight hours. That number reflects the number of milliseconds in eight hours.
Date/time Value stored in the Value displayed and entered Value function
type database 7 hours west of UTC returns
4:00 AM UTC)
11:00 AM UTC)
For example, Unix time shows September 9, 2001, at 01:46:40 UTC as 1,000,000,000. To
show that date/time value in a canvas app, multiply that number by 1,000 to convert it
to milliseconds, and then use it in a Text function. The formula Text( 1000000000 * 1000,
DateTimeFormat.UTC ) returns the string 2001-09-09T01:46:40.000Z.
However, that function returns Saturday, September 8, 2001 18:46:40 if you use the
DateTimeFormat.LongDateTime24 format in a time zone that's -7 hours offset from
UTC (7 hours west of UTC). This result shows the DateTime value correctly based on the
local time zone.
If you need the Unix time in a Date value for further calculations or display within Power
Apps, use this formula:
SQL Server
SQL Server has Datetime, Datetime2, and other date/time data types that don't include
a time-zone offset and don't indicate which time zone they're in. Canvas apps assume
these values are stored in UTC and treat them as User local. If the values are meant to
be time-zone independent, correct for the UTC translations by using the
TimeZoneOffset function.
Canvas apps use the included time-zone information in Datetimeoffset fields when
converting a value to the app's internal UTC representation. The apps always use UTC as
the time zone (zero time zone offset) when they write data.
Canvas apps read and write values of the Time data type in SQL Server as text strings in
the ISO 8601 duration format . For example, you must parse this string format and use
the Time function to convert the text string "PT2H1M39S" to a Time value:
Power Apps
With(
// Result: 2:01 AM (as shown in a label control, use the Text function to
see the seconds)
Adding and subtracting date and time values directly isn't recommended because time-
zone and other conversions could cause confusing results. Either use the Value function
to convert date/time values to milliseconds first and take into account the app user's
time zone, or use the DateAdd and DateDiff functions to add or subtract from one of
these values.
Both of these data types show their labels in a text-string context. For example, a label
control shows one of the order-status options if the control's Text property is set to a
formula that references that choice. Option labels might be localized for app users in
different locations.
When an app user selects an option and saves that change, the app transmits the data
to the database, which stores that data in a representation that's independent of
language. An option in a choice is transmitted and stored as a number, and an option in
a two-option data type is transmitted and stored as a boolean value.
The labels are for display purposes only. You can't perform direct comparisons with the
labels because they're specific to a language. Instead, each choice has an enumeration
that works with the underlying number or boolean value. For example, you can't use this
formula:
For global choices (which tables share), the name of the option-set enumeration
matches the name of the global choice. For local choices (which are scoped to a table),
the name might contain the name of the table. This behavior avoids conflicts if multiple
tables have choices that have the same name. For example, the Accounts table might
have an OrderStatus choice, and its name might be OrderStatus (Accounts). That name
contains one or more spaces and parentheses, so you must surround it with single
quotation marks if you reference it in a formula.
In addition, two-option values can also behave as boolean values. For example, a two-
option value named TaxStatus might have the labels Taxable and Non-Taxable, which
correspond to true and false respectively. To demonstrate, you can use this formula:
7 Note
Microsoft Power Fx is the new name for the canvas apps formula language. These
articles are work in progress as we extract the language from canvas apps, integrate
it with other Microsoft Power Platform products, and make it available as open
source. Start with the Microsoft Power Fx Overview for an introduction to the
language.
In Microsoft Power Fx, you can write a formula that accesses information in Microsoft
Excel, SharePoint, SQL Server, and several other sources that store data in records and
tables. To work most effectively with this kind of data, review the concepts that underlie
these structures.
You can build a variety of formulas that take the name of a table as an argument, just as
a formula in Excel takes one or more cell references as arguments. Some formulas in
Power Fx return a table that reflects the other arguments that you specify. For example,
you might create a formula:
Elements of a table
Records
Each record contains at least one category of information for a person, a place, or a
thing. The example above shows a record for each product (Chocolate, Bread, and
Water) and a column for each category of information (Price, Quantity on Hand, and
Quantity on Order).
In a formula, you can refer to a record by itself, outside of a table's context, by using
curly braces. For example, this record { Name: "Strawberries", Price: 7.99 } isn't
associated with a table. Note that field names, such as Name and Price in that example,
aren't enclosed in double quotation marks.
Fields
A field is an individual piece of information in a record. You can visualize this sort of field
as a value in a column for a particular record.
Just as with a control, you refer to a field of a record by using the . operator on the
record. For example, First(Products).Name returns the Name field for the first record in
the Products table.
A field can contain another record or table, as the example for the GroupBy function
shows. You can nest as many levels of records and tables as you want.
Columns
A column refers to the same field for one or more records in a table. In the above
example, each product has a price field, and that price is in the same column for all
products. The above table has four columns, shown horizontally across the top:
Name
Price
Quantity on Hand
Quantity on Order
All values within a column are of the same data type. In the above example, the
"Quantity on Hand" column always contains a number and can't contain a string, such as
"12 units," for one record. The value of any field may also be blank.
Table
A table comprises one or more records, each with multiple fields that have consistent
names across the records.
Any table that's stored in a data source or a collection has a name, which you use to
refer to the table and pass it to functions that take tables as arguments. Tables can also
be the result of a function or a formula.
As in the following example, you can express a table in a formula by using the Table
function with a set of records, which you express in curly braces:
You can also define a single-column table with square brackets. An equivalent way to
write the above:
[ "Strawberry", "Vanilla" ]
Table formulas
In Excel and Power Fx, you use formulas to manipulate numbers and strings of text in
similar ways:
In Excel, type a value, such as 42, in cell A1, and then type a formula, such as A1+2,
in another cell to show the value of 44.
In Power Apps, set the Default property of Slider1 to 42, and set the Text property
of a label to Slider1.Value + 2 to show the value of 44.
In both cases, the calculated value changes automatically if you change the values of the
arguments (for example, the number in cell A1 or the value of Slider1).
Similarly, you can use formulas to access and manipulate data in tables and records. You
can use names of tables as arguments in some formulas, such as Min(Catalog, Price) to
show the lowest value in the Price column of the Catalog table. Other formulas provide
whole tables as return values, such as RenameColumns(Catalog, "Price", "Cost"), which
returns all the records from the Catalog table but changes the name of the Price column
to Cost.
Just as with numbers, formulas that involve tables and records are automatically
recalculated as the underlying table or record changes. If the cost of a product in the
Catalog table is lowered below the previous minimum, the return value of the Min
formula will automatically change to match it.
Power Fx offers a set of functions that operate on tables in the same manner. These
functions take tables as input and filter, sort, transform, reduce, and summarize entire
tables of data. In fact, Lower and many other functions that typically take a single value
can also take a single-column table as input.
Many functions take a single-column table as their input. If an entire table has only one
column, you can specify it by name. If a table has multiple columns, you can specify one
of those columns by using Table.Column syntax. For example, Products.Name returns
the single-column table of only Name values from the Products table.
You can completely reshape a table however you want by using the AddColumns,
RenameColumns, ShowColumns, or DropColumns function. Again, these functions
change only their output, not their source.
Behavioral formulas
Other functions are specifically designed to modify data and have side effects. Because
these functions aren't pure, you must build them carefully, and they can't participate in
automatically recalculating values in the app. You can use these functions only within
behavioral formulas.
Record scope
Some functions operate by evaluating a formula across all the records of a table
individually. The formula's result is used in various ways:
Inside these formulas, you can reference the fields of the record being processed. Each
of these functions creates a "record scope" in which the formula is evaluated, where the
fields of the record are available as top-level identifiers. You can also reference control
properties and other values from throughout your app.
Power Apps
Set( Products,
Table(
To determine whether any of any of these products had more requested than is
available:
Adding to this example, we can calculate how much of each product to order:
Power Apps
AddColumns(
Here we are adding a calculated column to the result. AddColumns has its own record
scope that it uses to calculate the difference between what has been requested and
what is available.
Finally, we can reduce the result table to just the columns that we want:
Power Apps
ShowColumns(
AddColumns(
),
"Product",
"Quantity To Order"
Note that in the above, we used double quotes (") in some places and single quotes (')
in other places. Single quotes are required when referencing the value of an object, such
as a field or table, in which the name of the object contains a space. Double quotes are
used when we are not referencing the value of an object but instead talking about it,
especially in situations in which the object does not yet exist, as in the case of
AddColumns.
Disambiguation
Field names added with the record scope override the same names from elsewhere in
the app. When this happens, you can still access values from outside the record scope
with the @ disambiguation operator:
To access values from nested record scopes, use the @ operator with the name of
the table being operated upon using this pattern:
Table[@FieldName]
To access global values, such as data sources, collections, and context variables,
use the pattern [@ObjectName] (without a table designation).
If the table being operated upon is an expression, such as Filter( Table, ... ), then the
disambiguation operator cannot be used. Only the innermost record scope can access
fields from this table expression, by not using the disambiguation operator.
In addition, define a context variable named Value with this formula: UpdateContext(
{Value: "!"} )
Ungroup(
ForAll( X,
ForAll( Y,
),
"Value"
What is going on here? The outermost ForAll function defines a record scope for X,
allowing access to the Value field of each record as it is processed. It can be accessed by
simply using the word Value or by using X[@Value].
The innermost ForAll function defines another record scope for Y. Since this table also
has a Value field defined, using Value here refers to the field in Y's record and no longer
the one from X. Here, to access X's Value field, we must use the longer version with the
disambiguation operator.
Since Y is the innermost record scope, accessing fields of this table do not require
disambiguation, allowing us to use this formula with the same result:
Power Apps
Ungroup(
ForAll( X,
ForAll( Y,
),
"Value"
All the ForAll record scopes override the global scope. The Value context variable we
defined isn't available by name without the disambiguation operator. To access this
value, use [@Value].
Ungroup flattens the result because nested ForAll functions result in a nested result
table.
Single-column tables
To operate on a single column from a table, use the ShowColumns function as in this
example:
Power Apps
For a shorter alternative, specify Table.Column, which extracts the single-column table of
just Column from Table. For example, this formula produces exactly the same result as
using ShowColumns.
Power Apps
Products.Product
Inline records
You express records by using curly braces that contain named field values. For example,
you can express the first record in the table at the start of this topic by using this
formula:
You can also embed formulas within other formulas, as this example shows:
You can nest records by nesting curly braces, as this example shows:
{ 'Quantity': { 'OnHand': ThisItem.QuantOnHand, 'OnOrder': ThisItem.QuantOnOrder }
Enclose each column name that contains a special character, such as a space or a colon,
in single quotes. To use a single quote within a column name, double it.
Note that the value in the Price column doesn't include a currency symbol, such as a
dollar sign. That formatting will be applied when the value is displayed.
Inline tables
You can create a table by using the Table function and a set of records. You can express
the table at the start of this topic by using this formula:
Power Apps
Table(
Power Apps
Table(
{ Name: "Chocolate",
7 Note
Microsoft Power Fx is the new name for the canvas apps formula language. These
articles are work in progress as we extract the language from canvas apps, integrate
it with other Microsoft Power Platform products, and make it available as open
source. Start with the Microsoft Power Fx Overview for an introduction to the
language.
Power Apps
In this context, what does it mean when the user selects a Button control? No value has
changed, so there is nothing new to calculate. Excel has no equivalent to a Button
control.
By selecting a Button control, the user initiates a sequence of actions, or behaviors, that
will change the state of the app:
Because these functions change the state of the app, they can't be automatically
recalculated. You can use them in the formulas for the OnSelect, OnVisible, OnHidden,
and other On... properties, which are called behavior formulas.
Power Apps
UpdateContext( { x: 1 } ); Back()
Actions are performed in the order in which they appear in the formula. The next
function won't start until the current function has completed. If an error occurs,
subsequent functions might not start.
Variables
Article • 02/23/2023 • 16 minutes to read
7 Note
Microsoft Power Fx is the new name for the canvas apps formula language. These
articles are work in progress as we extract the language from canvas apps, integrate
it with other Microsoft Power Platform products, and make it available as open
source. Start with the Microsoft Power Fx Overview for an introduction to the
language.
If you've used another programming tool, such as Visual Basic or JavaScript, you may be
asking: Where are the variables? Microsoft Power Fx is a little different and requires a
different approach. Instead of reaching for a variable when you write a formula, ask
yourself: What would I do in a spreadsheet?
In other tools, you may have explicitly performed a calculation and stored the result in a
variable. However, Power Fx and Excel both automatically recalculate formulas as the
input data changes, so you usually don't need to create and update variables. By taking
this approach whenever possible, you can more easily create, understand, and maintain
your app.
In some cases, you'll need to use variables in Power Fx, which extends Excel's model by
adding behavior formulas. These formulas run when, for example, a user selects a
button. Within a behavior formula, it's often helpful to set a variable to be used in other
formulas.
In general, avoid using variables. But sometimes only a variable can enable the
experience you want. Variables are implicitly created and typed when they appear in
functions that set their values.
Excel
Let's review how Excel works. A cell can contain a value, such as a number or a string, or
a formula that's based on the values of other cells. After the user enters a different value
into a cell, Excel automatically recalculates any formulas that depend on the new value.
You don't have to do any programming to enable this behavior.
In the following example, cell A3 is set to the formula A1+A2. If A1 or A2 changes, A3
automatically recalculates to reflect the change. This behavior requires no coding
outside of the formula itself.
Excel doesn't have variables. The value of a cell that contains a formula changes based
on its input, but there's no way to remember the result of a formula and store it in a cell
or anywhere else. If you change a cell's value, the entire spreadsheet may change, and
any previously calculated values are lost. An Excel user can copy and paste cells, but
that's under the user's manual control and isn't possible with formulas.
Power Fx
Logic that you create in Power Fx behaves very much like Excel. Instead of updating
cells, you can add controls wherever you want on a screen and name them for use in
formulas.
For example in Power Apps, you can replicate the Excel behavior in an app by adding a
Label control, named Label1, and two Text input controls, named TextInput1 and
TextInput2. If you then set the Text property of Label1 to TextInput1 + TextInput2, it will
always show the sum of whatever numbers are in TextInput1 and TextInput2
automatically.
Notice that the Label1 control is selected, showing its Text formula in the formula bar at
the top of the screen. Here we find the formula TextInput1 + TextInput2. This formula
creates a dependency between these controls, just as dependencies are created
between cells in an Excel workbook. Let's change the value of TextInput1:
The formula for Label1 has been automatically recalculated, showing the new value.
In Power Fx, you can use formulas to determine not only the primary value of a control
but also properties such as formatting. In the next example, a formula for the Color
property of the label will automatically show negative values in red. The If function
should look familiar from Excel:
By using your device's GPS, a map control can display your current location with a
formula that uses Location.Latitude and Location.Longitude. As you move, the
map will automatically track your location.
Other users can update data sources. For example, others on your team might
update items in a SharePoint list. When you refresh a data source, any dependent
formulas are automatically recalculated to reflect the updated data. Furthering the
example, you might set a gallery's Items property to the formula Filter(
SharePointList ), which will automatically display the newly filtered set of records.
Benefits
Using formulas to build apps has many advantages:
If you know Excel, you know Power Fx. The model and formula language are the
same.
If you've used other programming tools, think about how much code would be
required to accomplish these examples. In Visual Basic, you'd need to write an
event handler for the change event on each text-input control. The code to
perform the calculation in each of these is redundant and could get out of sync, or
you'd need to write a common subroutine. In Power Fx, you accomplished all of
that with a single, one-line formula.
To understand where Label1's text is coming from, you know exactly where to look:
the formula in the Text property. There's no other way to affect the text of this
control. In a traditional programming tool, any event handler or subroutine could
change the value of the label, from anywhere in the program. This can make it hard
to track down when and where a variable was changed.
If the user changes a slider control and then changes their mind, they can change
the slider back to its original value. And it's as if nothing had ever changed: the
app shows the same control values as it did before. There are no ramifications for
experimenting and asking "what if," just as there are none in Excel.
In general, if you can achieve an effect by using a formula, you'll be better off. Let the
formula engine in Power Fx do the work for you.
Display Description
You'll sometimes need a variable for your app to behave the way you want. But the
approach comes with caveats:
You must manually update the running total. Automatic recalculation won't do it
for you.
The running total can no longer be calculated based on the values of other
controls. It depends on how many times the user selected the Add button and
what value was in the text-input control each time. Did the user enter 77 and select
Add twice, or did they specify 24 and 130 for each of the additions? You can't tell
the difference after the total has reached 154.
Changes to the total can come from different paths. In this example, both the Add
and Clear buttons can update the total. If the app doesn't behave the way you
expect, which button is causing the problem?
You set the value of the global variable with the Set function. Set( MyVar, 1 ) sets
the global variable MyVar to a value of 1.
You use the global variable by referencing the name used with the Set function. In
this case, MyVar will return 1.
Global variables can hold any value, including strings, numbers, records, and
tables.
1. Add a text-input control, named TextInput1, and two buttons, named Button1 and
Button2.
2. Set the Text property of Button1 to "Add", and set the Text property of Button2 to
"Clear".
3. To update the running total whenever a user selects the Add button, set its
OnSelect property to this formula:
Set( RunningTotal, RunningTotal + TextInput1 )
The first time that a user selects the Add button and Set runs, RunningTotal is set
to the value RunningTotal + TextInput1.
4. To set the running total to 0 whenever the user selects the Clear button, set its
OnSelect property to this formula:
Set( RunningTotal, 0 )
This formula will automatically be recalculated and show the user the value of
RunningTotal as it changes based on the buttons that the user selects.
6. Preview the app, and we have our adding machine as described above. Enter a
number in the text box and press the Add button a few times. When ready, return
to the authoring experience using the Esc key.
7. To show the global variable's value, select the File menu, and select Variables in
the left-hand pane.
8. To show all the places where the variable is defined and used, select it.
Types of variables
Power Fx has two types of variables:
Global App Simplest to use. Holds a number, text string, Boolean, Set
variables record, table, etc. that can be references from anywhere in
the app.
Collections App Holds a table that can be referenced from anywhere in the Collect
Context Screen Great for passing values to a screen, much like parameters UpdateContext
For example, you might have a button control with an OnSelect formula equal to Set( X,
1 ). This formula establishes X as a variable with a type of number. You can use X in
formulas as a number, and that variable has a value of blank after you open the app but
before you select the button. When you select the button, you give X the value of 1.
If you added another button and set its OnSelect property to Set( X, "Hello" ), an error
would occur because the type (text string) doesn't match the type in the previous Set
(number). All implicit definitions of the variable must agree on type. Again, all this
happened because you mentioned X in formulas, not because any of those formulas
had actually run.
You remove a variable by removing all the Set, UpdateContext, Navigate, Collect, or
ClearCollect functions that implicitly establish the variable. Without these functions, the
variable doesn't exist. You must also remove any references to the variable because they
will cause an error.
You can store the contents of a variable in a data source by using the Patch or Collect
functions. You can also store values in collections on the local device by using the
SaveData function.
When the user opens the app, all variables have an initial value of blank.
Reading variables
You use the variable's name to read its value. For example, you can define a variable
with this formula:
Set( Radius, 12 )
Then you can simply use Radius anywhere that you can use a number, and it will be
replaced with 12:
Pi() * Power( Radius, 2 )
If you give a context variable the same name as a global variable or a collection, the
context variable takes precedence. However, you can still reference the global variable
or collection if you use the disambiguation operator [@Radius].
You implicitly establish and set context variables by using the UpdateContext or
Navigate function. When the app starts, the initial value of all context variables is
blank.
You update context variables with records. In other programming tools, you
commonly use "=" for assignment, as in "x = 1". For context variables, use { x: 1 }
instead. When you use a context variable, use its name directly without the record
syntax.
You can also set a context variable when you use the Navigate function to show a
screen. If you think of a screen as a kind of procedure or subroutine, this approach
resembles parameter passing in other programming tools.
Except for Navigate, context variables are limited to the context of a single screen,
which is where they get their name. You can't use or set them outside of this
context.
Context variables can hold any value, including strings, numbers, records, and
tables.
1. Add a text-input control, named TextInput1, and two buttons, named Button1 and
Button2.
2. Set the Text property of Button1 to "Add", and set the Text property of Button2 to
"Clear".
3. To update the running total whenever a user selects the Add button, set its
OnSelect property to this formula:
The first time that the user selects the Add button and UpdateContext runs,
RunningTotal is set to the value RunningTotal + TextInput1.
4. To set the running total to 0 whenever the user selects the Clear button, set its
OnSelect property to this formula:
UpdateContext( { RunningTotal: 0 } )
This formula will automatically be recalculated and show the user the value of
RunningTotal as it changes based on the buttons that the user selects.
6. Preview the app and we have our adding machine as described above. Enter a
number in the text box and press the Add button a few times. When ready, return
to the authoring experience using the Esc key.
7. You can set the value of a context variable while navigating to a screen. This is
useful for passing "context" or "parameters" from one screen to another. To
demonstrate this technique, insert a screen, insert a button, and set its OnSelect
property to this formula:
8. To show the value of the context variable, select the File menu, and then select
Variables in the left-hand pane.
9. To show where the context variable is defined and used, select it.
Use a collection
Finally, let's look at creating our adding machine with a collection. Since a collection
holds a table that is easy to modify, we will make this adding machine keep a "paper
tape" of each value as they are entered.
Create and set collections by using the ClearCollect function. You can use the
Collect function instead, but it will effectively require another variable instead of
replacing the old one.
A collection is a kind of data source and, therefore, a table. To access a single value
in a collection, use the First function, and extract one field from the resulting
record. If you used a single value with ClearCollect, this will be the Value field, as in
this example:
1. Add a Text input control, named TextInput1, and two buttons, named Button1 and
Button2.
2. Set the Text property of Button1 to "Add", and set the Text property of Button2 to
"Clear".
3. To update the running total whenever a user selects the Add button, set its
OnSelect property to this formula:
Collect( PaperTape, TextInput1.Text )
The mere existence of this formula establishes PaperTape as a collection that holds
a single-column table of text strings. You can reference PaperTape anywhere in this
app. Whenever a user opens this app, PaperTape is an empty table.
When this formula runs, it adds the new value to the end of the collection. Because
we're adding a single value, Collect automatically places it in a single-column
table, and the column's name is Value, which you'll use later.
4. To clear the paper tape when the user selects the Clear button, set its OnSelect
property to this formula:
Clear( PaperTape )
5. To display the running total, add a label, and set its Text property to this formula:
8. To display the paper tape, insert a Data table control, and set its Items property to
this formula:
PaperTape
In the right-hand pane, select Edit fields and then select Add field, select Value
column and then select Add to show it.
9. To see the values in your collection, select Collections on the File menu.
10. To store and retrieve your collection, add two additional button controls, and set
their Text properties to Load and Save. Set the OnSelect property of the Load
button to this formula:
You need to clear the collection first because LoadData will append the stored
values to the end of the collection.
11. Set the OnSelect property of the Save button to this formula:
12. Preview again by pressing the F5 key, enter numbers in the text-input control, and
select buttons. Select the Save button. Close and reload the app, and select the
Load button to reload your collection.
Error handling
Article • 02/23/2023 • 13 minutes to read
7 Note
The behavior that this article describes is available only when the Formula-level
error management preview feature through Settings > Upcoming features >
Preview is turned on. More information: Controlling which features are enabled
Errors happen. Networks go down, storage fills up, unexpected values flow in. It's
important that your logic continues to work properly in the face of potential issues.
By default, errors flow through the formulas of an app and are reported to the end user
of the app. In this way, the end user knows something unexpected happened, they can
potentially fix the problem themselves with a different input, or they can report the
problem to the owner of the app.
Detecting and handling an error. If there's a chance an error may occur, the app's
formulas can be written to detect the error condition and retry the operation. The
end user doesn't need to be concerned that an error occurred because the maker
took the possibility into account. This is done with the IfError, IsError, and
IsErrorOrBlank functions within a formula.
Reporting an error. If an error isn't handled in the formula where it was
encountered, the error is then bubbled up to the App.OnError handler. Here, the
error can no longer be replaced as it has already occurred and is a part of formula
calculations. But you can use App.OnError to control how the error is reported to
the end user, including suppressing the error reporting all together. App.OnError
also provides a common choke point for error reporting across the entire app.
Creating and rethrowing an error. Finally, you may detect an error condition with
your own logic, a condition that is specific to your app. Use the Error function to
create custom errors. The Error function is also used to rethrow an error after
being interrogated in IfError or App.OnError.
Getting started
Let's start with a simple example.
Power Apps
1/Value( TextInput1.Text )
We have an error because the default text of a TextInput control is "Text input" , which
can't be converted to a number. By default this is a good thing: the end user will get a
notification that something isn't working as expected in the app.
Obviously, we don't want an error to greet the user each time they start this app. Likely
"Text input" isn't the right default for the text input box anyway. To remedy this, let's
Power Apps
Blank()
Hmm, now we have a different error. Mathematical operations with blank, such as
division, will coerce the blank value to a zero. And that is now causing a division by zero
error. To remedy this, we need to decide what the appropriate behavior is for this
situation in this app. The answer may be to show blank when the text input is blank. We
can accomplish this by wrapping our formula with the IfError function:
Power Apps
Now the error is replaced with a valid value and the error banner has gone away. But, we
may have overshot, the IfError we used covers all errors, including typing in a bad value
such as "hello" . We can address this by tuning our IfError to handle the division by
zero case only with and rethrowing all other errors:
Power Apps
So, let's run our app and try some different values.
Without any value, as when the app starts, there's no answer displayed as the default
value is blank, but there also no error shown as the IfError replaces the division by zero
error.
If we type in a 4, we get the expected result of 0.25:
And if we type in something illegal, like hello , then we'll receive an error banner:
This is a simple introductory example. Error handling can be done many different ways,
depending on the needs of the app:
1. Instead of an error banner, we could have shown "#Error" in the label control with
the formula. To keep the types of the replacements compatible with the first
argument to IfError we need to explicitly convert the numerical result to a text
string with the Text function.
Power Apps
2. Instead of wrapping this specific instance with IfError we could have written a
centralized App.OnError handler. We can't replace the string shown with "#Error"
as the error has already happened and App.OnError is only provided to control
reporting.
Power Apps
Error propagation
Errors flow through formulas much as they do in Excel. For example in Excel, if cell A1
has the formula =1/0 , then A1 will display the error value #DIV0! :
If cell A2 refers to A1 with a formula such as =A1*2 , then the error propagates through
that formula too:
The error replaces the value that would have otherwise been calculated. There's no
result for the multiplication in cell A2 , only the error from the division in A1 .
Power Fx works the same way. In general, if an error is provided as an argument to a
function or operator, the operation won't take place and the input error will flow
through as the result of the operation. For example, Mid( Text( 1/0 ), 1, 1 ) will
return a Division by Zero error, as the inner most error passes through the Text function
and Mid function:
In general, errors don't flow through Power Apps control properties. Let's extend the
previous example with an additional control that displays if the first label's Text
property is an error state:
It's fine that errors don't propagate through a control because the system will observe
errors on the input to all control properties. The error won't be lost.
Most functions and operators follow the "error in, error out" rule, but there are some
exceptions. The functions IsError, IsErrorOrBlank, and IfError are designed for working
with errors so they may not return an error even if one is passed into them.
Observing errors
Errors aren't observed until their value is used.
As a result, the If and Select functions may also not return an error if one is passed in.
Consider the formula If( false, 1/0, 3 ) . There's a division by zero error present in
this formula, but since the If isn't taking that branch because of the false , Power Fx
and Power Apps won't report an error:
Using the Set function with an error won't report an error at the point the error is placed
into the variable. For example in Power Apps, here's a formula in App.OnStart that
places a division by zero error into the variable x :
No error is reported, because x isn't being referenced. However, the moment we add a
label control and set its Text property to x , the error is displayed:
You can observe errors within a formula with the IfError, IsError, and IsErrorOrBlank
functions. With these functions, you can return an alternate value, take alternate action,
or modify the error before it's observed and reported.
Reporting errors
After an error is observed, the next step is to report the error to the end user.
Unlike Excel, there isn't always a convenient place to show an error result, as the result
of a formula may drive a property such as X and Y coordinates of a control for which
there's no convenient place to show some text. Each Power Fx host controls how errors
are ultimately displayed to the end user and how much control the maker has over this
process. In Power Apps, an error banner is shown and App.OnError is used to control
how the error is reported.
It's important to note that App.OnError can't replace the error in the same way that
IfError can. At the point that App.OnError is executed, the error has already happened,
and the result has propagated through other formulas. App.OnError only controls how
the error is reported to the end user and provides a hook for the maker to log the error
if desired.
The scope variables FirstError and AllErrors provide context information about the error
or errors. This provides information on the kind of error and where the error originated
and where it was observed.
In this case, for example, the grid control is showing what is in the T table. Each button
select changes the state in this table with two Patch calls:
In a chained behavior formula, actions don't stop after the first error. Let's modify our
example to pass an invalid index number in the first Patch call. The second Patch
continues on despite this earlier error. The first error is reported to the end user, and
shown as an error in Studio on the control:
IfError can be used to stop execution after an error. Similar to the If function, the third
argument to this function provides a place to put actions that should be executed only if
there's no error:
If an error is encountered during one of the iterations of ForAll, the rest of the iterations
won't stop. ForAll is designed to execute each iteration independently, allowing for
parallel execution. When the ForAll is complete, an error will be returned, which contains
all the errors encountered (by examining AllErrors in IfError or App.OnError).
For example, the following formula will result in ForAll returning two errors (for the
division by zero for Value of 0, twice) and Collection will have three records (for when
Value isn't 0): [1, 2, 3] .
Power Apps
Clear( Collection );
By default, the first error is reported to the end user. In this example, both Patch calls
will fail, the second with a division by zero error. Only the first error (about index) is
shown to the user:
The IfError function and App.OnError can access all the errors encountered with the
AllErrors scope variable. In this case, we can set this to a global variable and look at
both errors encountered. They appear in the table in the same order in which they were
encountered:
Multiple errors can be returned in non-behavior formulas too. For example, using the
Patch function with a batch of records to update can return multiple errors, one for each
record that fails.
Errors in tables
As we saw earlier, errors can be stored in variables. Errors can also be included in data
structures, such as tables. This is an important so that an error on any one record can't
invalidate the entire table.
The calculation in AddColumns has encountered a division by zero error for one of the
values. For that one record, the Reciprocal column has an error value (division by zero)
but the other records don't and are fine. IsError( Index( output, 2 ) ) returns false
and IsError( Index( output, 2 ).Value ) returns true.
If an error occurs when filtering a table, the entire record is an error but still returned in
the result so that the end user knows something was there and there's a problem.
Take this example. Here, the original table has no errors, but the act of filtering creates
an error whenever Value is equal to 0:
The values -5 and -3 are properly filtered out. The values 0 result in an error in
processing the filter, and so it's unclear if the record should be included or not in the
result. To maximize transparency for end users and help makers debug, we include an
error record in place of the original. In this case, IsError( Index( output, 2 ) ) returns
true.
Each of these functions will return an error value as the result of the operation.
Errors can be detected with IsError and replaced or suppressed with IfError and
App.OnError as usual.
After the operation, the Errors function will also return the errors for previous
operations. This can be useful for displaying the error message on a form screen
without needing to capture the error in a state variable.
For example, this formula will check for an error from Collect and display a custom error
message:
Power Apps
The Errors function also returns information about past errors during runtime
operations. It can be useful for displaying an error on a form screen without needing to
capture the error in a state variable.
Rethrowing errors
Sometimes some potential errors are expected and can be safely ignored. Inside IfError
and App.OnError, if an error is detected that should be passed on to the next higher
handler, it can be rethrown with Error( AllErrors ) .
If you're creating your own errors, it's recommended that you use values above 1000 to
avoid potential conflicts with future system error values.
BadRegex 15 Invalid regular expression. Check the syntax used with the
IsMatch, Match, or MatchAll functions.
Conflict 6 The record being updated has already been changed at the
source and the conflict needs to be resolved. A common solution
is to save any local changes, refresh the record, and reapply the
changes.
CreatePermission 3 The user doesn't have create record permission for the data
source. For example, the Collect function was called.
DeletePermissions 5 The user doesn't have delete record permission for the data
source. For example, the Remove function was called.
EditPermissions 4 The user doesn't have create record permission for the data
source. For example, the Patch function was called.
GeneratedValue 9 A value was erroneously passed to the server for a field that is
automatically calculated by the server.
InsufficientMemory 21 There isn't enough memory or storage on the device for the
operation.
Internal 26 System error. There was an internal problem with one of the
functions.
ReadPermission 19 The user doesn't have read record permission for the data source.
Sync 1 An error was reported by the data source. Check the Message
column for more information.
7 Note
Microsoft Power Fx is the new name for the canvas apps formula language. These
articles are work in progress as we extract the language from canvas apps, integrate
it with other Microsoft Power Platform products, and make it available as open
source. Start with the Microsoft Power Fx Overview for an introduction to the
language.
Both while building and running logic, the text displayed by Power Fx will be displayed
in the appropriate languages. Typing in and displaying dates and numbers is adapted
for your particular language and region.
For example, some regions of the world use a . (dot or period) as the decimal separator
while others use a , (comma). This is what Excel does too. This is commonly not done in
other programming languages, using a canonical . as the decimal separator for all users
worldwide. To be as approachable as possible for makers at all levels, it is important that
3,14 is a decimal number for a person in France who has used that syntax all their lives.
The apps you create can be globally aware as well. Use the Language, Text, and Value,
DateValue, and other functions to adapt what is displayed and used as input in different
languages.
Language settings
When using the native studio or a native player, the language used is provided by the
host operating system. For Windows, this setting can be controlled under "All Settings"
and then "Time & language" settings. Windows also allows you to specify the characters
to use for the decimal separator, overriding the language setting.
When using the web experiences, the language used is provided by the browser. Most
browser default to the host operating system's setting with some also providing a way
to set the language manually.
Authoring environment
The authoring environment adapts to the language setting of the author. The app itself
is stored in a language agnostic manner, so that authors using different languages can
edit the same app.
Names in formulas
Most elements in formula are always in English:
As the authoring experience is localized, control and other object names will appear in
the native language of the author. In Spanish, some of the control names appear as:
When you insert one of these controls into your app, their name will default to English.
This change is done for consistency with the control property names and the rest of the
formula. For example, Casilla listed above is inserted as Checkbox1.
After a control is inserted, you can change the name to whatever you like. While
selected, the far left-hand side of the "Content" ribbon displays the name of the control.
Selecting this name drops down a text box where you can edit the name:
If you like, here you can rename the control to Casilla1. The red squiggly, in this case
displayed by a browser, is because the name isn't a Spanish word and is of no concern.
Control names
Collection names
Context variable names
Author's language Power Apps decimal Power Apps list Power Apps chaining
decimal separator separator separator operator
The change in the Power Apps list separator is consistent with what happens to the Excel
list separator. It impacts:
For example, consider the following formula expressed in a language and region that
uses dot or period as the decimal separator, such as Japan or the United Kingdom:
Now view this same formula in a language and region where a comma is used for the
decimal separator, such as France or Spain:
The highlight shows the operators that change between the two versions. The property
selection operator . (dot or period) in Slider1.Value is always the same, no matter what
the decimal separator is.
Internally the formula doesn't change, all that changes is how it's displayed and edited
by the author. Two different authors using two different languages can view and edit the
same formula, with each seeing the appropriate separators and operators for their
language.
Language function
The Language function returns the language tag of the current user. For example, this
function returns "en-GB" for users in Great Britain and "de-DE" for users in Germany.
Among other things, you can use Language to display translated text for your users.
Your app can include a table of translated values in your app:
And then use a formula such as the following to pull translated strings from the table:
Power Apps
LookUp( Table1, TextID = "Hello" && (LanguageTag = Left( Language(), 2 ) ||
IsBlank( LanguageTag ))).LocalizedText
Translated strings in other languages could be longer than they are in your language. In
many cases, the labels and other elements that display the strings in your user interface
will need to be wider to accommodate.
For more information, see the documentation for the Language function.
The Text function formats numbers and dates using the language setting of the user.
Text requires a format string to know how you want to format the number or date. This
format string can take one of two forms:
The "[$-en-US]" on the front of the custom format string tells Text in which language to
interpret the custom format string. This string is inserted for you and defaults to your
authoring language. Normally you won't need to change this string. It's useful when
authors from different languages are editing the same app.
The third argument to Text specifies which language to use for the result of the
function. The default is the language setting of the current user.
For more information, see the documentation for the Text function.
If you have used Excel, all of these functions are combined in the single Value function.
They're broken out here since Power Apps has separate types for date/time values and
numbers.
String, required: A string from the user. For example, a string types into a Text
input control and read from the control with the Text property.
Language, optional: The language in which to interpret the String. By default, the
language setting of the user.
For example:
For more information, see the documentation for the Value and DateValue, TimeValue,
and DateTimeValue functions.
Among other things, use these functions to provide a Dropdown control with a list of
choices.
For more information, see the documentation for the Calendar and Clock functions.
Untyped object data type
(experimental)
Article • 12/16/2022 • 5 minutes to read
) Important
Untyped object is a data type in Power Fx that can hold any data structure, complex or
simple. It can't be used directly and requires explicit conversion to a data type. Fields in
records in an untyped object can be accessed using the dot notation, and existence of
fields is only verified at runtime.
Untyped object is the return type of specific untyped providers. Currently, only the
ParseJSON() function returns untyped object.
Simple Types
The value of a variable of type untyped object can't be used directly. You always have to
correctly type it using the corresponding type constructor.
The following examples convert the value of an untyped object variable named
UOValue .
Power Apps
Text(UOValue)
Power Apps
Value(UOValue)
The following table lists the data types and corresponding functions to convert untyped
object to that data type.
Boolean Boolean() When converting untyped object to boolean, the value may need
to be converted to text or number first if the untyped object
represents the boolean in those types.
Color ColorValue() or Colors can be represented in Cascading Style Sheet (CSS) color
RGBA() definition notation as a string, or as individual RGBA components.
The untyped object can be converted directly from a Cascading
Style Sheet (CSS) color definition string using the ColorValue()
function, or from individual RGBA numbers into color using the
RGBA() function.
Date, DateValue(), Date, time and datetime can be directly converted from untyped
DateTime, TimeValue() or object to their respective type, when represented in ISO 8601
Time DateTimeValue() format. Other formats must first be converted to text using the
Text() function and then passed into the DateValue(), TimeValue()
or DateTimeValue() function that by default will use the language
of the current user's settings to interpret the date and time.
HyperLink, Text() These data types are text data types, and can be converted to text
Image, and then used in Power Fx.
Media
Choice, Switch() or If() Choices and two options are presented as localized strings in
Two Power Fx. Choices are backed by a number and two options as
Option booleans. There's no direct conversion from boolean, number or
string to a choice or two option, but the Switch() or If() functions
can be used on the boolean, text or number value to correctly
assign the choice or two option value.
Table Table() and An untyped object can represent an array, which can be
ForAll() converted into a table. These objects can be arrays of records, or
arrays of values that are effectively single-column tables. ForAll()
can be used to create a table with fully typed records. Review the
examples further down this article for more information.
Record Types
You can access fields on a variable representing an untyped object record using regular
dot-notation used for records. However, the existence of the fields won't be verified
until runtime. As a result, there's also no intellisense available. If a field doesn't exist or
has an underlying null value, accessing it will result in a Blank() value.
Each field on the record is also of type untyped object, and needs to be properly typed.
The field can be an untyped record of simple type. In case it's a record, you can chain
the dot-notation. If any field in the chain doesn't exist, Blank() is returned.
The following examples use fields from an untyped object variable named UORecord .
Power Apps
Text(UORecord.StringField)
Power Apps
Value(UORecord.Field.ChildField)
In case a field name consists of an invalid identifier name, for example when the field
names starts with a number or contains invalid characters such as a hyphen, you can put
the field names in single quotes:
Power Apps
untyped.'01'
untyped.'my-field'
Arrays
An untyped object variable can contain an array. Even though the array could be either
an array of records or array of simple types, converting the untyped object array to a
table using the Table() function will always result in a single-column table of untyped
objects. Functions such as ForAll() and Index() do not require you to first create a Table()
and as result don't require you to use the single-column Value field,
For example, to get the second number in an array of untyped object containing
number values ( [1, 2, 3] ), the following formula can be used to retrieve the second
row in the table and convert column to a number:
Power Apps
If the untyped object was converted to a Table() first, the second row in the result
single-column table is a Value column containing the untyped object:
Power Apps
For an array of records that have a text column called Field , the same logic applies. The
untyped object can be accessed directly, or if using the Table() function will result in a
single-column table of untyped object.
The Field column can be access directly from the untyped object returned by the
Index() function.
Power Apps
When using the Table() function, first retrieve the single-column Value column to get
the untyped object, then access the Field column:
Power Apps
To convert an array of records to a typed table, you can use the ForAll() function and
convert each individual field.
Power Apps
If the untyped object is first converted to a table, again, the resulting single-column
table of untyped object will require you to use the Value column to get the fields.
Power Apps
) Important
Power Fx allows makers to read JSON into an Untyped object using the ParseJSON
function.
JSON
"Quantity" : 46,
"ReleaseDate" : "2022-09-01",
"AvailableForPreOrder" : true
Each of the fields can be accessed using the dot notation on the Untyped object value
returned from ParseJSON.
Power Apps
Set( untyped, ParseJSON( jsonStringVariable ) );
In case a field name consists of an invalid identifier name, for example when the field
names starts with a number or contains invalid characters such as a hyphen, you can put
the field names in single quotes:
Power Apps
untyped.'01'
untyped.'my-field'
Power Fx won't evaluate the existence of the field until the formula is run. This allows
flexibility in the incoming JSON. For example, the previous JSON may sometimes
contain an extra field called Discount . But in our previous example, this field isn't
present. Writing a formula that uses the Discount field won't result in any errors, during
the app making process or when users use the app. If the field is missing when the
formula runs, the value will just result in a Blank() value.
7 Note
JSON supports null values for fields. These will also result in Blank() values.
Currently, there is no distinction in Power Fx between a missing field, or a field that
has the value null .
As accessing fields on Untyped objects isn't evaluated when writing the formula, there's
also no Intellisense available. Both JSON and Power Fx are case sensitive, so take extra
care in writing out field names.
JSON values don't have to be in a record-style notation. Valid JSON can be just a value,
such as "text value" , true or 123.456 . In such a case, the Untyped object that
ParseJSON returns is the value itself and the dot notation isn't used.
Power Apps
Finally, JSON supports nested records. Converting such JSON to Untyped object results
in nested objects, and the dot notation can be used to traverse the hierarchy.
JSON
"Version" : 1,
"RootElement" : {
"Parent" : {
"Child" : {
When converting this JSON string to an Untyped object variable named jsonObject , the
fields can be accessed using the dot notation.
Power Apps
If any of the fields in the dot notation expression don't exist, Blank() will be returned.
JSON
"OrderNumber" : "SO000010",
"CustomerID" : "CUST0126",
"OrderLines" : [
"Quantity" : 3
},
"Quantity" : 5
This JSON contains a record with a field named OrderLines which contains an array of
records. Each record has two fields: Item and Quantity . If the JSON is converted into an
Untyped object using the ParseJSON function and set to a variable named jsonOrder ,
we can access the individual order lines in several ways.
Power Apps
You can retrieve individual records and values using the Index() function. For example, to
get the second record in the OrderLines field, then access the Quantity field and
convert it to a value.
Power Apps
You can convert the array of order lines directly to a table. This will create a single-
column table with an Untyped object representing the record.
Power Apps
Single column table 'orderLines' now has a 'Value' column that represents the Untyped
object. To use any of the fields from a record in this table, use the dot notation to access
the specific JSON field on the Untyped object in the Value column.
Power Apps
To make the use of the order line records easier and more straightforward in other parts
of your app, you can convert the whole Untyped object to an entirely typed record
using the ForAll() function. Providing the Untyped object directly to ForAll() means you
can access the object fields directly instead of using the single-column Value field.
Power Apps
The new typedOrderLines variable is now a fully typed Power Fx table with the following
columns and values:
Item Quantity
"Widget 1" 3
"Widget 2" 5
The previous examples use arrays of records, but JSON can also contain arrays of just
values. Consider the following example that is a valid JSON string containing an array of
three strings.
JSON
We can retrieve one of the items from the array using the Index() function, and convert
it to text.
Power Apps
Functions take parameters, perform an operation, and return a value. For example,
Sqrt(25) returns 5. Functions are modeled after Microsoft Excel functions. Some
functions have side effects, such as SubmitForm, which are appropriate only in a
behavior formula such as Button.OnSelect.
Signals return information about the environment. For example, Location returns
the device's current GPS coordinates. Signals don't take parameters or have side
effects.
Enumerations return a pre-defined constant value. For example, Color is an
enumeration that has pre-defined values for Color.Red, Color.Blue, and so forth.
Common enumerations are included here; function-specific enumerations are
described with the function.
Named operators, such as ThisItem and Self, provide access to information from
within a container.
A
Abs – Absolute value of a number.
And – Boolean logic AND. Returns true if all arguments are true. You can also use the
&& operator.
App – Provides information about the currently running app and control over the app's
behavior.
As – Names the current record in gallery, form, and record scope functions such as
ForAll, With, and Sum.
B
Back – Displays the previous screen.
Blank – Returns a blank value that can be used to insert a NULL value in a data source.
C
Calendar – Retrieves information about the calendar for the current locale.
ClearCollect – Deletes all data from a collection and then adds a set of records.
ClearData – Clears a collection or all collections from an app host such as a local device.
Clock – Retrieves information about the clock for the current locale.
D
DataSourceInfo – Provides information about a data source.
Date – Returns a date/time value, based on Year, Month, and Day values.
DateDiff – Subtracts two date values, and shows the result in days, months, quarters, or
years.
E
EditForm – Resets a form control for editing of an item.
EndsWith – Checks whether a text string ends with another text string.
exactin – Checks if a text string is contained within another text string or table, case
dependent. Also used to check if a record is in a table.
Exit – Exits the currently running app and optionally signs out the current user.
F
Filter – Returns a filtered table based on one or more criteria.
Find – Checks whether one string appears within another and returns the location.
ForAll – Calculates values and performs actions for all records of a table.
G
GroupBy – Returns a table with records grouped together.
GUID – Converts a GUID string to a GUID value or creates a new GUID value.
H
HashTags – Extracts the hashtags (#strings) from a string.
I
If – Returns one value if a condition is true and another value if not.
in – Checks if a text string is contained within another text string or table, case
independent. Also used to check if a record is in a table.
IsToday – Checks whether a date/time value is sometime today in the user's time zone.
J
JSON - Generates a JSON text string for a table, a record, or a value.
L
Language – Returns the language tag of the current user.
Location – Returns your location as a map coordinate by using the Global Positioning
System (GPS) and other information.
M
Match – Extracts a substring based on a pattern. Regular expressions can be used.
N
Navigate – Changes which screen is displayed.
NewForm – Resets a form control for creation of an item.
Not – Boolean logic NOT. Returns true if its argument is false, and returns false if its
argument is true. You can also use the ! operator.
Now – Returns the current date/time value in the user's time zone.
O
Or – Boolean logic OR. Returns true if any of its arguments are true. You can also use
the || operator.
P
Param – Access parameters passed to a canvas app when launched.
Power – Returns a number raised to a power. You can also use the ^ operator.
Proper – Converts the first letter of each word in a string to uppercase, and converts the
rest to lowercase.
R
Radians - Converts degrees to radians.
Replace – Replaces part of a string with another string, by starting position of the string.
Reset – Resets an input control to its default value, discarding any user changes.
Revert – Reloads and clears errors for the records of a data source.
RGBA – Returns a color value for a set of red, green, blue, and alpha components.
S
SaveData – Saves a collection to an app host such as a local device.
Search – Finds records in a table that contain a string in one of their columns.
Sequence – Generate a table of sequential numbers, useful when iterating with ForAll.
Switch – Matches with a set of values and then evaluates a corresponding formula.
T
Table – Creates a temporary table.
Text – Converts any value and formats a number or date/time value to a string of text.
ThisItem – Returns the record for the current item in a gallery or form control.
ThisRecord – Returns the record for the current item in a record scope function, such as
ForAll, With, and Sum.
Time – Returns a date/time value, based on Hour, Minute, and Second values.
Trim – Removes extra spaces from the ends and interior of a string of text.
TrimEnds – Removes extra spaces from the ends of a string of text only.
Trunc – Truncates the number to only the integer portion by removing any decimal
portion.
U
Ungroup – Removes a grouping.
UpdateContext – Sets the value of one or more context variables of the current screen.
UTCNow – Returns the current date/time value in Coordinated Universal Time (UTC).
UTCToday – Returns the current date-only value in Coordinated Universal Time (UTC).
V
Validate – Checks whether the value of a single column or a complete record is valid for
a data source.
With – Calculates values and performs actions for a single record, including inline
records of named values.
Y
Year – Retrieves the year portion of a date/time value.
Abs, Exp, Ln, Power, Log, and Sqrt
functions in Power Apps
Article • 03/17/2023 • 2 minutes to read
Calculates absolute values, logarithms, square roots, and the results of raising e or any
number to specified powers.
Description
The Abs function returns the non-negative value of its argument. If a number is
negative, Abs returns the positive equivalent.
The Exp function returns e raised to the power of its argument. The transcendental
number e begins 2.7182818...
The Power function returns a number raised to a power. It's equivalent to using the ^
operator.
The Log function returns the logarithm of its first argument in the base specified by its
second argument (or 10 if not specified).
The Sqrt function returns the number that, when multiplied by itself, equals its
argument.
If you pass a single number, the return value is a single result based on the function
called. If you pass a single-column table that contains numbers, the return value is a
single-column table of results in a Value column, one result for each record in the
argument's table. If you have a multi-column table, you can shape it into a single-
column table, as working with tables describes.
If an argument would result in an undefined valued, the result is blank. Which can
happen with square roots and logarithms of negative numbers.
Syntax
Abs( Number )
Exp( Number )
Ln( Number )
Sqrt( Number )
Number - Required. Number to operate on.
Abs( SingleColumnTable )
Exp( SingleColumnTable )
Ln( SingleColumnTable )
Sqrt( SingleColumnTable )
Examples
Single number
Ln( 100 ) Returns the natural logarithm (base e) of the number 100. 4.605170...
Single-column table
The examples in this section use a data source that's named ValueTable and that
contains this data:
Value
-4
Sqrt( ValueTable ) Returns the square root A single-column table with a Value column
of each number in the containing the following values: 3, Blank(),
table 1.414213...
Step-by-step example
1. Add a Text input control, and name it Source.
2. Add a Label control, and set its Text property to this formula:
Returns information about the app's environment, such as where the user is located in
the world and which screen is displayed.
Signals typically return a record of information. You can use and store this information
as a record, or you can extract individual properties by using the . operator.
7 Note
The Acceleration and Compass functions return accurate values in a native player
such as on iOS or Android, but those functions return zero values as you create or
modify an app in the browser.
Acceleration
The Acceleration signal returns the device's acceleration in three dimensions relative to
the device's screen. Acceleration is measured in g units of 9.81 m/second2 or 32.2
ft/second2 (the acceleration that the Earth imparts to objects at its surface due to
gravity).
Property Description
Property Description
App.ActiveScreen Screen that's showing. Returns a screen object, which you can use to
reference properties of the screen or compare to another screen to
determine which screen is showing. You can use the Back or Navigate
function to change the screen that's showing.
Compass
The Compass signal returns the compass heading of the top of the screen. The heading
is based on magnetic north.
Property Description
Connection
The Connection signal returns the information about the network connection. When on
a metered connection, you may want to limit how much data you send or receive over
the network.
Property Description
Connection.Connected Returns a Boolean true or false value that indicates whether the device
is connected to a network.
Connection.Metered Returns a Boolean true or false value that indicates whether the
connection is metered.
Location
The Location signal returns the location of the device based on the Global Positioning
System (GPS) and other device information, such as cell-tower communications and IP
address.
When a user accesses the location information for the first time, the device may prompt
that user to allow access to this information.
Property Description
Location.Altitude Returns a number that indicates the altitude, measured in meters, above
sea level.
Location.Latitude Returns a number, from –90 to 90, that indicates the latitude, as measured
in degrees from the equator. A positive number indicates a location that's
north of the equator.
Location.Longitude Returns a number, from –180 to 180, that indicates the longitude, as
measured in degrees from Greenwich, England. A positive number indicates
a location that's east of Greenwhich.
Examples
In a baseball field, a pitcher throws a phone from the pitcher's mound to a catcher at
home plate. The phone is lying flat with respect to the ground, the top of the screen is
pointed at the catcher, and the pitcher adds no spin. At this location, the phone has
cellular network service that's metered but no WiFi. The PlayBall screen is displayed.
Acceleration.Y Returns the acceleration of the device front to 8.2, while the
back. The pitcher initially gives the device a large pitcher throws the
acceleration when throwing the device, going device.
Acceleration.Z Returns the acceleration of the device top to 0, before the pitcher
bottom. While in the air, the device experiences throws the device.
Description
Primary functions
The Cos function returns the cosine of its argument, an angle specified in radians.
The Cot function returns the cotangent of its argument, an angle specified in radians.
The Sin function returns the sine of its argument, an angle specified in radians.
The Tan function returns the tangent of its argument, an angle specified in radians.
Inverse functions
The Acos function returns the arccosine, or inverse cosine, of its argument. The
arccosine is the angle whose cosine is the argument. The returned angle is given in
radians in the range 0 (zero) to π.
The Acot function returns the principal value of the arccotangent, or inverse cotangent,
of its argument. The returned angle is given in radians in the range 0 (zero) to π.
The Asin function returns the arcsine, or inverse sine, of its argument. The arcsine is the
angle whose sine is the argument. The returned angle is given in radians in the range
-π/2 to π/2.
The Atan function returns the arctangent, or inverse tangent, of its argument. The
arctangent is the angle whose tangent is the argument. The returned angle is given in
radians in the range -π/2 to π/2.
The Atan2 function returns the arctangent, or inverse tangent, of the specified x and y
coordinates as arguments. The arctangent is the angle from the x-axis to a line that
contains the origin (0, 0) and a point with coordinates (x, y). The angle is given in radians
between -π and π, excluding -π. A positive result represents a counterclockwise angle
from the x-axis; a negative result represents a clockwise angle. Atan2( a, b ) equals
Atan( b/a ), except that a can equal 0 (zero) with the Atan2 function.
Helper functions
The Degrees function converts radians to degrees. π radians equals 180 degrees.
Notes
If you pass a single number to these functions, the return value is a single result. If you
pass a single-column table that contains numbers, the return value is a single-column
table of results with a Value column, one result for each record in the argument's table.
If you have a multi-column table, you can shape it into a single-column table, as
working with tables describes.
If an argument would result in an undefined value, the result is blank. This can happen,
for example, when using inverse functions with arguments that are out of range.
Syntax
Primary Functions
Cos( Radians )
Cot( Radians )
Sin( Radians )
Tan( Radians )
Cos( SingleColumnTable )
Cot( SingleColumnTable )
Sin( SingleColumnTable )
Tan( SingleColumnTable )
Inverse Functions
Acos( Number )
Acot( Number )
Asin( Number )
Atan( Number )
Acos( SingleColumnTable )
Acot( SingleColumnTable )
Asin( SingleColumnTable )
Atan( SingleColumnTable )
Atan2( X, Y )
Helper Functions
Degrees( Radians )
Pi()
Radians( Degrees )
Examples
Single number
Atan2( 5, 3 ) Returns the arctangent of the angle from the x-axis of the line 0.540419...
that contains the origin (0,0) and the coordinate (5,3), which is
approximately 31 degrees.
Atan2( 4, 4 ) Returns the arctangent of the angle from the x-axis of the line 0.785398...
that contains the origin (0,0) and the coordinate (4,4), which is
exactly π/4 radians or 45 degrees.
Single-column table
The examples in this section use a data source that's named ValueTable and that
contains the following data. The last record in the table is π/2 radians or 90 degrees.
Value
0.5
-2
1.570796...
Sin( ValueTable ) Returns the sine of each number A single-column table with a Value
in the table. column containing the following
values: 0.479425, -0.909297..., 1
Description
Primary functions
The Cos function returns the cosine of its argument, an angle specified in radians.
The Cot function returns the cotangent of its argument, an angle specified in radians.
The Sin function returns the sine of its argument, an angle specified in radians.
The Tan function returns the tangent of its argument, an angle specified in radians.
Inverse functions
The Acos function returns the arccosine, or inverse cosine, of its argument. The
arccosine is the angle whose cosine is the argument. The returned angle is given in
radians in the range 0 (zero) to π.
The Acot function returns the principal value of the arccotangent, or inverse cotangent,
of its argument. The returned angle is given in radians in the range 0 (zero) to π.
The Asin function returns the arcsine, or inverse sine, of its argument. The arcsine is the
angle whose sine is the argument. The returned angle is given in radians in the range
-π/2 to π/2.
The Atan function returns the arctangent, or inverse tangent, of its argument. The
arctangent is the angle whose tangent is the argument. The returned angle is given in
radians in the range -π/2 to π/2.
The Atan2 function returns the arctangent, or inverse tangent, of the specified x and y
coordinates as arguments. The arctangent is the angle from the x-axis to a line that
contains the origin (0, 0) and a point with coordinates (x, y). The angle is given in radians
between -π and π, excluding -π. A positive result represents a counterclockwise angle
from the x-axis; a negative result represents a clockwise angle. Atan2( a, b ) equals
Atan( b/a ), except that a can equal 0 (zero) with the Atan2 function.
Helper functions
The Degrees function converts radians to degrees. π radians equals 180 degrees.
Notes
If you pass a single number to these functions, the return value is a single result. If you
pass a single-column table that contains numbers, the return value is a single-column
table of results with a Value column, one result for each record in the argument's table.
If you have a multi-column table, you can shape it into a single-column table, as
working with tables describes.
If an argument would result in an undefined value, the result is blank. This can happen,
for example, when using inverse functions with arguments that are out of range.
Syntax
Primary Functions
Cos( Radians )
Cot( Radians )
Sin( Radians )
Tan( Radians )
Cos( SingleColumnTable )
Cot( SingleColumnTable )
Sin( SingleColumnTable )
Tan( SingleColumnTable )
Inverse Functions
Acos( Number )
Acot( Number )
Asin( Number )
Atan( Number )
Acos( SingleColumnTable )
Acot( SingleColumnTable )
Asin( SingleColumnTable )
Atan( SingleColumnTable )
Atan2( X, Y )
Helper Functions
Degrees( Radians )
Pi()
Radians( Degrees )
Examples
Single number
Atan2( 5, 3 ) Returns the arctangent of the angle from the x-axis of the line 0.540419...
that contains the origin (0,0) and the coordinate (5,3), which is
approximately 31 degrees.
Atan2( 4, 4 ) Returns the arctangent of the angle from the x-axis of the line 0.785398...
that contains the origin (0,0) and the coordinate (4,4), which is
exactly π/4 radians or 45 degrees.
Single-column table
The examples in this section use a data source that's named ValueTable and that
contains the following data. The last record in the table is π/2 radians or 90 degrees.
Value
0.5
-2
1.570796...
Sin( ValueTable ) Returns the sine of each number A single-column table with a Value
in the table. column containing the following
values: 0.479425, -0.909297..., 1
Overview
These functions shape a table by adjusting its columns:
Reduce a table that contains multiple columns down to a single column for use
with single-column functions, such as Lower or Abs.
Add a calculated column to a table (for example, a Total Price column that shows
the results of multiplying Quantity by Unit Price).
Rename a column to something more meaningful, for display to users or for use in
formulas.
A table is a value in Power Apps, just like a string or a number. You can specify a table as
an argument in a formula, and functions can return a table as a result.
7 Note
The functions that this topic describes don't modify the original table. Instead, they
take that table as an argument and return a new table with a transform applied. See
working with tables for more details.
You can't modify the columns of a data source by using these functions. You must
modify the data at its source. You can add columns to a collection with the Collect
function. See working with data sources for more details.
Description
The AddColumns function adds a column to a table, and a formula defines the values in
that column. Existing columns remain unmodified.
The DropColumns function excludes columns from a table. All other columns remain
unmodified. DropColumns excludes columns, and ShowColumns includes columns.
The ShowColumns function includes columns of a table and drops all other columns.
You can use ShowColumns to create a single-column table from a multi-column table.
ShowColumns includes columns, and DropColumns excludes columns.
For all these functions, the result is a new table with the transform applied. The original
table isn't modified. You can't modify an existing table with a formula. SharePoint,
Microsoft Dataverse, SQL Server, and other data sources provide tools for modifying the
columns of lists, tables, and tables, which are often referred to as the schema. The
functions in this topic only transform an input table, without modifying the original, into
an output table for further use.
The arguments to these functions support delegation. For example, a Filter function
used as an argument to pull in related records searches through all listings, even if the
'[dbo].[AllListings]' data source contains a million rows:
Power Apps
AddColumns( RealEstateAgents,
"Listings",
However, the output of these functions is subject to the non-delegation record limit. In
this example, only 500 records are returned even if the RealEstateAgents data source
has 501 or more records.
If you use AddColumns in this manner, Filter must make separate calls to the data
source for each of those first records in RealEstateAgents, which causes a lot of network
chatter. If [dbo](.[AllListings] is small enough and doesn't change often, you could call
the Collect function in OnStart to cache the data source in your app when it starts. As
an alternative, you could restructure your app so that you pull in the related records
only when the user asks for them.
Syntax
AddColumns( Table, ColumnName1, Formula1 [, ColumnName2, Formula2, ... ] )
None of these examples modify the IceCreamSales data source. Each function
transforms the value of the data source as a table and returns that value as the result.
DropColumns(
Performs the following table transforms in
RenameColumns(
order, starting from the inside of the formula:
AddColumns(
IceCreamSales, 1. Adds a Revenue column based on the
"Revenue",
per-record calculation of UnitPrice *
UnitPrice * QuantitySold ),
Quantity.
"UnitPrice", "Price" ),
2. Renames UnitPrice to Price.
"Quantity" ) 3. Excludes the Quantity column.
Step by step
Let's try some of the examples from earlier in this topic.
1. Create a collection by adding a Button control and setting its OnSelect property to
this formula:
Power Apps
ClearCollect( IceCreamSales,
Table(
2. Run the formula by selecting the button while holding down the Alt key.
3. Add a second Button control, set its OnSelect property to this formula, and then
run it:
Power Apps
ClearCollect( FirstExample,
4. On the File menu, select Collections, and then select IceCreamSales to show that
collection.
As this graphic shows, the second formula didn't modify this collection. The
AddColumns function used IceCreamSales as a read-only argument; the function
didn't modify the table to which that argument refers.
5. Select FirstExample.
As this graphic shows, the second formula returned a new table with the added
column. The ClearCollect function captured the new table in the FirstExample
collection, adding something to the original table as it flowed through the function
without modifying the source:
Map columns in a component
See Map columns.
And, Or, and Not functions in Power
Apps
Article • 02/23/2023 • 2 minutes to read
Boolean logic functions, commonly used to manipulate the results of comparisons and
tests.
Description
The And function returns true if all of its arguments are true.
The Not function returns true if its argument is false; it returns false if its argument is
true.
These functions work the same way as they do in Excel. You can also use operators to
perform these same operations, using either Visual Basic or JavaScript syntax:
Or( x, y ) x Or y x || y
Not( x ) Not x !x
These functions work with logical values. You can't pass them a number or a string
directly; instead, you must make a comparison or a test. For example, this logical
formula x > 1 evaluates to the Boolean value true if x is greater than 1. If x is less than 1,
the formula evaluates to false.
Syntax
And( LogicalFormula1, LogicalFormula2 [, LogicalFormula3, ... ] )
Not( LogicalFormula )
Examples
The examples in this section use these global variables:
a = false
b = true
x = 10
y = 100
s = "Hello World"
To create these global variables in an app, insert a Button control, and set its OnSelect
property to this formula:
Power Apps
Select the button (by clicking it while you hold down the Alt key), and then set the Text
property of a Label control to a formula in the first column of the next table.
And( a, b ) Tests the values of a and b. One of the arguments is false, so the false
function returns false.
a And b Same as the previous example, using Visual Basic notation. false
Or( a, b ) Tests the values of a and b. One of the arguments is true, so the true
function returns true.
Not( a ) Tests the value of a. The argument is false, so the function returns true
the opposite result.
Not a Same as the previous example, using Visual Basic notation. true
Len( s ) < 20 Tests whether the length of s is less than 20 and whether it isn't a true
And Not IsBlank( s ) blank value. The length is less than 20, and the value isn't blank.
Therefore, the result is true.
Formula Description Result
Or( Len( s ) < 10, Tests whether the length of s is less than 10, whether x is less than true
x < 100, y < 100 ) 100, and whether y is less than 100. The first and third arguments
are false, but the second one is true. Therefore, the function
returns true.
Not IsBlank( s ) Tests whether s is blank, which returns false. Not returns the true
opposite of this result, which is true.
App object in Power Apps
Article • 02/23/2023 • 14 minutes to read
Provides information about the currently running app and control over the app's
behavior.
Description
Like a control, the App object provides properties that identify which screen is showing
and that prompt the user to save changes so that they're not lost. Every app has an App
object.
You can write formulas for some properties of the App object. At the top of the Tree
view pane, select the App object as you would any other control or screen. View and
edit one of the object's properties by selecting it in the drop-down list to the left of the
formula bar.
ActiveScreen property
The ActiveScreen property identifies the screen that's showing.
This property returns a screen object, which you can use to reference properties of the
screen or compare to another screen to determine which screen is showing. You can
also use the expression App.ActiveScreen.Name to retrieve the name of the screen
that's showing.
Use the Back or Navigate function to change the screen that's showing.
ConfirmExit properties
Nobody wants to lose unsaved changes. Use the ConfirmExit and ConfirmExitMessage
properties to warn the user before they close your app.
7 Note
ConfirmExit doesn't work in apps that are embedded in, for example, Power
BI and SharePoint.
At present, these properties can reference controls on only the first screen if
the Delayed load preview feature is enabled (which it is by default for new
apps). If references are made, Power Apps Studio doesn't show an error, but
the resulting published app doesn't open in Power Apps Mobile or a browser.
We're actively working to lift this limitation. In the meantime, you can turn off
Delayed load in Settings > Upcoming features (under Preview).
ConfirmExit
ConfirmExit is a Boolean property that, when true, opens a confirmation dialog box
before the app is closed. By default, this property is false, and no dialog box appears.
Use this property to show a confirmation dialog box if the user has made changes but
not saved them. Use a formula that can check variables and control properties (for
example, the Unsaved property of the Edit form control).
The confirmation dialog box appears in any situation where data could be lost, as in
these examples:
The exact look of the confirmation dialog box might vary across devices and versions of
Power Apps.
In a browser, the confirmation dialog box might appear with a generic message from
the browser.
7 Note
App object has two more properties OnMessage and BackEnabled that are
experimental. These properties will be removed from the app object eventually. We
recommend that you don't use these properties in your production environment.
Example
1. Create an app that contains two form controls, AccountForm and ContactForm.
Power Apps
AccountForm.Unsaved Or ContactForm.Unsaved
This dialog box appears if the user changes data in either form and then tries to
close the app without saving those changes.
Power Apps
If( AccountsForm.Unsaved,
This dialog box appears if the user changes data in the Account form and then
tries to close the app without saving those changes.
Formulas property
7 Note
Use named formulas, in the Formulas property, to define a formula that can be reused
throughout your app.
In Power Apps, control properties are driven by formulas. For example, to set the
background color consistently across an app, you might set the Fill property for each to
a common formula:
Power Apps
With so many places where this formula may appear, it becomes tedious and error
prone to update them all if a change is needed. Instead, you can create a global variable
in OnStart to set the color once, and then reuse the value throughout the app:
Power Apps
Label1.Fill: BGColor
Label2.Fill: BGColor
Label3.Fill: BGColor
While this method is better, it also depends on OnStart running before the value for
BGColor is established. BGColor might also be manipulated in some corner of the app
that the maker is unaware of, a change made by someone else, and that can be hard to
track down.
Power Apps
Label1.Fill: BGColor
Label2.Fill: BGColor
Label3.Fill: BGColor
Named formulas are defined, one after another in the Formulas property, each ending
with a semi-colon. The type of the formula is inferred from the types of the expression,
which is based on the types of the elements within the expression and how they're used
together. For example, these named formulas retrieve useful information about the
current user from Dataverse:
Power Apps
UserEmail = User().Email;
UserTitle = UserInfo.Title;
UserInfo.'Main Phone' );
If the formula for UserTitle needs to be updated, it can be done easily in this one
location. If UserPhone isn't needed in the app, then these calls to the Users table in
Dataverse aren't made. There's no penalty for including a formula definition that isn't
used.
They can't use behavior functions or otherwise cause side effects within the app.
They can't create a circular reference. Having a = b; and b = a; in the same app
isn't allowed.
OnError property
7 Note
Use OnError to take action after an error has been detected. It provides a global
opportunity to intercept an error banner before it's displayed to the end user. It can also
be used to log an error with the Trace function or write to a database or web service.
The result of every formula evaluation is checked for an error. If it's an error, OnError will
be evaluated with the same FirstError and AllErrors scope variables that would have
been present if the entire formula was wrapped in an IfError function.
If OnError is empty, a default error banner is shown with the FirstError.Message of the
error. Defining an OnError formula overrides this behavior enabling the maker to handle
the error reporting as they see fit. The default behavior can be requested in the OnError
by rethrowing the error with the Error function. This is useful if some errors are to be
filtered out or handled in a different manner, while others are to be passed through.
OnError can't replace an error in calculations the way that IfError can. At the point that
OnError is invoked, the error has already happened and it has already been processed
through formula calculations. *OnError* controls error reporting only.
OnError formulas are evaluated concurrently and it's possible that their evaluation may
overlap with the processing of other errors. For example, if you set a global variable at
the top of an OnError and read it later on in the same formula, the value may have
changed. Use the With function to create a named value that is local to the formula.
Although each error is processed individually by OnError, the default error banner may
not appear for each error individually. To avoid having too many error banners displayed
at the same time, the same error won't trigger a new error banner if it has recently been
shown.
Example
Consider a Label control and Slider control that are bound together through the
formula:
Power Apps
Label1.Text = 1/Slider1.Value
The slider defaults to 50. If the slider is moved to 0, Label1 will show no value, and an
error banner is shown:
1. User moved the slide to the left and the Slide1.Value property changed to 0.
2. Label1.Text was automatically reevaluated. Division by zero occurred, generating
an error.
3. There's no IfError in this formula. The division by zero error is returned by the
formula evaluation.
4. Label1.Text can't show anything for this error, so it shows a blank state.
5. OnError is invoked. Since there's no handler, the standard error banner is displayed
with error information.
value of an error from OnError since at that point the error has already happened, it's
only a question of how it will be reported.
If we add an OnError handler, it will have no impact before step 5, but it can impact how
the error is reported:
Power Apps
With this in place, from the app user's perspective, there won't be any error. But the
error will be added to Monitor's trace, complete with the source of the error information
from FirstError:
If we also wanted to have the same default error banner displayed in addition to the
trace, we can rethrow the error with the Error function after the Trace call just as it did if
the Trace wasn't there:
Power Apps
Error( FirstError )
OnStart property
7 Note
The use of OnStart property can cause performance problems when loading an
app. We're in the process of creating alternatives for the top two reasons for using
property—caching data and setting up global variables. We've already created an
alternative for defining the first screen to be shown with Navigate. Depending on
your context, this property may be disabled by default. If you don't see it, and you
need to use it, check the app's Advanced settings for a switch to enable it. The
OnVisible property of a screen can also be used.
The OnStart property runs when the user starts the app. This property is often used to
perform the following tasks:
Retrieve and cache data into collections by using the Collect function.
Set up global variables by using the Set function.
This formula is evaluated before the first screen appears. No screen is loaded, so you
can't set context variables with the UpdateContext function. However, you can pass
context variables with the Navigate function.
After you change the OnStart property, test it by hovering over the App object in the
Tree view pane, selecting ellipsis (...), and then selecting Run OnStart. Unlike when the
app is loaded for the first time, existing collections and variables will already be set. To
start with empty collections, use the ClearCollect function instead of the Collect
function.
7 Note
Using the Navigate function in the OnStart property has been retired. Existing
apps will continue to work. For a limited time, you can still enable it in the app
settings (available under Retired). However, using Navigate in this manner
can lead to app load delays as it forces the system to complete evaluation of
OnStart before displaying the first screen. Use the StartScreen property
instead to calculate the first screen displayed.
Retired switch will be turned off for apps created before March 2021 where
you added Navigate to OnStart between March 2021 and now. When you
edit such apps in Power Apps Studio, you may see an error. Turn the above
mentioned Retired switch to clear this error.
StartScreen property
7 Note
StartScreen property will not appear in the list of properties when the retired
option Enhanced formula bar is turned on. To turn Enhanced formula bar off, go
to Settings > Upcoming features > Retired > turn off the Enhanced formula bar
switch when you want to use StartScreen property.
The StartScreen property determines which screen will be displayed first. It's evaluated
once when the app is loaded and returns the screen object to be displayed. By default,
this property will be empty, and the first screen in the Studio Tree view is shown first.
StartScreen is a data flow property that can't contain behavior functions. All data flow
functions are available, in particular use these functions and signals to determine which
screen to show first:
7 Note
Global variables and collections, including those created in OnStart, are not
available in StartScreen. There are declarative alternatives for doing this that are on
the way. For your feedback on this restriction, go to Power Apps community
forum .
If StartScreen returns an error, the first screen in the Studio Tree view will be shown as if
StartScreen hadn't been set. Use the IfError function to catch any errors and redirect to
an appropriate error screen.
After changing StartScreen in Studio, test it by hovering over the App object in the Tree
view pane, selecting the ellipsis (...), and then selecting Navigate to StartScreen. The
screen will change as if the app has been loaded.
Examples
Power Apps
Screen9
Indicates that Screen9 should be shown first whenever the app starts.
Power Apps
Checks if the Param "admin-mode" has been set by the user and uses it to decide if the
HomeScreen or AdminScreen should be displayed first.
Power Apps
Checks if an attendee to a conference is a staff member and directs them to the proper
screen on startup.
Power Apps
ForestScreen,
OceanScreen
),
ErrorScreen
Directs the app based on an API call to either ForestScreen or OceanScreen . If the API
fails for any reason, the ErrorScreen is used instead.
Operators and Identifiers in Power Apps
Article • 03/01/2023 • 12 minutes to read
Some of these operators are dependent on the language of the author. For more
information about language support in canvas apps, see Global apps.
"..." Text string "Hello, World" Text strings are enclosed in double
quotes
. Property Slider1.Value
Extracts a property from a table,
Selector Color.Red
control, signal, or enumeration. For
Acceleration.X backward compatibility, ! may also be
used.
.
Decimal 1.23 Separator between whole and fractional
[language separator parts of a number. The character
dependent] depends on the language.
* 2*3 Multiplication
& String "hello" & " " & Makes multiple strings appear
concatenation "world" continuous
operator
&& or And Logical Price < 100 && Logical conjunction, equivalent to the
operators Slider1.Value = 20
And function
or Price < 100 And
Slider1.Value = 20
! or Not !(Price < 100) or Not Logical negation, equivalent to the Not
(Price < 100) function
,
List separator If( X < 10, "Low", Separates:
[language "Good" )
arguments in function calls
dependent] { X: 12, Y: 32 }
fields in a record
[ 1, 2, 3 ] records in a table
;
Formula Collect(T, A); Separate invocations of functions in
[language chaining Navigate(S1, "") behavior properties. The chaining
dependent] operator depends on the language.
7 Note
The @ operator can also be used to validate the type of the record object against a
data source. For example, Collect(coll,Account@{'Account Number: 1111')
The gallery shows all products except Callisto because the name of that product is
the only one that doesn't contain the letter you specified.
The gallery shows only Europa because only its name contains the letter that you
specified in the case that you specified.
ThisItem Gallery control
The default name for the current record in a Gallery or form
Edit form control
control.
Display form control
ThisRecord ForAll, Filter, With, The default name for the current record in ForAll and other
Sum and other record scope functions.
record scope
functions
As name Gallery control
Defines a name for the current record, replacing default
ForAll, Filter, With, ThisItem or ThisRecord. Use As to make formulas easier to
Sum and other understand and resolve ambiguity when nesting.
record scope
functions
ThisItem operator
For example, in the following Gallery control, the Items property is set to the Employees
data source (such as the Employees table included with the Northwind Traders sample):
Power Apps
Employees
The first item in the gallery is a template that is replicated for each employee. In the
template, the formula for the picture uses ThisItem to refer to the current item:
Power Apps
ThisItem.Picture
Power Apps
ThisRecord operator
ThisRecord is used in functions that have a record scope. For example, we can use the
Filter function with our gallery's Items property to only show first names that being with
M:
Power Apps
ThisRecord is optional and implied by using the fields directly, for example, in this case,
we could have written:
Power Apps
Although optional, using ThisRecord can make formulas easier to understand and may
be required in ambiguous situations where a field name may also be a relationship
name. ThisRecord is optional while ThisItem is always required.
Use ThisRecord to reference the whole record with Patch, Collect, and other record
scope functions. For example, the following formula sets the status for all inactive
employees to active:
Power Apps
ForAll( InactiveEmployees,
As operator
Use the As operator to name a record in a gallery or record scope function, overriding
the default ThisItem or ThisRecord. Naming the record can make your formulas easier
to understand and may be required in nested situations to access records in other
scopes.
For example, you can modify the Items property of our gallery to use As to identify that
we are working with an Employee:
Power Apps
Employees As Employee
The formulas for the picture and name are adjusted to use this name for the current
record:
Power Apps
Employee.Picture
Power Apps
Employee.'First Name' & " " & Employee.'Last Name'
As can also be used with record scope functions to replace the default name
ThisRecord. We can apply this to our previous example to clarify the record we're
working with:
Power Apps
When nesting galleries and record scope functions, ThisItem and ThisRecord always
refers to the inner most scope, leaving records in outer scopes unavailable. Use As to
make all record scopes available by giving each a unique name.
For example, this formula produces a chessboard pattern as a text string by nesting two
ForAll functions:
Power Apps
Concat(
Concat(
),
Value
) & Char(10)
),
Value
A similar example is possible with nested Gallery controls instead of ForAll functions.
Let's start with the vertical gallery for the Rank. This gallery control will have an Items
formula of:
Power Apps
Sequence(8) as Rank
Within this gallery, we'll place a horizontal gallery for the File, that will be replicated for
each Rank, with an Items property of:
Power Apps
Sequence(8) as File
And finally, within this gallery, we'll add a Label control that will be replicated for each
File and each Rank. We'll size it to fill the entire space and use the Fill property to
provide the color with this formula:
Power Apps
Method Description
By Any control can be referenced by name from anywhere within the app.
control
name For example, Label1.Fill refers to the fill property of the control who's name is Label1.
Self It's often convenient to reference another property of the same control when writing a
operator formula. Instead of using an absolute reference by name, it's easier and more portable
to use a relative reference to oneself. The Self operator provides that easy access to
the current control.
For example, Self.Fill refers to the fill color of the current control.
Parent Some controls host other controls, such as the Screen and Gallery controls. The
operator hosting control of the controls within it's called the parent. Like the Self operator, the
Parent operator provides an easy relative reference to the container control.
For example, Parent.Fill refers to the fill property of the control that is the container for
the current control.
Self and Parent are operators and not properties on the controls themselves. Referring
to Parent.Parent, Self.Parent or Parent.Self is not supported.
Identifier names
The names of variables, data sources, columns, and other objects can contain any
Unicode .
Use single quotes around a name that contains a space or other special character.
Use two single quotes together to represent one single quote in the name. Names that
don't contain special characters don't require single quotes.
Here are some example column names you might encounter in a table, and how they're
represented in a formula:
SimpleName SimpleName
NameWith123Numbers NameWith123Numbers
Display name - A name that is user-friendly and intended to be seen by end users.
This name may not be unique, may change over time, may contain spaces and any
Unicode character, and may be localized into different languages. Corresponding
to the example above, the display name may be Custom Field with space in
between the words.
Since display names are easier to understand, Canvas apps will suggest them as choices
and not suggest logical names. Although logical names aren't suggested, they can still
be used if typed indirectly.
For example, imagine you've added a Custom Field to a table in Dataverse. A logical
name will be assigned for you by the system, which you can modify only when creating
the field. The result would look similar to:
When authoring a reference to a field of Accounts, the suggestion will be made to use
'Custom Field' since this is the display name. Single quotes must be used because this
name has a space in it:
After selecting the suggestion, 'Custom Field' is shown in the formula bar and the data is
retrieved:
Although it isn't suggested, we could also use the logical name for this field. This will
result in the same data being retrieved. Single quotes are not required since this name
doesn't contain spaces or special characters:
Behind the scenes, a mapping is maintained between the display names seen in
formulas and the underlying logical names. Since logical names must be used to interact
with the data source, this mapping is used to convert from the current display name to
the logical name automatically and that is what is seen in the network traffic. This
mapping is also used to convert back to logical names to switch into new display names,
for example, if a display name changes or a maker in a different language edits the app.
7 Note
Logical names are not translated when moving an app between environments. For
Dataverse system table and field names, this should not be a problem as logical
names are consistent across environments. But any custom fields, such as
cra3a_customfield in this example above, may have a different environment prefix
(cra3a in this case). Display names are preferred as they can be matched against
display names in the new environment.
Name disambiguation
Since display names aren't unique, the same display name may appear more than once
in the same table. When this happens, the logical name will be added to the end of the
display name in parenthesis for one of more of the conflicting names. Building on the
example above, if there was a second field with the same display name of Custom Field
with a logical name of cra3a_customfieldalt then the suggestions would show:
Name disambiguation strings are added in other situations where name conflicts occur,
such as the names of table, choices, and other Dataverse items.
Disambiguation operator
Some functions create record scopes for accessing the fields of table while processing
each record, such as Filter, AddColumns, and Sum. Field names added with the record
scope override the same names from elsewhere in the app. When this happens, you can
still access values from outside the record scope with the @ disambiguation operator:
To access values from nested record scopes, use the @ operator with the name of
the table being operated upon using this pattern:
Table[@FieldName]
To access global values, such as data sources, collections, and context variables,
use the pattern [@ObjectName] (without a table designation).
Description
Primary functions
The Cos function returns the cosine of its argument, an angle specified in radians.
The Cot function returns the cotangent of its argument, an angle specified in radians.
The Sin function returns the sine of its argument, an angle specified in radians.
The Tan function returns the tangent of its argument, an angle specified in radians.
Inverse functions
The Acos function returns the arccosine, or inverse cosine, of its argument. The
arccosine is the angle whose cosine is the argument. The returned angle is given in
radians in the range 0 (zero) to π.
The Acot function returns the principal value of the arccotangent, or inverse cotangent,
of its argument. The returned angle is given in radians in the range 0 (zero) to π.
The Asin function returns the arcsine, or inverse sine, of its argument. The arcsine is the
angle whose sine is the argument. The returned angle is given in radians in the range
-π/2 to π/2.
The Atan function returns the arctangent, or inverse tangent, of its argument. The
arctangent is the angle whose tangent is the argument. The returned angle is given in
radians in the range -π/2 to π/2.
The Atan2 function returns the arctangent, or inverse tangent, of the specified x and y
coordinates as arguments. The arctangent is the angle from the x-axis to a line that
contains the origin (0, 0) and a point with coordinates (x, y). The angle is given in radians
between -π and π, excluding -π. A positive result represents a counterclockwise angle
from the x-axis; a negative result represents a clockwise angle. Atan2( a, b ) equals
Atan( b/a ), except that a can equal 0 (zero) with the Atan2 function.
Helper functions
The Degrees function converts radians to degrees. π radians equals 180 degrees.
Notes
If you pass a single number to these functions, the return value is a single result. If you
pass a single-column table that contains numbers, the return value is a single-column
table of results with a Value column, one result for each record in the argument's table.
If you have a multi-column table, you can shape it into a single-column table, as
working with tables describes.
If an argument would result in an undefined value, the result is blank. This can happen,
for example, when using inverse functions with arguments that are out of range.
Syntax
Primary Functions
Cos( Radians )
Cot( Radians )
Sin( Radians )
Tan( Radians )
Cos( SingleColumnTable )
Cot( SingleColumnTable )
Sin( SingleColumnTable )
Tan( SingleColumnTable )
Inverse Functions
Acos( Number )
Acot( Number )
Asin( Number )
Atan( Number )
Acos( SingleColumnTable )
Acot( SingleColumnTable )
Asin( SingleColumnTable )
Atan( SingleColumnTable )
Atan2( X, Y )
Helper Functions
Degrees( Radians )
Pi()
Radians( Degrees )
Examples
Single number
Atan2( 5, 3 ) Returns the arctangent of the angle from the x-axis of the line 0.540419...
that contains the origin (0,0) and the coordinate (5,3), which is
approximately 31 degrees.
Atan2( 4, 4 ) Returns the arctangent of the angle from the x-axis of the line 0.785398...
that contains the origin (0,0) and the coordinate (4,4), which is
exactly π/4 radians or 45 degrees.
Single-column table
The examples in this section use a data source that's named ValueTable and that
contains the following data. The last record in the table is π/2 radians or 90 degrees.
Value
0.5
-2
1.570796...
Sin( ValueTable ) Returns the sine of each number A single-column table with a Value
in the table. column containing the following
values: 0.479425, -0.909297..., 1
Assertion messages, for both passed and failed assertions, are also contained in a Traces
table in the TestCaseResult record.
Syntax
Assert(expression, message)
Examples
Assert(lblResult.Text = "Success", "lblResult value Expected : Success , Actual : "
& lblResult.Text)
See Also
Test Studio Overview
Checks a record reference for a specific table type (IsType) and treats the reference as a
specific type (AsType).
Description
Read Understand record references and polymorphic lookups for a broader introduction
and more details.
A lookup field usually refers to records in a particular table. Because the table type is
well established, you can access the fields of the lookup by using a simple dot notation.
For example, First( Accounts ).'Primary Contact'.'Full Name' walks from the Accounts
table to the Primary Contact record in the Contacts table and extracts the Full Name
field.
Microsoft Dataverse also supports polymorphic lookup fields, which can refer to records
from a set of tables, as in these examples.
The IsType function tests whether a record reference refers to a specific table type. The
function returns a Boolean TRUE or FALSE.
The AsType function treats a record reference as a specific table type, sometimes
referred to as casting. You can use the result as if it were a record of the table and again
use the Record.Field notation to access all of the fields of that record. An error occurs if
the reference isn't of the specific type.
Use these functions together to first test the table type of a record and then treat it as a
record of that type so that the fields are available:
Power Apps
You need these functions only if you're accessing the fields of a record reference. For
example, you can use record references in the Filter function without IsType or AsType:
Power Apps
Similarly, you can use record references with the Patch function:
Power Apps
If used in a record context, such as within a Gallery or Edit form control, you might need
to use the global disambiguation operator to reference the table type. For example, this
formula would be effective for a gallery that's displaying a list of contacts where
Company Name is a Customer lookup:
Power Apps
For both functions, you specify the type through the name of the data source that's
connected to the table. For the formula to work, you must also add a data source to the
app for any types that you want to test or cast. For example, you must add the Users
table as a data source if you want to use IsType and AsType with an Owner lookup and
records from that table. You can add only the data sources that you actually use in your
app; you don't need to add all the tables that a lookup could reference.
If the record reference is blank, IsType returns FALSE, and AsType returns blank. All fields
of a blank record will be blank.
Syntax
AsType( RecordReference, TableType )
RecordReference - Required. A record reference, often a lookup field that can refer
to a record in any of multiple tables.
TableType - Required. The specific table to which the record should be cast.
RecordReference - Required. A record reference, often a lookup field that can refer
to a record in any of multiple tables.
TableType - Required. The specific table for which to test.
Example
Understand record references and polymorphic lookups contains extensive examples.
2. On the left-pane, select Data > Add data. And then, add Accounts and Contacts
tables.
3. On the left-pane, select + (Insert) > Layout > Blank vertical gallery.
4. Select Connect to data, and then select Contacts as the data source.
Power Apps
If( IsBlank( ThisItem.'Company Name' ), "--",
Your results might differ from those in this topic because it uses sample data that
was modified to show additional types of results.
Acos, Acot, Asin, Atan, Atan2, Cos, Cot,
Degrees, Pi, Radians, Sin, and Tan
functions in Power Apps
Article • 03/17/2023 • 5 minutes to read
Description
Primary functions
The Cos function returns the cosine of its argument, an angle specified in radians.
The Cot function returns the cotangent of its argument, an angle specified in radians.
The Sin function returns the sine of its argument, an angle specified in radians.
The Tan function returns the tangent of its argument, an angle specified in radians.
Inverse functions
The Acos function returns the arccosine, or inverse cosine, of its argument. The
arccosine is the angle whose cosine is the argument. The returned angle is given in
radians in the range 0 (zero) to π.
The Acot function returns the principal value of the arccotangent, or inverse cotangent,
of its argument. The returned angle is given in radians in the range 0 (zero) to π.
The Asin function returns the arcsine, or inverse sine, of its argument. The arcsine is the
angle whose sine is the argument. The returned angle is given in radians in the range
-π/2 to π/2.
The Atan function returns the arctangent, or inverse tangent, of its argument. The
arctangent is the angle whose tangent is the argument. The returned angle is given in
radians in the range -π/2 to π/2.
The Atan2 function returns the arctangent, or inverse tangent, of the specified x and y
coordinates as arguments. The arctangent is the angle from the x-axis to a line that
contains the origin (0, 0) and a point with coordinates (x, y). The angle is given in radians
between -π and π, excluding -π. A positive result represents a counterclockwise angle
from the x-axis; a negative result represents a clockwise angle. Atan2( a, b ) equals
Atan( b/a ), except that a can equal 0 (zero) with the Atan2 function.
Helper functions
The Degrees function converts radians to degrees. π radians equals 180 degrees.
Notes
If you pass a single number to these functions, the return value is a single result. If you
pass a single-column table that contains numbers, the return value is a single-column
table of results with a Value column, one result for each record in the argument's table.
If you have a multi-column table, you can shape it into a single-column table, as
working with tables describes.
If an argument would result in an undefined value, the result is blank. This can happen,
for example, when using inverse functions with arguments that are out of range.
Syntax
Primary Functions
Cos( Radians )
Cot( Radians )
Sin( Radians )
Tan( Radians )
Cos( SingleColumnTable )
Cot( SingleColumnTable )
Sin( SingleColumnTable )
Tan( SingleColumnTable )
Inverse Functions
Acos( Number )
Acot( Number )
Asin( Number )
Atan( Number )
Acos( SingleColumnTable )
Acot( SingleColumnTable )
Asin( SingleColumnTable )
Atan( SingleColumnTable )
Atan2( X, Y )
Helper Functions
Degrees( Radians )
Pi()
Radians( Degrees )
Examples
Single number
Atan2( 5, 3 ) Returns the arctangent of the angle from the x-axis of the line 0.540419...
that contains the origin (0,0) and the coordinate (5,3), which is
approximately 31 degrees.
Atan2( 4, 4 ) Returns the arctangent of the angle from the x-axis of the line 0.785398...
that contains the origin (0,0) and the coordinate (4,4), which is
exactly π/4 radians or 45 degrees.
Single-column table
The examples in this section use a data source that's named ValueTable and that
contains the following data. The last record in the table is π/2 radians or 90 degrees.
Value
0.5
-2
1.570796...
Sin( ValueTable ) Returns the sine of each number A single-column table with a Value
in the table. column containing the following
values: 0.479425, -0.909297..., 1
Description
Primary functions
The Cos function returns the cosine of its argument, an angle specified in radians.
The Cot function returns the cotangent of its argument, an angle specified in radians.
The Sin function returns the sine of its argument, an angle specified in radians.
The Tan function returns the tangent of its argument, an angle specified in radians.
Inverse functions
The Acos function returns the arccosine, or inverse cosine, of its argument. The
arccosine is the angle whose cosine is the argument. The returned angle is given in
radians in the range 0 (zero) to π.
The Acot function returns the principal value of the arccotangent, or inverse cotangent,
of its argument. The returned angle is given in radians in the range 0 (zero) to π.
The Asin function returns the arcsine, or inverse sine, of its argument. The arcsine is the
angle whose sine is the argument. The returned angle is given in radians in the range
-π/2 to π/2.
The Atan function returns the arctangent, or inverse tangent, of its argument. The
arctangent is the angle whose tangent is the argument. The returned angle is given in
radians in the range -π/2 to π/2.
The Atan2 function returns the arctangent, or inverse tangent, of the specified x and y
coordinates as arguments. The arctangent is the angle from the x-axis to a line that
contains the origin (0, 0) and a point with coordinates (x, y). The angle is given in radians
between -π and π, excluding -π. A positive result represents a counterclockwise angle
from the x-axis; a negative result represents a clockwise angle. Atan2( a, b ) equals
Atan( b/a ), except that a can equal 0 (zero) with the Atan2 function.
Helper functions
The Degrees function converts radians to degrees. π radians equals 180 degrees.
Notes
If you pass a single number to these functions, the return value is a single result. If you
pass a single-column table that contains numbers, the return value is a single-column
table of results with a Value column, one result for each record in the argument's table.
If you have a multi-column table, you can shape it into a single-column table, as
working with tables describes.
If an argument would result in an undefined value, the result is blank. This can happen,
for example, when using inverse functions with arguments that are out of range.
Syntax
Primary Functions
Cos( Radians )
Cot( Radians )
Sin( Radians )
Tan( Radians )
Cos( SingleColumnTable )
Cot( SingleColumnTable )
Sin( SingleColumnTable )
Tan( SingleColumnTable )
Inverse Functions
Acos( Number )
Acot( Number )
Asin( Number )
Atan( Number )
Acos( SingleColumnTable )
Acot( SingleColumnTable )
Asin( SingleColumnTable )
Atan( SingleColumnTable )
Atan2( X, Y )
Helper Functions
Degrees( Radians )
Pi()
Radians( Degrees )
Examples
Single number
Atan2( 5, 3 ) Returns the arctangent of the angle from the x-axis of the line 0.540419...
that contains the origin (0,0) and the coordinate (5,3), which is
approximately 31 degrees.
Atan2( 4, 4 ) Returns the arctangent of the angle from the x-axis of the line 0.785398...
that contains the origin (0,0) and the coordinate (4,4), which is
exactly π/4 radians or 45 degrees.
Single-column table
The examples in this section use a data source that's named ValueTable and that
contains the following data. The last record in the table is π/2 radians or 90 degrees.
Value
0.5
-2
1.570796...
Sin( ValueTable ) Returns the sine of each number A single-column table with a Value
in the table. column containing the following
values: 0.479425, -0.909297..., 1
Description
The Average function calculates the average, or arithmetic mean, of its arguments.
Fields of the record currently being processed are available within the formula. Use the
ThisRecord operator or simply reference fields by name as you would any other value.
The As operator can also be used to name the record being processed which can help
make your formula easier to understand and make nested records accessible. For more
information, see the examples below and working with record scope.
These functions operate on numeric values only. Other types of values, such as strings or
records, are ignored. Use the Value function to convert a string into a number.
The Average, Max, Min, and Sum functions can be delegated when used with a data
source that supports delegation for these functions. However, StdevP and VarP can't be
delegated for any data sources. If delegation is not supported, only the first portion of
the data will be retrieved and then the function applied locally. The result may not
represent the complete story. A delegation warning will appear at authoring time to
remind you of this limitation and to suggest switching to delegable alternatives where
possible. For more information, see the delegation overview.
Syntax
Average( NumericalFormula1, [ NumericalFormula2, ... ] )
Examples
Step by step
Let's say that you had a data source named Sales that contained a CostPerUnit column
and a UnitsSold column, and you set the Text property of a label to this function:
The label would show total sales by multiplying the values in those columns for each
record and then adding the results from all records together:
As a different example, let's say that you had sliders that were named Slider1, Slider2,
and Slider3 and a label with its Text property set to this formula:
Sum(Slider1.Value, Slider2.Value, Slider3.Value): The label would show the sum of all
values to which the sliders were set.
Overview
Most apps contain multiple screens. Use the Back and Navigate function to change
which screen is displayed. For example, set the OnSelect property of a button to a
formula that includes a Navigate function if you want to show a different screen when a
user selects that button. In that formula, you can specify a visual transition, such as Fade,
to control how one screen changes to another.
Back and Navigate change only which screen is displayed. Screens that aren't currently
displayed continue to operate behind the scenes. You can build formulas that refer to
properties of controls on other screens. For example, a user can change the value of a
slider on one screen, navigate to a different screen that uses that value in a formula, and
determine how it affects what happens in the new screen. The user can then navigate
back to the original screen and confirm that the slider has kept its value.
Context variables are also preserved when a user navigates between screens. You can
use Navigate to set one or more context variables for the screen that the formula will
display, which is the only way to set a context variable from outside the screen. You can
use this approach to pass parameters to a screen. If you've used another programming
tool, this approach is similar to passing parameters to procedures.
Use the App object's StartScreen property to control the first screen to be displayed.
Navigate
In the first argument, specify the name of the screen to display.
In the second argument, specify how the old screen changes to the new screen:
You can use Navigate to create or update context variables of the new screen. As an
optional third argument, pass a record that contains the context-variable name as a
column name and the new value for the context variable. This record is the same as the
record that you use with the UpdateContext function.
Set the OnHidden property of the old screen, the OnVisible property of the new screen,
or both to make additional changes during the transition. The App.ActiveScreen
property will be updated to reflect the change.
Navigate normally returns true but will return false if an error is encountered.
Context variables for navigation are explained in the article navigate between screens.
Back
The Back function returns to the screen that was most recently displayed.
For each Navigate call, the app tracks the screen that appeared and the transition. You
can use successive Back calls to return all the way to the screen that appeared when the
user started the app.
When the Back function runs, the inverse transition is used by default. For example, if a
screen appeared through the CoverRight transition, Back uses UnCover (which is to the
left) to return. Fade and None are their own inverses. Pass an optional argument to Back
to force a specific transition.
Back normally returns true but returns false if the user hasn't navigated to another
screen since starting the app.
Syntax
Back( [ Transition ] )
Transition - Optional. The visual transition to use between the current screen and
the previous screen. Refer to the list of valid values for this argument earlier in this
article. By default, the transition through which a screen returns is the inverse of
the transition through which it appeared.
Examples
Formula Description Result
Navigate( Details ) Displays the Details The Details screen appears quickly.
screen with no
transition or change in
value for a context
variable.
Navigate( Details, Displays the Details The current screen fades away to show
ScreenTransition.Fade ) screen with a Fade the Details screen.
transition. No value of a
context variable is
changed.
Formula Description Result
Navigate( Details, Displays the Details The current screen fades away to show
ScreenTransition.Fade, screen with a Fade the Details screen, and the context
{ ID: 12 } ) transition, and updates variable ID on that screen is set to 12.
the value of the ID
context variable to 12.
Navigate( Details, Displays the Details The current screen fades away to show
ScreenTransition.Fade, screen with a Fade the Details screen. The context variable
{ ID: 12 , Shade: Color.Red } transition. Updates the ID on the Details screen is set to 12, and
) value of the ID context the context variable Shade is set to
variable to 12, and Color.Red. If you set the Fill property of
updates the value of the a control on the Details screen to Shade,
Shade context variable that control would display as red.
to Color.Red.
Back() Displays the previous Displays the previous screen through the
screen with the default inverse transition of the transition
return transition. through which the current screen
appeared.
Back( Displays the previous Displays the previous screen through the
ScreenTransition.Cover ) screen with the Cover Cover transition, regardless of the
transition. transition through which the current
screen appeared.
Step-by-step
1. Create a blank app.
4. On Screen2, add a button, and set its OnSelect property to this formula:
Power Apps
Screen1 appears with a white background through a transition that covers to the
left.
6. On Screen1, add a button, and set its OnSelect property to this formula:
Power Apps
Back()
The second screen appears with a gray background through a transition that
uncovers to the right (the inverse of Cover).
8. Select the button on each screen repeatedly to bounce back and forth.
See also
Using context variables
Blank, Coalesce, IsBlank, and IsEmpty
functions in Power Apps
Article • 02/23/2023 • 8 minutes to read
Tests whether a value is blank or a table contains no records, and provides a way to
create blank values.
Overview
Blank is a placeholder for "no value" or "unknown value." For example, a Combo box
control's Selected property is blank if the user hasn't made a selection. Many data
sources can store and return NULL values, which are represented in Power Apps as
blank.
Any property or calculated value in Power Apps can be blank. For example, a Boolean
value normally has one of two values: true or false. But in addition to these two, it can
also be blank indicating that the state is not known. This is similar to Microsoft Excel,
where a worksheet cell starts out as blank with no contents but can hold the values
TRUE or FALSE (among others). At any time, the contents of the cell can again be
cleared, returning it to a blank state.
Empty string refers to a string that contains no characters. The Len function returns zero
for such a string and it can be written in a formulas as two double quotes with nothing
in between "" . Some controls and data sources use an empty string to indicate a "no
value" condition. To simplify app creation, the IsBlank and Coalesce functions test for
both blank values or empty strings.
In the context of the IsEmpty function, empty is specific to tables that contain no
records. The table structure may be intact, complete with column names, but no data is
in the table. A table may start as empty, take on records and no longer be empty, and
then have the records removed and again be empty.
7 Note
We are in a period of transition. Until now, blank has also been used to report
errors, making it impossible to differentiate a valid "no value" from an error. For this
reason, at this time, storing blank values is supported only for local collections. You
can store blank values in other data sources if you turn on the Formula-level error
management experimental feature under Settings > Upcoming features >
Experimental. We are actively working to finish this feature and complete the
proper separation of blank values from errors.
Blank
The Blank function returns a blank value. Use this to store a NULL value in a data source
that supports these values, effectively removing any value from the field.
IsBlank
The IsBlank function tests for a blank value or an empty string. The test includes empty
strings to ease app creation since some data sources and controls use an empty string
when there is no value present. To test specifically for a blank value use if( Value =
Blank(), ... instead of IsBlank. The IsBlank function considers empty tables as not
When enabling error handling for existing apps, consider replacing IsBlank with
IsBlankOrError to preserve existing app behavior. Prior to the addition of error handling,
a blank value was used to represent both null values from databases and error values.
Error handling separates these two interpretations of blank which could change the
behavior of existing apps that continue to use IsBlank.
Coalesce
The Coalesce function evaluates its arguments in order and returns the first value that
isn't blank or an empty string. Use this function to replace a blank value or empty string
with a different value but leave non-blank and non-empty string values unchanged. If all
the arguments are blank or empty strings then the function returns blank, making
Coalesce a good way to convert empty strings to blank values.
Coalesce( value1, value2 ) is the more concise equivalent of If( Not IsBlank( value1
), value1, Not IsBlank( value2 ), value2 ) and doesn't require value1 and value2 to
be evaluated twice. The If function returns blank if there is no "else" formula as is the
case here.
All arguments to Coalesce must be of the same type; for example, you can't mix
numbers with text strings. The return value from Coalesce is of this common type.
IsEmpty
The IsEmpty function tests whether a table contains any records. It's equivalent to using
the CountRows function and checking for zero. You can check for data-source errors by
combining IsEmpty with the Errors function.
Syntax
Blank()
Value(s) – Required. Values to test. Each value is evaluated in order until a value
that is not blank and not an empty string is found. Values after this point are not
evaluated.
IsBlank( Value )
IsEmpty( Table )
Examples
Blank
7 Note
At this time, the following example only works for local collections. You can store
blank values in other data sources if you turn on the Formula-level error
management experimental feature under Settings > Upcoming features >
Experimental. We are actively working to finish this feature and complete the
separation of blank values from errors.
3. Preview your app, click or tap the button that you added, and then close Preview.
The Cities collection appears, showing one record with "Seattle" and "Rainy":
6. Add a Label control, and set its Text property to this formula:
Power Apps
The label shows false because the Weather field contains a value ("Rainy").
7. Add a second button, and set its OnSelect property to this formula:
Power Apps
8. Preview your app, click or tap the button that you added, and then close Preview.
The Weather field of the first record in Cities is replaced with a blank, removing
the "Rainy" that was there previously.
The label shows true because the Weather field no longer contains a value.
Coalesce
Coalesce( Blank(), 1 ) Tests the return value from the Blank function, which always 1
returns a blank value. Because the first argument is blank,
evaluation continues with the next argument until a non-blank
value and non-empty string is found.
Coalesce( "", "2" ) Tests the first argument which is an empty string. Because the 2
first argument is an empty string, evaluation continues with the
next argument until a non-blank value and non-empty string is
found.
Coalesce( Blank(), Coalesce starts at the beginning of the argument list and 3
"", Blank(), "", "3", evaluates each argument in turn until a non-blank value and
"4" ) non-empty string is found. In this case, the first four arguments
all return blank or an empty string, so evaluation continues to
the fifth argument. The fifth argument is non-blank and non-
empty string, so evaluation stops here. The value of the fifth
argument is returned, and the sixth argument isn't evaluated.
Coalesce( "" ) Tests the first argument which is an empty string. Because the blank
first argument is an empty string, and there are no more
arguments, the function returns blank.
IsBlank
1. Create an app from scratch, add a text-input control, and name it FirstName.
Power Apps
If( IsBlank( FirstName.Text ), "First Name is a required field." )
By default, the Text property of a text-input control is set to "Text input". Because
the property contains a value, it isn't blank, and the label doesn't display any
message.
3. Remove all the characters from the text-input control, including any spaces.
Because the Text property no longer contains any characters, it's an empty string,
and IsBlank( FirstName.Text ) will be true. The required field message is displayed.
For information about how to perform validation by using other tools, see the Validate
function and working with data sources.
Other examples:
IsBlank( Blank() ) Tests the return value from the Blank function, which always returns true
a blank value.
IsBlank( Because the collection exists, it isn't blank, even if it doesn't contain false
AnyCollection ) any records. To check for an empty collection, use IsEmpty instead.
IsBlank( Mid( The starting character for Mid is beyond the end of the string. The true
"Hello", 17, 2 ) ) result is an empty string.
IsBlank( If( false, An If function with no ElseResult. Because the condition is always true
false ) ) false, this If always returns blank.
IsEmpty
1. Create an app from scratch, and add a Button control.
3. Preview your app, click or tap the button that you added, and then close Preview.
4. Add a second button, and set its OnSelect property to this formula:
Clear( IceCream )
5. Preview your app, click or tap the second button, and then close Preview.
The Clear function removes all the records from a collection, resulting in an empty
collection. IsEmpty( IceCream ) returns true, and CountRows( IceCream ) returns
0.
You can also use IsEmpty to test whether a calculated table is empty, as these examples
show:
IsEmpty( [ 1, 2, 3 ] The single-column table contains three records and, therefore, isn't false
) empty.
IsEmpty( [ ] ) The single-column table contains no records and is empty. true
IsEmpty( Filter( The single-column table contains no values that are greater than 5. true
[ 1, 2, 3 ], Value > The result from the filter doesn't contain any records and is empty.
5))
Boolean function in Power Apps
Article • 12/16/2022 • 2 minutes to read
Description
Use the Boolean function to convert other types to a Boolean value. A Boolean value is
true, false, or blank.
In most cases, type coercion happens automatically and the Boolean function need not
be used explicitly. For example, If( "true", 1, 0 ) will return 1 as the text string
"true" is automatically converted to a Boolean. The Boolean function is useful when an
Syntax
Boolean( String )
Boolean( StringSingleColumnTable )
Boolean( Number )
Boolean( NumberSingleColumnTable )
Number - Required. The number(s) to convert. 0 is converted to false and all other
numbers are converted to true. blank values are accepted and converted to a
blank.
Boolean( Untyped )
Examples
Basic usage
Untyped usage
Boolean( Converts the untyped value null (a JSON null) to a boolean blank
ParseJSON( " value.
{ ""bool"": null }"
).bool )
Boolean( Attempts to convert the untyped value "true" (a JSON string) error
ParseJSON( " to a boolean value, but since it isn't a valid boolean value in (invalid
{ ""bool"": "true" }" JSON, an error is returned. argument)
).bool )
Boolean( [ 1, 2, 0 ] ) Converts the single column table of numbers to a single [ true,
column table of boolean value. true, false
]
Calendar and Clock functions in Power
Apps
Article • 02/23/2023 • 2 minutes to read
Description
The Calendar and Clock functions are a set of functions that retrieve information about
the current locale.
You can use these functions to display dates and times in the language of the current
user. The single-column tables returned by Calendar and Clock functions can be used
directly with the Items property of Dropdown and Listbox controls.
Function Description
Clock.AmPm() Single-column table containing the long uppercase "AM" and "PM"
designations. If the language uses a 24-hour clock, the table will be
empty.
Clock.AmPmShort() Single-column table containing the short uppercase "A" and "P"
designations. If the language uses a 24-hour clock, the table will be
empty.
Use the Text function to format date and time values using this same information. The
Language function returns the current language and region code.
Syntax
Calendar.MonthsLong()
Calendar.MonthsShort()
Calendar.WeekdaysLong()
Calendar.WeekdaysShort()
Clock.AmPm()
Clock.AmPmShort()
Clock.IsClock24()
Examples
1. Insert a Dropdown control.
Calendar.MonthsLong()
3. Users of your app can now select a month in their own language. MonthsLong can
be replaced with any of the single-column tables that are returned by Calendar to
create weekday and time selectors.
In the United States, with Language returning "en-US", the following is returned by the
Calendar functions:
Calendar.MonthsLong() The return value contains the full [ "January", "February", "March",
name of each month, starting "April", "May", "June", "July",
with "January". "August", "September",
"October", "November",
"December" ]
Calendar.MonthsShort() The return value contains the [ "Jan", "Feb", "Mar", "Apr",
abbreviated name of each "May", "Jun", "Jul", "Aug", "Sep",
month, starting with "January". "Oct", "Nov", "Dec" ]
Calendar.WeekdaysShort() The return value contains the [ "Sun", "Mon", "Tue", "Wed",
abbreviated name of each day, "Thu", "Fri", "Sat" ]
starting with "Sunday".
Formula Description Result
Description
The Char function translates a number into a string with the corresponding ASCII
character.
If you pass a single number, the return value is the translated string version of that
number. If you pass a single-column table that contains numbers, the return value is a
single-column table of strings in a Value column. If you have a multi-column table, you
can shape it into a single-column table, as working with tables describes.
Syntax
Char( CharacterCode )
Char( CharacterCodeTable )
Examples
Single number
Char( 65 ) Returns the character that corresponds to ASCII code 65. "A"
Char( 105 ) Returns the character that corresponds to ASCII code 105. "i"
Char( 35 ) Returns the character that corresponds to ASCII code 35. "#"
Single-column table
The example in this section converts numbers from a single-column table.
Formula Result
Char( [ 65, 105 ] A single-column table with a Value column containing the following values:
) "A", "i"
Char( [ 35, 52 ] A single-column table with a Value column containing the following values:
) "#", "4"
2. Inside that gallery, add a Gallery control with a Blank Vertical layout, and then set
these properties:
3. Inside the second (vertical) gallery, add a Label control, and set these properties:
Text: FullCode.Value
Width: Parent.Width / 2
X: 0
Y: 0
Align: Center
FontWeight: Bold
Size: 24
4. Inside the second (vertical) gallery, add another Label control, and set these
properties:
You've created a chart of the first 128 ASCII characters. Characters that appear as a small
square can't be printed.
If you want to see how FullCode.Value gets its values. Let's begin with the outer
horizontal gallery. Its Items property uses the Sequence function to create 8 columns,
starting with 0 with increments of 16:
Nested within this gallery is another vertical gallery. Its Items property fills in the gap left
by the increment of 16 from the outer gallery:
To show the extended ASCII characters, it is a simple matter of changing the starting
point for the chart, set in the Sequence function for the outer gallery:
Finally, to show the characters in a different font, set the Font property of the second
label to a value such as 'Dancing Script'.
Choices function in Power Apps
Article • 02/23/2023 • 3 minutes to read
Description
The Choices function returns a table of the possible values for a lookup column.
Use the Choices function to provide a list of choices for your user to select from. This
function is commonly used with the Combo box control in edit forms.
For a lookup, the table that Choices returns matches the foreign table that's associated
with the lookup. By using Choices, you eliminate the need to add the foreign table as an
additional data source. Choices returns all columns of the foreign table.
Because Choices returns a table, you can use Filter, Sort, AddColumns, and all the other
table-manipulation functions to filter, sort, and shape the table.
At this time, you can't delegate Choices. If this limitation poses a problem in your app,
add the foreign table as a data source, and use it directly.
Choices doesn't require column names to be strings and enclosed in double quotes,
unlike the ShowColumns, Search, and other table functions. Provide the formula as if
you were referencing the column directly.
Column references must be direct to the data source. For example, if the data source is
Accounts and the lookup is SLA, the column reference would be Accounts.SLA. The
reference can't pass through a function, a variable, or a control. Furthering this example,
if Accounts is fed to a Gallery control, use the formula Gallery.Selected.SLA to reference
the SLA for the selected account. However, this reference has passed through a control,
so it can't be passed to the Columns function - you must still use Accounts.SLA.
At this time, you can use lookup columns only with SharePoint and Microsoft Dataverse.
Syntax
Choices( column-reference )
1. Create a database in Dataverse, and select the Include sample apps and data box.
Note: Table names are singular on make.powerapps.com and plural in Power Apps
Studio.
The Accounts table has a Primary Contact column, which is a lookup to the
Contacts table.
For each account, a contact is designated as the primary contact, or the primary
contact is blank.
6. Search for the Primary Contact field, select its check box, and then select Add.
The Primary Contact field appears at the bottom of the form. If the field shows an
error, select Data sources on the View tab, select the ellipsis (...) for the Accounts
data source, and then select Refresh.
7. (optional) Drag the Primary Contact field from the bottom to the top of the list of
fields.
8. In the card for Primary Contact, select the Combo box control.
The Items property of that control is set to a formula that identifies the column by
either its display name, as in the first example, or its logical name, as in the second
example:
Choices( Accounts.primarycontactid )
9. For illustration purposes, we can view the complete table returned by the Choices
function in a Data table control. On the Home tab, select New screen, and then
select Blank.
11. Set the Items property of the Data table control to this formula:
12. In the middle of the Data table control, select the link that starts Choose the
fields..., and then select the check boxes for the field or fields that you want to
show (for example, firstname and lastname).
Collect, Clear, and ClearCollect functions
in Power Apps
Article • 02/23/2023 • 4 minutes to read
Creates and clears collections and adds records to any data source.
Description
Collect
The Collect function adds records to a data source. The items to be added can be:
A single value: The value is placed in the Value field of a new record. All other
properties are left blank.
A record: Each named property is placed in the corresponding property of a new
record. All other properties are left blank.
A table: Each record of the table is added as a separate record of the data source
as described above. The table isn't added as a nested table to a record. To do this,
wrap the table in a record first.
When used with a collection, additional columns will be created as needed. The columns
for other data sources are fixed by the data source and new columns can't be added.
Collections are sometimes used to hold global variables or make a temporary copy of a
data source. Canvas apps are based on formulas that automatically recalculate as the
user interacts with an app. Collections don't enjoy this benefit and their use can make
your app harder to create and understand. Before using a collection in this manner,
review working with variables.
You can also use the Patch function to create records in a data source.
Collect returns the modified data source as a table. Collect can only be used in a
behavior formula.
Clear
The Clear function deletes all the records of a collection. The columns of the collection
will remain.
Note that Clear only operates on collections and not other data sources. You can use
RemoveIf( DataSource, true ) for this purpose. Use caution as this will remove all
records from the data source's storage and can affect other users.
ClearCollect
The ClearCollect function deletes all the records from a collection. And then adds a
different set of records to the same collection. With a single function, ClearCollect offers
the combination of Clear and then Collect.
ClearCollect returns the modified collection as a table. ClearCollect can only be used in
a behavior formula.
Delegation
When used with a data source, these functions can't be delegated. Only the first portion
of the data source will be retrieved and then the function applied. The result may not
represent the complete story. A warning may appear at authoring time to remind you of
this limitation and to suggest switching to delegable alternatives where possible. For
more information, see the delegation overview.
Syntax
Collect( DataSource, Item, ... )
DataSource – Required. The data source that you want to add data to. If it doesn't
already exist, a new collection is created.
Item(s) - Required. One or more records or tables to add to the data source.
Clear( Collection )
Collection – Required. The collection that you want to clear and then add data to.
Item(s) - Required. One or more records or tables to add to the data source.
Examples
The IceCream
collection has
also been
modified.
For step-by-step examples of how to create a collection, see Create and update a
collection.
ClearCollect( IceCream, Clear all data and then adds two records to
{ Flavor: "Chocolate", Quantity: 100 }, the IceCream collection that includes a
{ Flavor: "Vanilla", Quantity: 200 } ) quantity of chocolate and vanilla ice cream.
The
The records to be added are provided as
IceCream
individual arguments to the function.
collection
has also
been
modified.
ClearCollect( IceCream,
Same as the previous example except that
{ MyFavorites: Table( the table is wrapped in a record. The records
{ Flavor: "Chocolate", Quantity: 100 }, of the table aren't extracted and instead the
{ Flavor: "Vanilla", Quantity: 200 } ) } entire table is added as a cell of the record. The
) IceCream
collection
has also
been
modified.
Collect, Clear, and ClearCollect functions
in Power Apps
Article • 02/23/2023 • 4 minutes to read
Creates and clears collections and adds records to any data source.
Description
Collect
The Collect function adds records to a data source. The items to be added can be:
A single value: The value is placed in the Value field of a new record. All other
properties are left blank.
A record: Each named property is placed in the corresponding property of a new
record. All other properties are left blank.
A table: Each record of the table is added as a separate record of the data source
as described above. The table isn't added as a nested table to a record. To do this,
wrap the table in a record first.
When used with a collection, additional columns will be created as needed. The columns
for other data sources are fixed by the data source and new columns can't be added.
Collections are sometimes used to hold global variables or make a temporary copy of a
data source. Canvas apps are based on formulas that automatically recalculate as the
user interacts with an app. Collections don't enjoy this benefit and their use can make
your app harder to create and understand. Before using a collection in this manner,
review working with variables.
You can also use the Patch function to create records in a data source.
Collect returns the modified data source as a table. Collect can only be used in a
behavior formula.
Clear
The Clear function deletes all the records of a collection. The columns of the collection
will remain.
Note that Clear only operates on collections and not other data sources. You can use
RemoveIf( DataSource, true ) for this purpose. Use caution as this will remove all
records from the data source's storage and can affect other users.
ClearCollect
The ClearCollect function deletes all the records from a collection. And then adds a
different set of records to the same collection. With a single function, ClearCollect offers
the combination of Clear and then Collect.
ClearCollect returns the modified collection as a table. ClearCollect can only be used in
a behavior formula.
Delegation
When used with a data source, these functions can't be delegated. Only the first portion
of the data source will be retrieved and then the function applied. The result may not
represent the complete story. A warning may appear at authoring time to remind you of
this limitation and to suggest switching to delegable alternatives where possible. For
more information, see the delegation overview.
Syntax
Collect( DataSource, Item, ... )
DataSource – Required. The data source that you want to add data to. If it doesn't
already exist, a new collection is created.
Item(s) - Required. One or more records or tables to add to the data source.
Clear( Collection )
Collection – Required. The collection that you want to clear and then add data to.
Item(s) - Required. One or more records or tables to add to the data source.
Examples
The IceCream
collection has
also been
modified.
For step-by-step examples of how to create a collection, see Create and update a
collection.
ClearCollect( IceCream, Clear all data and then adds two records to
{ Flavor: "Chocolate", Quantity: 100 }, the IceCream collection that includes a
{ Flavor: "Vanilla", Quantity: 200 } ) quantity of chocolate and vanilla ice cream.
The
The records to be added are provided as
IceCream
individual arguments to the function.
collection
has also
been
modified.
ClearCollect( IceCream,
Same as the previous example except that
{ MyFavorites: Table( the table is wrapped in a record. The records
{ Flavor: "Chocolate", Quantity: 100 }, of the table aren't extracted and instead the
{ Flavor: "Vanilla", Quantity: 200 } ) } entire table is added as a cell of the record. The
) IceCream
collection
has also
been
modified.
Calendar and Clock functions in Power
Apps
Article • 02/23/2023 • 2 minutes to read
Description
The Calendar and Clock functions are a set of functions that retrieve information about
the current locale.
You can use these functions to display dates and times in the language of the current
user. The single-column tables returned by Calendar and Clock functions can be used
directly with the Items property of Dropdown and Listbox controls.
Function Description
Clock.AmPm() Single-column table containing the long uppercase "AM" and "PM"
designations. If the language uses a 24-hour clock, the table will be
empty.
Clock.AmPmShort() Single-column table containing the short uppercase "A" and "P"
designations. If the language uses a 24-hour clock, the table will be
empty.
Use the Text function to format date and time values using this same information. The
Language function returns the current language and region code.
Syntax
Calendar.MonthsLong()
Calendar.MonthsShort()
Calendar.WeekdaysLong()
Calendar.WeekdaysShort()
Clock.AmPm()
Clock.AmPmShort()
Clock.IsClock24()
Examples
1. Insert a Dropdown control.
Calendar.MonthsLong()
3. Users of your app can now select a month in their own language. MonthsLong can
be replaced with any of the single-column tables that are returned by Calendar to
create weekday and time selectors.
In the United States, with Language returning "en-US", the following is returned by the
Calendar functions:
Calendar.MonthsLong() The return value contains the full [ "January", "February", "March",
name of each month, starting "April", "May", "June", "July",
with "January". "August", "September",
"October", "November",
"December" ]
Calendar.MonthsShort() The return value contains the [ "Jan", "Feb", "Mar", "Apr",
abbreviated name of each "May", "Jun", "Jul", "Aug", "Sep",
month, starting with "January". "Oct", "Nov", "Dec" ]
Calendar.WeekdaysShort() The return value contains the [ "Sun", "Mon", "Tue", "Wed",
abbreviated name of each day, "Thu", "Fri", "Sat" ]
starting with "Sunday".
Formula Description Result
Tests whether a value is blank or a table contains no records, and provides a way to
create blank values.
Overview
Blank is a placeholder for "no value" or "unknown value." For example, a Combo box
control's Selected property is blank if the user hasn't made a selection. Many data
sources can store and return NULL values, which are represented in Power Apps as
blank.
Any property or calculated value in Power Apps can be blank. For example, a Boolean
value normally has one of two values: true or false. But in addition to these two, it can
also be blank indicating that the state is not known. This is similar to Microsoft Excel,
where a worksheet cell starts out as blank with no contents but can hold the values
TRUE or FALSE (among others). At any time, the contents of the cell can again be
cleared, returning it to a blank state.
Empty string refers to a string that contains no characters. The Len function returns zero
for such a string and it can be written in a formulas as two double quotes with nothing
in between "" . Some controls and data sources use an empty string to indicate a "no
value" condition. To simplify app creation, the IsBlank and Coalesce functions test for
both blank values or empty strings.
In the context of the IsEmpty function, empty is specific to tables that contain no
records. The table structure may be intact, complete with column names, but no data is
in the table. A table may start as empty, take on records and no longer be empty, and
then have the records removed and again be empty.
7 Note
We are in a period of transition. Until now, blank has also been used to report
errors, making it impossible to differentiate a valid "no value" from an error. For this
reason, at this time, storing blank values is supported only for local collections. You
can store blank values in other data sources if you turn on the Formula-level error
management experimental feature under Settings > Upcoming features >
Experimental. We are actively working to finish this feature and complete the
proper separation of blank values from errors.
Blank
The Blank function returns a blank value. Use this to store a NULL value in a data source
that supports these values, effectively removing any value from the field.
IsBlank
The IsBlank function tests for a blank value or an empty string. The test includes empty
strings to ease app creation since some data sources and controls use an empty string
when there is no value present. To test specifically for a blank value use if( Value =
Blank(), ... instead of IsBlank. The IsBlank function considers empty tables as not
When enabling error handling for existing apps, consider replacing IsBlank with
IsBlankOrError to preserve existing app behavior. Prior to the addition of error handling,
a blank value was used to represent both null values from databases and error values.
Error handling separates these two interpretations of blank which could change the
behavior of existing apps that continue to use IsBlank.
Coalesce
The Coalesce function evaluates its arguments in order and returns the first value that
isn't blank or an empty string. Use this function to replace a blank value or empty string
with a different value but leave non-blank and non-empty string values unchanged. If all
the arguments are blank or empty strings then the function returns blank, making
Coalesce a good way to convert empty strings to blank values.
Coalesce( value1, value2 ) is the more concise equivalent of If( Not IsBlank( value1
), value1, Not IsBlank( value2 ), value2 ) and doesn't require value1 and value2 to
be evaluated twice. The If function returns blank if there is no "else" formula as is the
case here.
All arguments to Coalesce must be of the same type; for example, you can't mix
numbers with text strings. The return value from Coalesce is of this common type.
IsEmpty
The IsEmpty function tests whether a table contains any records. It's equivalent to using
the CountRows function and checking for zero. You can check for data-source errors by
combining IsEmpty with the Errors function.
Syntax
Blank()
Value(s) – Required. Values to test. Each value is evaluated in order until a value
that is not blank and not an empty string is found. Values after this point are not
evaluated.
IsBlank( Value )
IsEmpty( Table )
Examples
Blank
7 Note
At this time, the following example only works for local collections. You can store
blank values in other data sources if you turn on the Formula-level error
management experimental feature under Settings > Upcoming features >
Experimental. We are actively working to finish this feature and complete the
separation of blank values from errors.
3. Preview your app, click or tap the button that you added, and then close Preview.
The Cities collection appears, showing one record with "Seattle" and "Rainy":
6. Add a Label control, and set its Text property to this formula:
Power Apps
The label shows false because the Weather field contains a value ("Rainy").
7. Add a second button, and set its OnSelect property to this formula:
Power Apps
8. Preview your app, click or tap the button that you added, and then close Preview.
The Weather field of the first record in Cities is replaced with a blank, removing
the "Rainy" that was there previously.
The label shows true because the Weather field no longer contains a value.
Coalesce
Coalesce( Blank(), 1 ) Tests the return value from the Blank function, which always 1
returns a blank value. Because the first argument is blank,
evaluation continues with the next argument until a non-blank
value and non-empty string is found.
Coalesce( "", "2" ) Tests the first argument which is an empty string. Because the 2
first argument is an empty string, evaluation continues with the
next argument until a non-blank value and non-empty string is
found.
Coalesce( Blank(), Coalesce starts at the beginning of the argument list and 3
"", Blank(), "", "3", evaluates each argument in turn until a non-blank value and
"4" ) non-empty string is found. In this case, the first four arguments
all return blank or an empty string, so evaluation continues to
the fifth argument. The fifth argument is non-blank and non-
empty string, so evaluation stops here. The value of the fifth
argument is returned, and the sixth argument isn't evaluated.
Coalesce( "" ) Tests the first argument which is an empty string. Because the blank
first argument is an empty string, and there are no more
arguments, the function returns blank.
IsBlank
1. Create an app from scratch, add a text-input control, and name it FirstName.
Power Apps
If( IsBlank( FirstName.Text ), "First Name is a required field." )
By default, the Text property of a text-input control is set to "Text input". Because
the property contains a value, it isn't blank, and the label doesn't display any
message.
3. Remove all the characters from the text-input control, including any spaces.
Because the Text property no longer contains any characters, it's an empty string,
and IsBlank( FirstName.Text ) will be true. The required field message is displayed.
For information about how to perform validation by using other tools, see the Validate
function and working with data sources.
Other examples:
IsBlank( Blank() ) Tests the return value from the Blank function, which always returns true
a blank value.
IsBlank( Because the collection exists, it isn't blank, even if it doesn't contain false
AnyCollection ) any records. To check for an empty collection, use IsEmpty instead.
IsBlank( Mid( The starting character for Mid is beyond the end of the string. The true
"Hello", 17, 2 ) ) result is an empty string.
IsBlank( If( false, An If function with no ElseResult. Because the condition is always true
false ) ) false, this If always returns blank.
IsEmpty
1. Create an app from scratch, and add a Button control.
3. Preview your app, click or tap the button that you added, and then close Preview.
4. Add a second button, and set its OnSelect property to this formula:
Clear( IceCream )
5. Preview your app, click or tap the second button, and then close Preview.
The Clear function removes all the records from a collection, resulting in an empty
collection. IsEmpty( IceCream ) returns true, and CountRows( IceCream ) returns
0.
You can also use IsEmpty to test whether a calculated table is empty, as these examples
show:
IsEmpty( [ 1, 2, 3 ] The single-column table contains three records and, therefore, isn't false
) empty.
IsEmpty( [ ] ) The single-column table contains no records and is empty. true
IsEmpty( Filter( The single-column table contains no values that are greater than 5. true
[ 1, 2, 3 ], Value > The result from the filter doesn't contain any records and is empty.
5))
Collect, Clear, and ClearCollect functions
in Power Apps
Article • 02/23/2023 • 4 minutes to read
Creates and clears collections and adds records to any data source.
Description
Collect
The Collect function adds records to a data source. The items to be added can be:
A single value: The value is placed in the Value field of a new record. All other
properties are left blank.
A record: Each named property is placed in the corresponding property of a new
record. All other properties are left blank.
A table: Each record of the table is added as a separate record of the data source
as described above. The table isn't added as a nested table to a record. To do this,
wrap the table in a record first.
When used with a collection, additional columns will be created as needed. The columns
for other data sources are fixed by the data source and new columns can't be added.
Collections are sometimes used to hold global variables or make a temporary copy of a
data source. Canvas apps are based on formulas that automatically recalculate as the
user interacts with an app. Collections don't enjoy this benefit and their use can make
your app harder to create and understand. Before using a collection in this manner,
review working with variables.
You can also use the Patch function to create records in a data source.
Collect returns the modified data source as a table. Collect can only be used in a
behavior formula.
Clear
The Clear function deletes all the records of a collection. The columns of the collection
will remain.
Note that Clear only operates on collections and not other data sources. You can use
RemoveIf( DataSource, true ) for this purpose. Use caution as this will remove all
records from the data source's storage and can affect other users.
ClearCollect
The ClearCollect function deletes all the records from a collection. And then adds a
different set of records to the same collection. With a single function, ClearCollect offers
the combination of Clear and then Collect.
ClearCollect returns the modified collection as a table. ClearCollect can only be used in
a behavior formula.
Delegation
When used with a data source, these functions can't be delegated. Only the first portion
of the data source will be retrieved and then the function applied. The result may not
represent the complete story. A warning may appear at authoring time to remind you of
this limitation and to suggest switching to delegable alternatives where possible. For
more information, see the delegation overview.
Syntax
Collect( DataSource, Item, ... )
DataSource – Required. The data source that you want to add data to. If it doesn't
already exist, a new collection is created.
Item(s) - Required. One or more records or tables to add to the data source.
Clear( Collection )
Collection – Required. The collection that you want to clear and then add data to.
Item(s) - Required. One or more records or tables to add to the data source.
Examples
The IceCream
collection has
also been
modified.
For step-by-step examples of how to create a collection, see Create and update a
collection.
ClearCollect( IceCream, Clear all data and then adds two records to
{ Flavor: "Chocolate", Quantity: 100 }, the IceCream collection that includes a
{ Flavor: "Vanilla", Quantity: 200 } ) quantity of chocolate and vanilla ice cream.
The
The records to be added are provided as
IceCream
individual arguments to the function.
collection
has also
been
modified.
ClearCollect( IceCream,
Same as the previous example except that
{ MyFavorites: Table( the table is wrapped in a record. The records
{ Flavor: "Chocolate", Quantity: 100 }, of the table aren't extracted and instead the
{ Flavor: "Vanilla", Quantity: 200 } ) } entire table is added as a cell of the record. The
) IceCream
collection
has also
been
modified.
Color enumeration and ColorFade,
ColorValue, and RGBA functions in
Power Apps
Article • 02/23/2023 • 7 minutes to read
Use built-in color values, define custom colors, and use the alpha channel.
Description
By using the Color enumeration, you can easily access the colors that are defined by
HTML's Cascading Style Sheets (CSS). For example, Color.Red returns pure red. You can
find a list of these colors at the end of this topic.
The ColorValue function returns a color based on a color string in a CSS. The string can
take any of these forms:
CSS color name: "RoxyBrown" and "OliveDrab" are examples. These names don't
include spaces. The list of supported colors appears later in this topic.
6-digit hex value: As an example "#ffd700" is the same as "Gold". The string is in
the format "#rrggbb" where rr is the red portion in two hexadecimal digits, gg is
the green, and bb is the blue.
8-digit hex value: As an example, "#ff7f5080" is the same as "Coral" with a 50%
alpha channel. The string is in the format "#rrggbbaa" where rr, gg, and bb are
identical to the 6-digit form. The alpha channel is represented by aa: 00 represents
fully transparent, and ff represents fully opaque.
The RGBA function returns a color based on red, green, and blue components. The
function also includes an alpha channel for mixing colors of controls that are layered in
front of one another. An alpha channel varies from 0 or 0% (which is fully transparent
and invisible) to 1 or 100% (which is fully opaque and completely blocks out any layers
behind a control).
The ColorFade function returns a brighter or darker version of a color. The amount of
fade varies from -1 (which fully darkens a color to black) to 0 (which doesn't affect the
color) to 1 (which fully brightens a color to white).
Alpha channel
In a canvas app, you can layer controls in front of one another and specify the
transparency of a control to any controls that are behind it. As a result, colors will blend
through the layers. For example, this diagram shows how the three primary colors mix
with an alpha setting of 50%:
You can also blend images in file formats that support alpha channels. For example, you
can't blend .jpeg files, but you can blend .png files. The next graphic shows the same
red, green, and blue colors from the previous example, but the red color appears as a
squiggle (instead of a circle) in a .png file with a 50% alpha channel:
If you specify a Color enumeration value or you build a ColorValue formula with a color
name or a 6-digit hexadecimal value, the alpha setting is 100%, which is fully opaque.
Syntax
Color.ColorName
ColorName - Required. A Cascading Style Sheet (CSS) color name. The list of
possible enumeration values appears at the end of this topic.
ColorValue( CSSColor )
CSSColor - Required. A Cascading Style Sheet (CSS) color definition. You can
specify either a name, such as OliveDrab, or a hex value, such as #6b8e23 or
#7fffd420. Hex values can take the form of either #rrggbb or #rrggbbaa.
ColorValue( Untyped )
Red, Green, Blue - Required. Color-component values, which range from 0 (no
saturation) to 255 (full saturation).
Alpha - Required. Alpha component, which ranges from 0 (fully transparent) to 1
(fully opaque). You can also use a percentage, 0% to 100%.
Color - Required. A color value such as Color.Red or the output from ColorValue or
RGBA.
FadeAmount - Required. A number between -1 and 1. -1 fully darkens a color to
black, 0 doesn't affect the color, and 1 fully brightens a color to white. You can also
use a percentage from -100% to 100%.
Built-in colors
Color enumeration ColorValue RGBA Color
Swatch
ColorValue(
"Transparent" )
Use built-in color values, define custom colors, and use the alpha channel.
Description
By using the Color enumeration, you can easily access the colors that are defined by
HTML's Cascading Style Sheets (CSS). For example, Color.Red returns pure red. You can
find a list of these colors at the end of this topic.
The ColorValue function returns a color based on a color string in a CSS. The string can
take any of these forms:
CSS color name: "RoxyBrown" and "OliveDrab" are examples. These names don't
include spaces. The list of supported colors appears later in this topic.
6-digit hex value: As an example "#ffd700" is the same as "Gold". The string is in
the format "#rrggbb" where rr is the red portion in two hexadecimal digits, gg is
the green, and bb is the blue.
8-digit hex value: As an example, "#ff7f5080" is the same as "Coral" with a 50%
alpha channel. The string is in the format "#rrggbbaa" where rr, gg, and bb are
identical to the 6-digit form. The alpha channel is represented by aa: 00 represents
fully transparent, and ff represents fully opaque.
The RGBA function returns a color based on red, green, and blue components. The
function also includes an alpha channel for mixing colors of controls that are layered in
front of one another. An alpha channel varies from 0 or 0% (which is fully transparent
and invisible) to 1 or 100% (which is fully opaque and completely blocks out any layers
behind a control).
The ColorFade function returns a brighter or darker version of a color. The amount of
fade varies from -1 (which fully darkens a color to black) to 0 (which doesn't affect the
color) to 1 (which fully brightens a color to white).
Alpha channel
In a canvas app, you can layer controls in front of one another and specify the
transparency of a control to any controls that are behind it. As a result, colors will blend
through the layers. For example, this diagram shows how the three primary colors mix
with an alpha setting of 50%:
You can also blend images in file formats that support alpha channels. For example, you
can't blend .jpeg files, but you can blend .png files. The next graphic shows the same
red, green, and blue colors from the previous example, but the red color appears as a
squiggle (instead of a circle) in a .png file with a 50% alpha channel:
If you specify a Color enumeration value or you build a ColorValue formula with a color
name or a 6-digit hexadecimal value, the alpha setting is 100%, which is fully opaque.
Syntax
Color.ColorName
ColorName - Required. A Cascading Style Sheet (CSS) color name. The list of
possible enumeration values appears at the end of this topic.
ColorValue( CSSColor )
CSSColor - Required. A Cascading Style Sheet (CSS) color definition. You can
specify either a name, such as OliveDrab, or a hex value, such as #6b8e23 or
#7fffd420. Hex values can take the form of either #rrggbb or #rrggbbaa.
ColorValue( Untyped )
Red, Green, Blue - Required. Color-component values, which range from 0 (no
saturation) to 255 (full saturation).
Alpha - Required. Alpha component, which ranges from 0 (fully transparent) to 1
(fully opaque). You can also use a percentage, 0% to 100%.
Color - Required. A color value such as Color.Red or the output from ColorValue or
RGBA.
FadeAmount - Required. A number between -1 and 1. -1 fully darkens a color to
black, 0 doesn't affect the color, and 1 fully brightens a color to white. You can also
use a percentage from -100% to 100%.
Built-in colors
Color enumeration ColorValue RGBA Color
Swatch
ColorValue(
"Transparent" )
Use built-in color values, define custom colors, and use the alpha channel.
Description
By using the Color enumeration, you can easily access the colors that are defined by
HTML's Cascading Style Sheets (CSS). For example, Color.Red returns pure red. You can
find a list of these colors at the end of this topic.
The ColorValue function returns a color based on a color string in a CSS. The string can
take any of these forms:
CSS color name: "RoxyBrown" and "OliveDrab" are examples. These names don't
include spaces. The list of supported colors appears later in this topic.
6-digit hex value: As an example "#ffd700" is the same as "Gold". The string is in
the format "#rrggbb" where rr is the red portion in two hexadecimal digits, gg is
the green, and bb is the blue.
8-digit hex value: As an example, "#ff7f5080" is the same as "Coral" with a 50%
alpha channel. The string is in the format "#rrggbbaa" where rr, gg, and bb are
identical to the 6-digit form. The alpha channel is represented by aa: 00 represents
fully transparent, and ff represents fully opaque.
The RGBA function returns a color based on red, green, and blue components. The
function also includes an alpha channel for mixing colors of controls that are layered in
front of one another. An alpha channel varies from 0 or 0% (which is fully transparent
and invisible) to 1 or 100% (which is fully opaque and completely blocks out any layers
behind a control).
The ColorFade function returns a brighter or darker version of a color. The amount of
fade varies from -1 (which fully darkens a color to black) to 0 (which doesn't affect the
color) to 1 (which fully brightens a color to white).
Alpha channel
In a canvas app, you can layer controls in front of one another and specify the
transparency of a control to any controls that are behind it. As a result, colors will blend
through the layers. For example, this diagram shows how the three primary colors mix
with an alpha setting of 50%:
You can also blend images in file formats that support alpha channels. For example, you
can't blend .jpeg files, but you can blend .png files. The next graphic shows the same
red, green, and blue colors from the previous example, but the red color appears as a
squiggle (instead of a circle) in a .png file with a 50% alpha channel:
If you specify a Color enumeration value or you build a ColorValue formula with a color
name or a 6-digit hexadecimal value, the alpha setting is 100%, which is fully opaque.
Syntax
Color.ColorName
ColorName - Required. A Cascading Style Sheet (CSS) color name. The list of
possible enumeration values appears at the end of this topic.
ColorValue( CSSColor )
CSSColor - Required. A Cascading Style Sheet (CSS) color definition. You can
specify either a name, such as OliveDrab, or a hex value, such as #6b8e23 or
#7fffd420. Hex values can take the form of either #rrggbb or #rrggbbaa.
ColorValue( Untyped )
Red, Green, Blue - Required. Color-component values, which range from 0 (no
saturation) to 255 (full saturation).
Alpha - Required. Alpha component, which ranges from 0 (fully transparent) to 1
(fully opaque). You can also use a percentage, 0% to 100%.
Color - Required. A color value such as Color.Red or the output from ColorValue or
RGBA.
FadeAmount - Required. A number between -1 and 1. -1 fully darkens a color to
black, 0 doesn't affect the color, and 1 fully brightens a color to white. You can also
use a percentage from -100% to 100%.
Built-in colors
Color enumeration ColorValue RGBA Color
Swatch
ColorValue(
"Transparent" )
Returns information about the app's environment, such as where the user is located in
the world and which screen is displayed.
Signals typically return a record of information. You can use and store this information
as a record, or you can extract individual properties by using the . operator.
7 Note
The Acceleration and Compass functions return accurate values in a native player
such as on iOS or Android, but those functions return zero values as you create or
modify an app in the browser.
Acceleration
The Acceleration signal returns the device's acceleration in three dimensions relative to
the device's screen. Acceleration is measured in g units of 9.81 m/second2 or 32.2
ft/second2 (the acceleration that the Earth imparts to objects at its surface due to
gravity).
Property Description
Property Description
App.ActiveScreen Screen that's showing. Returns a screen object, which you can use to
reference properties of the screen or compare to another screen to
determine which screen is showing. You can use the Back or Navigate
function to change the screen that's showing.
Compass
The Compass signal returns the compass heading of the top of the screen. The heading
is based on magnetic north.
Property Description
Connection
The Connection signal returns the information about the network connection. When on
a metered connection, you may want to limit how much data you send or receive over
the network.
Property Description
Connection.Connected Returns a Boolean true or false value that indicates whether the device
is connected to a network.
Connection.Metered Returns a Boolean true or false value that indicates whether the
connection is metered.
Location
The Location signal returns the location of the device based on the Global Positioning
System (GPS) and other device information, such as cell-tower communications and IP
address.
When a user accesses the location information for the first time, the device may prompt
that user to allow access to this information.
Property Description
Location.Altitude Returns a number that indicates the altitude, measured in meters, above
sea level.
Location.Latitude Returns a number, from –90 to 90, that indicates the latitude, as measured
in degrees from the equator. A positive number indicates a location that's
north of the equator.
Location.Longitude Returns a number, from –180 to 180, that indicates the longitude, as
measured in degrees from Greenwich, England. A positive number indicates
a location that's east of Greenwhich.
Examples
In a baseball field, a pitcher throws a phone from the pitcher's mound to a catcher at
home plate. The phone is lying flat with respect to the ground, the top of the screen is
pointed at the catcher, and the pitcher adds no spin. At this location, the phone has
cellular network service that's metered but no WiFi. The PlayBall screen is displayed.
Acceleration.Y Returns the acceleration of the device front to 8.2, while the
back. The pitcher initially gives the device a large pitcher throws the
acceleration when throwing the device, going device.
Acceleration.Z Returns the acceleration of the device top to 0, before the pitcher
bottom. While in the air, the device experiences throws the device.
Description
The Concatenate function concatenates a mix of individual strings and a single-column
table of strings. When you use this function with individual strings, it's equivalent to
using the & operator.
The Concat function concatenates the result of a formula applied across all the records
of a table, resulting in a single string. Use this function to summarize the strings of a
table, just as the Sum function does for numbers.
Fields of the record currently being processed are available within the formula. Use the
ThisRecord operator or simply reference fields by name as you would any other value.
The As operator can also be used to name the record being processed which can help
make your formula easier to understand and make nested records accessible. For more
information, see the examples below and working with record scope.
Use the Split or MatchAll function to split a string into a table of substrings.
Syntax
Concat( Table, Formula, separator)
Examples
The examples in this section use these global variables:
FirstName = "Jane"
LastName = "Doe"
Products =
To create these global variables in an app, insert a Button control, and set its OnSelect
property to this formula:
Power Apps
Set( Products,
Table(
Select the button (by clicking it while you hold down the Alt key).
Concat function
For these examples, set the Text property of a label to a formula from the first column of
the next table.
Concat( Products, Name, ", " ) Evaluates the expression Name "'Violin', 'Cello', 'Trumpet'"
for each record of Products and
concatenates the results
together into a single text string
separated by ", ".
Concat( Products, "'" & Name & Evaluates the expression "'" & "'Violin', 'Cello', 'Trumpet'"
"'", ", " ) Name & "'" for each record of
Products and concatenates the
results together into a single
text string separated by ", ".
Description
The Concatenate function concatenates a mix of individual strings and a single-column
table of strings. When you use this function with individual strings, it's equivalent to
using the & operator.
The Concat function concatenates the result of a formula applied across all the records
of a table, resulting in a single string. Use this function to summarize the strings of a
table, just as the Sum function does for numbers.
Fields of the record currently being processed are available within the formula. Use the
ThisRecord operator or simply reference fields by name as you would any other value.
The As operator can also be used to name the record being processed which can help
make your formula easier to understand and make nested records accessible. For more
information, see the examples below and working with record scope.
Use the Split or MatchAll function to split a string into a table of substrings.
Syntax
Concat( Table, Formula, separator)
Examples
The examples in this section use these global variables:
FirstName = "Jane"
LastName = "Doe"
Products =
To create these global variables in an app, insert a Button control, and set its OnSelect
property to this formula:
Power Apps
Set( Products,
Table(
Select the button (by clicking it while you hold down the Alt key).
Concat function
For these examples, set the Text property of a label to a formula from the first column of
the next table.
Concat( Products, Name, ", " ) Evaluates the expression Name "'Violin', 'Cello', 'Trumpet'"
for each record of Products and
concatenates the results
together into a single text string
separated by ", ".
Concat( Products, "'" & Name & Evaluates the expression "'" & "'Violin', 'Cello', 'Trumpet'"
"'", ", " ) Name & "'" for each record of
Products and concatenates the
results together into a single
text string separated by ", ".
Description
The Concurrent function allows multiple formulas specified within the same property to
be evaluated at the same time if they have connector or Dataverse calls. Normally,
multiple formulas are evaluated by chaining them together with the ; (semi-colon)
operator, which evaluates each formula sequentially. With the Concurrent function, the
app will evaluate all formulas within a property concurrently even after using the ;
operator. This concurrency will help users wait less for the same result.
In the OnStart property of your app, use Concurrent to improve performance when the
app loads data. When data calls don't start until the previous calls finish, the app must
wait for the sum of all request times. If data calls start at the same time, the app needs
to wait only for the longest request time. Web browsers often improve performance by
performing network calls concurrently.
You can't predict the order in which formulas within the Concurrent function start and
end evaluation. Formulas within the Concurrent function shouldn't contain
dependencies on other formulas within the same Concurrent function, and Power Apps
shows an error if you try. From within, you can safely take dependencies on formulas
outside the Concurrent function because they will complete before the Concurrent
function starts. Formulas after the Concurrent function can safely take dependencies on
formulas within: they'll all complete before the Concurrent function finishes and moves
on to the next formula in a chain (if you use the ; operator). Watch out for subtle order
dependencies if you're calling functions or service methods that have side effects.
You can chain formulas together with the ; operator within an argument to Concurrent.
For example, Concurrent( Set( a, 1 ); Set( b, a+1 ), Set( x, 2 ); Set( y, x+2 ) ) evaluates
Set( a, 1 ); Set( b, a+1 ) concurrently with Set( x, 2 ); Set( y, x+2 ). In this case, the
dependencies within the formulas are fine: a will be set before b, and x will be set before
y.
Depending on the device or browser in which the app is running, only a handful of
formulas might actually be evaluated concurrently. Concurrent uses the available
capabilities and won't finish until all formulas have been evaluated.
If you enable Formula-level error management (in advanced settings), the first error
encountered in argument order is returned from Concurrent; otherwise, blank is
returned. If all formulas are successful, true is returned. If one formula fails, the rest of
that formula stops, but other formulas continue evaluating.
Syntax
Concurrent( Formula1, Formula2 [, ...] )
Examples
This example uses four tables from the sample Adventure Works database on SQL
Azure. After you create the database, connect to it from Power Apps using the fully
qualified server name (for example, srvname.database.windows.net):
2. Add a Button control, and set its OnSelect property to this formula:
Power Apps
5. While holding down the Alt key, select the button, and then watch the network
traffic.
The tools show four requests performed in series, similar to this example. Actual
times have been removed as they will vary wildly. The graph shows that each call
starts after the last has finished:
6. Save, close, and reopen the app.
Power Apps caches data, so selecting the button again won't necessarily cause four
new requests. Each time you want to test performance, close and reopen your app.
If you turned network throttling on, you may want to turn it off until you're ready
for another test.
7. Add a second Button control, and set its OnSelect property to this formula:
Power Apps
Concurrent(
Note that you added the same ClearCollect calls to the first button, but they're
wrapped in a Concurrent function and separated by commas this time.
10. While holding down the Alt key, select the second button, and then watch the
network traffic.
The tools show four requests performed concurrently, similar to this example.
Again, actual times have been removed as they will vary wildly. The graph shows
that all the calls start at about the same time and do not wait for the previous one
to finish:
These graphs are based on the same scale. By using Concurrent, you halved the
total amount of time these operations took to finish.
11. Save, close, and reopen the app.
Race condition
1. Add a connection to the Microsoft Translator service to your app.
2. Add a Text input control, and rename it TextInput1 if it has a different name.
3. Add a Button control, and set its OnSelect property to this formula:
Power Apps
Concurrent(
);
Collect( Results,
Input: TextInput1.Text,
4. Add a Data table control, and set its Items property to Results.
5. On the Properties tab of the right pane, select Edit fields to open the Fields pane.
6. In the list of fields, select the check box for each field to show them all in the data
table.
7. (optional) Drag the Input field to the top of the list, and drag the FrenchFaster
field to the bottom of the list.
8. In the Text input control, type or paste a phrase to translate.
9. While holding down the Alt key, select the button multiple times to fill the table.
In some cases, the French translation is faster than the German translation, and
vice versa. Both start at the same time, but one returns before the other for a
variety of reasons, including network latency and server-side processing.
A race condition would occur if the app depended on one translation ending
first. Fortunately, Power Apps flags most timing dependencies that it can detect.
Confirm function in Power Apps
Article • 02/23/2023 • 2 minutes to read
Description
7 Note
At this time, the Confirm function is only available when writing Power Fx
commands for model-driven apps.
The Confirm function displays a dialog box on top of the current screen. Two buttons
are provided: a confirm button and a cancel button, which default to localized versions
of "OK" and "Cancel" respectively. The user must confirm or cancel before the dialog
box is dismissed and the function returns. Besides the dialog button, cancel can also be
selected with the Esc key or other gestures that are platform specific.
The Message parameter is displayed in the body of the dialog box. If the message is
long, it may be truncated, or a scroll bar may be provided.
Use the OptionsRecord parameter to specify options for the dialog box. Not all options
are available on every platform and are handled on a best effort basis. These options are
not supported in canvas apps.
ConfirmButton The text to display on the confirm button, replacing the default, localized "OK"
text.
CancelButton The text to display on the cancel button, replacing the default, localized
"Cancel" text.
Title The text to display as the title of the dialog box. A larger, bolder font than the
message font may be used to display this text. The text will be truncated if it is
long.
Subtitle The text to display as the subtitle of the dialog box. A larger, bolder font than
the message font may be used to display this text. The text will be truncated if it
is long.
Confirm returns true if the confirm button was selected, false otherwise.
Use the Notify function to display a message banner at the top of the app that doesn't
need to be dismissed.
Syntax
Confirm( Message [, OptionsRecord ] )
Examples
Power Apps
Simple confirmation dialog, asking the user to confirm deletion of a record before it's
removed. Unless the user presses the "OK" button, the record won't be deleted.
Power Apps
Power Apps
Set( FavColor,
),
"Red",
"Green"
Asks the user for their favorite color, capturing the result into a global variable. The
result that will be placed in FavColor will be the text string "Red" or "Green". As the
confirm choice, "Red" is the default. This only works on platforms that support
ConfirmButton and CancelButton options.
Power Apps
Displays a message much like the Notify function does, but is modal and requires the
user to select a button to proceed. Use when it's important that the user acknowledges
the message before proceeding. In this situation, which button was selected isn't
important and the result isn't checked.
Acceleration, App, Compass,
Connection, and Location signals in
Power Apps
Article • 02/23/2023 • 4 minutes to read
Returns information about the app's environment, such as where the user is located in
the world and which screen is displayed.
Signals typically return a record of information. You can use and store this information
as a record, or you can extract individual properties by using the . operator.
7 Note
The Acceleration and Compass functions return accurate values in a native player
such as on iOS or Android, but those functions return zero values as you create or
modify an app in the browser.
Acceleration
The Acceleration signal returns the device's acceleration in three dimensions relative to
the device's screen. Acceleration is measured in g units of 9.81 m/second2 or 32.2
ft/second2 (the acceleration that the Earth imparts to objects at its surface due to
gravity).
Property Description
Property Description
App.ActiveScreen Screen that's showing. Returns a screen object, which you can use to
reference properties of the screen or compare to another screen to
determine which screen is showing. You can use the Back or Navigate
function to change the screen that's showing.
Compass
The Compass signal returns the compass heading of the top of the screen. The heading
is based on magnetic north.
Property Description
Connection
The Connection signal returns the information about the network connection. When on
a metered connection, you may want to limit how much data you send or receive over
the network.
Property Description
Connection.Connected Returns a Boolean true or false value that indicates whether the device
is connected to a network.
Connection.Metered Returns a Boolean true or false value that indicates whether the
connection is metered.
Location
The Location signal returns the location of the device based on the Global Positioning
System (GPS) and other device information, such as cell-tower communications and IP
address.
When a user accesses the location information for the first time, the device may prompt
that user to allow access to this information.
Property Description
Location.Altitude Returns a number that indicates the altitude, measured in meters, above
sea level.
Location.Latitude Returns a number, from –90 to 90, that indicates the latitude, as measured
in degrees from the equator. A positive number indicates a location that's
north of the equator.
Location.Longitude Returns a number, from –180 to 180, that indicates the longitude, as
measured in degrees from Greenwich, England. A positive number indicates
a location that's east of Greenwhich.
Examples
In a baseball field, a pitcher throws a phone from the pitcher's mound to a catcher at
home plate. The phone is lying flat with respect to the ground, the top of the screen is
pointed at the catcher, and the pitcher adds no spin. At this location, the phone has
cellular network service that's metered but no WiFi. The PlayBall screen is displayed.
Acceleration.Y Returns the acceleration of the device front to 8.2, while the
back. The pitcher initially gives the device a large pitcher throws the
acceleration when throwing the device, going device.
Acceleration.Z Returns the acceleration of the device top to 0, before the pitcher
bottom. While in the air, the device experiences throws the device.
Counts all records in a table, or counts all records that satisfy a condition.
Description
The Count function counts the number of records that contain a number in a single-
column table.
The CountA function counts the number of records that aren't blank in a single-column
table. This function includes empty text ("") in the count.
The CountIf function counts the number of records in a table that are true for a logical
formula. The formula can reference columns of the table.
You need to enable the Enhanced delegation for Microsoft Dataverse option in the
advance settings to make CountIf and CountRows functions delegation to work. To
enable the option:
) Important
There is a 50K delegation limit if you use CountRows and CountIf functions
with filters. There is no hard limit on the CountRows function when extracted
directly from the data source because of the cached count that Dataverse
keeps.
If the CountRows(<Data Source>) function is used without filtering, the count
might not be 100% accurate, because the cached count updates periodically.
If you need precise count and expect the result to be under the aggregate
limit, you can bypass the cached count via CountIf(<Data Source>, True) .
Syntax
Count( SingleColumnTable )
CountA( SingleColumnTable )
CountRows( Table )
Example
1. Import or create a collection named Inventory, as the first subprocedure in Show
images and text in a gallery describes.
The label shows 2 because two products (Ganymede and Callisto) have fewer than
30 units in stock.
3. Add another label, and set its Text property to this formula:
CountA(Inventory.UnitsInStock)
The label shows 5, the number of non-empty cells in the UnitsInStock column.
4. Add another label, and set its Text property to this formula:
CountRows(Inventory)
Description
Primary functions
The Cos function returns the cosine of its argument, an angle specified in radians.
The Cot function returns the cotangent of its argument, an angle specified in radians.
The Sin function returns the sine of its argument, an angle specified in radians.
The Tan function returns the tangent of its argument, an angle specified in radians.
Inverse functions
The Acos function returns the arccosine, or inverse cosine, of its argument. The
arccosine is the angle whose cosine is the argument. The returned angle is given in
radians in the range 0 (zero) to π.
The Acot function returns the principal value of the arccotangent, or inverse cotangent,
of its argument. The returned angle is given in radians in the range 0 (zero) to π.
The Asin function returns the arcsine, or inverse sine, of its argument. The arcsine is the
angle whose sine is the argument. The returned angle is given in radians in the range
-π/2 to π/2.
The Atan function returns the arctangent, or inverse tangent, of its argument. The
arctangent is the angle whose tangent is the argument. The returned angle is given in
radians in the range -π/2 to π/2.
The Atan2 function returns the arctangent, or inverse tangent, of the specified x and y
coordinates as arguments. The arctangent is the angle from the x-axis to a line that
contains the origin (0, 0) and a point with coordinates (x, y). The angle is given in radians
between -π and π, excluding -π. A positive result represents a counterclockwise angle
from the x-axis; a negative result represents a clockwise angle. Atan2( a, b ) equals
Atan( b/a ), except that a can equal 0 (zero) with the Atan2 function.
Helper functions
The Degrees function converts radians to degrees. π radians equals 180 degrees.
Notes
If you pass a single number to these functions, the return value is a single result. If you
pass a single-column table that contains numbers, the return value is a single-column
table of results with a Value column, one result for each record in the argument's table.
If you have a multi-column table, you can shape it into a single-column table, as
working with tables describes.
If an argument would result in an undefined value, the result is blank. This can happen,
for example, when using inverse functions with arguments that are out of range.
Syntax
Primary Functions
Cos( Radians )
Cot( Radians )
Sin( Radians )
Tan( Radians )
Cos( SingleColumnTable )
Cot( SingleColumnTable )
Sin( SingleColumnTable )
Tan( SingleColumnTable )
Inverse Functions
Acos( Number )
Acot( Number )
Asin( Number )
Atan( Number )
Acos( SingleColumnTable )
Acot( SingleColumnTable )
Asin( SingleColumnTable )
Atan( SingleColumnTable )
Atan2( X, Y )
Helper Functions
Degrees( Radians )
Pi()
Radians( Degrees )
Examples
Single number
Atan2( 5, 3 ) Returns the arctangent of the angle from the x-axis of the line 0.540419...
that contains the origin (0,0) and the coordinate (5,3), which is
approximately 31 degrees.
Atan2( 4, 4 ) Returns the arctangent of the angle from the x-axis of the line 0.785398...
that contains the origin (0,0) and the coordinate (4,4), which is
exactly π/4 radians or 45 degrees.
Single-column table
The examples in this section use a data source that's named ValueTable and that
contains the following data. The last record in the table is π/2 radians or 90 degrees.
Value
0.5
-2
1.570796...
Sin( ValueTable ) Returns the sine of each number A single-column table with a Value
in the table. column containing the following
values: 0.479425, -0.909297..., 1
Description
Primary functions
The Cos function returns the cosine of its argument, an angle specified in radians.
The Cot function returns the cotangent of its argument, an angle specified in radians.
The Sin function returns the sine of its argument, an angle specified in radians.
The Tan function returns the tangent of its argument, an angle specified in radians.
Inverse functions
The Acos function returns the arccosine, or inverse cosine, of its argument. The
arccosine is the angle whose cosine is the argument. The returned angle is given in
radians in the range 0 (zero) to π.
The Acot function returns the principal value of the arccotangent, or inverse cotangent,
of its argument. The returned angle is given in radians in the range 0 (zero) to π.
The Asin function returns the arcsine, or inverse sine, of its argument. The arcsine is the
angle whose sine is the argument. The returned angle is given in radians in the range
-π/2 to π/2.
The Atan function returns the arctangent, or inverse tangent, of its argument. The
arctangent is the angle whose tangent is the argument. The returned angle is given in
radians in the range -π/2 to π/2.
The Atan2 function returns the arctangent, or inverse tangent, of the specified x and y
coordinates as arguments. The arctangent is the angle from the x-axis to a line that
contains the origin (0, 0) and a point with coordinates (x, y). The angle is given in radians
between -π and π, excluding -π. A positive result represents a counterclockwise angle
from the x-axis; a negative result represents a clockwise angle. Atan2( a, b ) equals
Atan( b/a ), except that a can equal 0 (zero) with the Atan2 function.
Helper functions
The Degrees function converts radians to degrees. π radians equals 180 degrees.
Notes
If you pass a single number to these functions, the return value is a single result. If you
pass a single-column table that contains numbers, the return value is a single-column
table of results with a Value column, one result for each record in the argument's table.
If you have a multi-column table, you can shape it into a single-column table, as
working with tables describes.
If an argument would result in an undefined value, the result is blank. This can happen,
for example, when using inverse functions with arguments that are out of range.
Syntax
Primary Functions
Cos( Radians )
Cot( Radians )
Sin( Radians )
Tan( Radians )
Cos( SingleColumnTable )
Cot( SingleColumnTable )
Sin( SingleColumnTable )
Tan( SingleColumnTable )
Inverse Functions
Acos( Number )
Acot( Number )
Asin( Number )
Atan( Number )
Acos( SingleColumnTable )
Acot( SingleColumnTable )
Asin( SingleColumnTable )
Atan( SingleColumnTable )
Atan2( X, Y )
Helper Functions
Degrees( Radians )
Pi()
Radians( Degrees )
Examples
Single number
Atan2( 5, 3 ) Returns the arctangent of the angle from the x-axis of the line 0.540419...
that contains the origin (0,0) and the coordinate (5,3), which is
approximately 31 degrees.
Atan2( 4, 4 ) Returns the arctangent of the angle from the x-axis of the line 0.785398...
that contains the origin (0,0) and the coordinate (4,4), which is
exactly π/4 radians or 45 degrees.
Single-column table
The examples in this section use a data source that's named ValueTable and that
contains the following data. The last record in the table is π/2 radians or 90 degrees.
Value
0.5
-2
1.570796...
Sin( ValueTable ) Returns the sine of each number A single-column table with a Value
in the table. column containing the following
values: 0.479425, -0.909297..., 1
Counts all records in a table, or counts all records that satisfy a condition.
Description
The Count function counts the number of records that contain a number in a single-
column table.
The CountA function counts the number of records that aren't blank in a single-column
table. This function includes empty text ("") in the count.
The CountIf function counts the number of records in a table that are true for a logical
formula. The formula can reference columns of the table.
You need to enable the Enhanced delegation for Microsoft Dataverse option in the
advance settings to make CountIf and CountRows functions delegation to work. To
enable the option:
) Important
There is a 50K delegation limit if you use CountRows and CountIf functions
with filters. There is no hard limit on the CountRows function when extracted
directly from the data source because of the cached count that Dataverse
keeps.
If the CountRows(<Data Source>) function is used without filtering, the count
might not be 100% accurate, because the cached count updates periodically.
If you need precise count and expect the result to be under the aggregate
limit, you can bypass the cached count via CountIf(<Data Source>, True) .
Syntax
Count( SingleColumnTable )
CountA( SingleColumnTable )
CountRows( Table )
Example
1. Import or create a collection named Inventory, as the first subprocedure in Show
images and text in a gallery describes.
The label shows 2 because two products (Ganymede and Callisto) have fewer than
30 units in stock.
3. Add another label, and set its Text property to this formula:
CountA(Inventory.UnitsInStock)
The label shows 5, the number of non-empty cells in the UnitsInStock column.
4. Add another label, and set its Text property to this formula:
CountRows(Inventory)
Counts all records in a table, or counts all records that satisfy a condition.
Description
The Count function counts the number of records that contain a number in a single-
column table.
The CountA function counts the number of records that aren't blank in a single-column
table. This function includes empty text ("") in the count.
The CountIf function counts the number of records in a table that are true for a logical
formula. The formula can reference columns of the table.
You need to enable the Enhanced delegation for Microsoft Dataverse option in the
advance settings to make CountIf and CountRows functions delegation to work. To
enable the option:
) Important
There is a 50K delegation limit if you use CountRows and CountIf functions
with filters. There is no hard limit on the CountRows function when extracted
directly from the data source because of the cached count that Dataverse
keeps.
If the CountRows(<Data Source>) function is used without filtering, the count
might not be 100% accurate, because the cached count updates periodically.
If you need precise count and expect the result to be under the aggregate
limit, you can bypass the cached count via CountIf(<Data Source>, True) .
Syntax
Count( SingleColumnTable )
CountA( SingleColumnTable )
CountRows( Table )
Example
1. Import or create a collection named Inventory, as the first subprocedure in Show
images and text in a gallery describes.
The label shows 2 because two products (Ganymede and Callisto) have fewer than
30 units in stock.
3. Add another label, and set its Text property to this formula:
CountA(Inventory.UnitsInStock)
The label shows 5, the number of non-empty cells in the UnitsInStock column.
4. Add another label, and set its Text property to this formula:
CountRows(Inventory)
Counts all records in a table, or counts all records that satisfy a condition.
Description
The Count function counts the number of records that contain a number in a single-
column table.
The CountA function counts the number of records that aren't blank in a single-column
table. This function includes empty text ("") in the count.
The CountIf function counts the number of records in a table that are true for a logical
formula. The formula can reference columns of the table.
You need to enable the Enhanced delegation for Microsoft Dataverse option in the
advance settings to make CountIf and CountRows functions delegation to work. To
enable the option:
) Important
There is a 50K delegation limit if you use CountRows and CountIf functions
with filters. There is no hard limit on the CountRows function when extracted
directly from the data source because of the cached count that Dataverse
keeps.
If the CountRows(<Data Source>) function is used without filtering, the count
might not be 100% accurate, because the cached count updates periodically.
If you need precise count and expect the result to be under the aggregate
limit, you can bypass the cached count via CountIf(<Data Source>, True) .
Syntax
Count( SingleColumnTable )
CountA( SingleColumnTable )
CountRows( Table )
Example
1. Import or create a collection named Inventory, as the first subprocedure in Show
images and text in a gallery describes.
The label shows 2 because two products (Ganymede and Callisto) have fewer than
30 units in stock.
3. Add another label, and set its Text property to this formula:
CountA(Inventory.UnitsInStock)
The label shows 5, the number of non-empty cells in the UnitsInStock column.
4. Add another label, and set its Text property to this formula:
CountRows(Inventory)
Overview
Data sources can provide a wealth of information to optimize the user experience.
You can use column-level information to validate user input and provide immediate
feedback to the user before using the Patch function. The Validate function uses this
same information.
You can use information at the data-source level, for example, to disable or hide Edit
and New buttons for users who don't have permissions to edit and create records.
Data sources vary in how much information they provide, including not providing any at
all. Collections provide no information. If a piece of information isn't provided, a default
is used, or blank is returned.
7 Note
Description
Column information
You can use DataSourceInfo to obtain information about a particular column of a data
source:
DataSourceInfo.Required Boolean Is a value required for this column? If not set by the
data source, returns false.
The third argument is the name of a column as a string. For example, column Phone in
collection People would be passed as "Phone" including the double quotes.
Data-source information
You can also use DataSourceInfo to obtain information about a data source as a whole:
7 Note
DataSourceInfo returns true if it cannot determine whether the current user has the
requested permission. Permissions will be checked again by the server when the
actual operation is carried out and an error is displayed if it was not allowed. At this
time, permissions checking with DataSourceInfo is only possible when using
Microsoft Dataverse.
Syntax
DataSourceInfo( DataSource, Information, ColumnName )
7 Note
For SharePoint and Excel data sources that contain column names with
spaces, specify each space as "_x0020_". For example, specify "Column
Name" as "Column_x0020_Name".
Examples
The examples in this section use this data source, named IceCream:
Description
The Date function converts individual Year, Month, and Day values to a Date/Time value.
The time portion is midnight.
If Year is between 0 and 1899 (inclusive), the function adds that value to 1900 to
calculate the year. 70 becomes 1970.
If Month is less than 1 or more than 12, the result subtracts or adds that many
months from the beginning of the specified year.
If Day is greater than the number of days in the specified month, the function adds
that many days to the first day of the month and returns the corresponding date
from a subsequent month. If Day is less than 1, the function subtracts that many
days, plus 1, from the first day of the specified month.
The Time function converts individual Hour, Minute, and Second values to a Date/Time
value. The result has no date associated with it.
See the DateValue, TimeValue, and DateTimeValue functions for information about how
to convert a string to a value.
Also see working with dates and times for more information.
Syntax
Date( Year, Month, Day )
Year - Required. Numbers greater than 1899 are interpreted as absolute (1980 is
interpreted as 1980); numbers that range from 0 to 1899 are interpreted as relative
to 1900. (For example, 80 is interpreted as 1980.)
Month - Required. A number that ranges from 1 to 12.
Day - Required. A number that ranges from 1 to 31.
Hour - Required. A number that ranges from 0 (12:00 AM) to 23 (11:00 PM).
Minute - Required. A number that ranges from 0 to 59.
Second - Required. A number that ranges from 0 to 59.
Examples
Date
If a user typed 1979 in a text-input control named HireYear, 3 in a text-input control
named HireMonth, and 17 in a text-input control named HireDay, this function would
return 3/17/1979:
Time
If a user typed 14 in a text-input control named BirthHour, 50 in a text-input control
named BirthMinute, and 24 in a text-input control named BirthSecond, this function
would return 02:50:24 p.
Adds to or finds the difference in date/time values and converts between local time and
UTC.
Description
The DateAdd function adds a number of units to a date/time value. The result is a new
date/time value. You can also subtract a number of units from a date/time value by
specifying a negative value.
The DateDiff function returns the difference between two date/time values. The result is
a whole number of units.
The TimeZoneOffset function returns the number of minutes between the user's local
time and UTC (Coordinated Universal Time).
You can use DateAdd with the TimeZoneOffset to convert between the user's local time
and UTC (Coordinated Universal Time). Adding TimeZoneOffset will convert a local time
to UTC, and subtracting it (adding the negative) will convert from UTC to local time.
Also see Date, Time, and DateTime data types and working with dates and times for
more information.
Syntax
DateAdd( DateTime, Addition [, Units ] )
TimeZoneOffset( [ DateTime ] )
DateTime - Optional. Date/time value for which to return the offset. By default, the
current date/time is used.
Examples
In all of these examples, assume that the current date and time is July 15, 2013, 1:02 PM.
Simple DateAdd
Text( DateAdd( Now(), 4, Add four hours to the current date and time. "15-07-
TimeUnit.Hours ),
2013
"dd-mm-yyyy hh:mm" ) 17:02"
Text( DateAdd( Today(), 1, Adds one month to the current date, without time as "15-08-
TimeUnit.Months ),
Today doesn't return a time component. 2013
"dd-mm-yyyy hh:mm" ) 00:00"
Text( DateAdd( Now(), ‑30, Subtracts 30 minutes from the current date and time. "15-07-
TimeUnit.Minutes ),
2013
"dd-mm-yyyy hh:mm" ) 12:32"
Simple DateDiff
DateDiff( Now(), Returns the difference between the two units in the default 170
DateValue("1/1/2014") ) units of TimeUnit.Days
DateDiff( Now(), Returns the difference between the current date/time and the -782
Today(), current date only (no time) in minutes. Since the Now is later
TimeUnit.Minutes ) than Today the result will be negative.
DateDiff( TimeValue("09:45:00"), The minutes are used in the difference, and the 0.5
TimeValue("10:15:36"), result is divided by 60 to have the difference in
TimeUnit.Minutes )/60 hours.
DateDiff( TimeValue("09:45:00"), The minutes and seconds are used in the 0.51
TimeValue("10:15:36"), difference; the result is divided by 3600 to have
TimeUnit.Seconds )/3600 the difference in hours.
Converting to UTC
To convert to UTC (Coordinated Universal Time), add the TimeZoneOffset for the given
time.
For example, imagine the current date and time is July 15, 2013, 1:02 PM in Pacific
Daylight Time (PDT, UTC-7). To determine the current time in UTC, use:
TimeZoneOffset defaults to the current time, so you don't need to pass it an argument.
To see the result, use the Text function with the format dd-mm-yyyy hh:mm, which will
return 15-07-2013 20:02.
For example, imagine the UTC date and time July 15, 2013, 8:02 PM is stored in a
variable named StartTime. To adjust the time for the user's time zone, use:
Note the negative sign before TimeZoneOffset to subtract the offset rather than add it.
To see the result, use the Text function with the format dd-mm-yyyy hh:mm, which will
result in 15-07-2013 13:02 if you're in Pacific Daylight Time.
DateAdd, DateDiff, and TimeZoneOffset
functions in Power Apps
Article • 03/08/2023 • 3 minutes to read
Adds to or finds the difference in date/time values and converts between local time and
UTC.
Description
The DateAdd function adds a number of units to a date/time value. The result is a new
date/time value. You can also subtract a number of units from a date/time value by
specifying a negative value.
The DateDiff function returns the difference between two date/time values. The result is
a whole number of units.
The TimeZoneOffset function returns the number of minutes between the user's local
time and UTC (Coordinated Universal Time).
You can use DateAdd with the TimeZoneOffset to convert between the user's local time
and UTC (Coordinated Universal Time). Adding TimeZoneOffset will convert a local time
to UTC, and subtracting it (adding the negative) will convert from UTC to local time.
Also see Date, Time, and DateTime data types and working with dates and times for
more information.
Syntax
DateAdd( DateTime, Addition [, Units ] )
TimeZoneOffset( [ DateTime ] )
DateTime - Optional. Date/time value for which to return the offset. By default, the
current date/time is used.
Examples
In all of these examples, assume that the current date and time is July 15, 2013, 1:02 PM.
Simple DateAdd
Text( DateAdd( Now(), 4, Add four hours to the current date and time. "15-07-
TimeUnit.Hours ),
2013
"dd-mm-yyyy hh:mm" ) 17:02"
Text( DateAdd( Today(), 1, Adds one month to the current date, without time as "15-08-
TimeUnit.Months ),
Today doesn't return a time component. 2013
"dd-mm-yyyy hh:mm" ) 00:00"
Text( DateAdd( Now(), ‑30, Subtracts 30 minutes from the current date and time. "15-07-
TimeUnit.Minutes ),
2013
"dd-mm-yyyy hh:mm" ) 12:32"
Simple DateDiff
DateDiff( Now(), Returns the difference between the two units in the default 170
DateValue("1/1/2014") ) units of TimeUnit.Days
DateDiff( Now(), Returns the difference between the current date/time and the -782
Today(), current date only (no time) in minutes. Since the Now is later
TimeUnit.Minutes ) than Today the result will be negative.
DateDiff( TimeValue("09:45:00"), The minutes are used in the difference, and the 0.5
TimeValue("10:15:36"), result is divided by 60 to have the difference in
TimeUnit.Minutes )/60 hours.
DateDiff( TimeValue("09:45:00"), The minutes and seconds are used in the 0.51
TimeValue("10:15:36"), difference; the result is divided by 3600 to have
TimeUnit.Seconds )/3600 the difference in hours.
Converting to UTC
To convert to UTC (Coordinated Universal Time), add the TimeZoneOffset for the given
time.
For example, imagine the current date and time is July 15, 2013, 1:02 PM in Pacific
Daylight Time (PDT, UTC-7). To determine the current time in UTC, use:
TimeZoneOffset defaults to the current time, so you don't need to pass it an argument.
To see the result, use the Text function with the format dd-mm-yyyy hh:mm, which will
return 15-07-2013 20:02.
For example, imagine the UTC date and time July 15, 2013, 8:02 PM is stored in a
variable named StartTime. To adjust the time for the user's time zone, use:
Note the negative sign before TimeZoneOffset to subtract the offset rather than add it.
To see the result, use the Text function with the format dd-mm-yyyy hh:mm, which will
result in 15-07-2013 13:02 if you're in Pacific Daylight Time.
DateValue, TimeValue, and
DateTimeValue functions in Power Apps
Article • 02/23/2023 • 4 minutes to read
Description
DateValue function converts a date string (for example, "10/01/2014") to a
date/time value.
TimeValue function converts a time string (for example, "12:15 PM") to a date/time
value.
DateTimeValue function converts a date and time string (for example, "January 10,
2013 12:13 AM") to a date/time value.
DateValue function ignores any time information in the date string, and the TimeValue
function ignores any date information in the time string.
7 Note
MM/DD/YYYY or MM-DD-YYYY
DD/MM/YYYY or DD-MM-YYYY
YYYY/MM/DD or YYYY-MM-DD
MM/DD/YY or MM-DD-YY
DD/MM/YY or DD-MM-YY
DD Mon YYYY
Month DD, YYYY
To convert from numeric date, month and year components, read Date.
To convert from numeric hour, minute and second components, read Time.
For more information, read:
Syntax
DateValue( String [, Language ])
String - Required. A text string that contains a date, time, or combination date and
time value.
Language - Optional. A language string, such as would be returned by the first two
characters from the Language function. If not provided, the language of the
current user's settings is used.
DateValue( Untyped )
DateTimeValue( Untyped )
TimeValue( Untyped )
Examples
DateValue
If you type 10/11/2014 into a text-input control named Startdate, and then set the Text
property of a label to these formulas:
Convert a date from a string in the user's locale and show the result as a long date.
Power Apps
Device set to en locale shows the label as Saturday, October 11, 2014.
7 Note
You can use several options with the DateTimeFormat enum. To display a list
of options, type the parameter followed by a dot or period (.) in the formula
bar or check Text function reference.
Convert date from a string in the French locale and show the result as a long date.
In this example, the months and day of the month are interpreted differently from
English.
Power Apps
Device set to en locale shows the label as Monday, November 10, 2014.
Convert a date from a string in the user's locale and calculate the difference
between two days, in days
Power Apps
Device set to en locale shows the label as 9, indicating the number of days
between October 11 and October 20. The DateDiff function can also show the
difference in months, quarters, or years.
DateTimeValue
If you typed 10/11/2014 1:50:24.765 PM into a text-input control named Start, and then
set the Text property of a label to the following formula:
Power Apps
Device set to en locale shows the label as Saturday, October 11, 2014 1:50:24 PM.
7 Note
You can use several options with the DateTimeFormat enum. To display a list
of options, type the parameter followed by a dot or period (.) in the formula
bar or check Text function reference.
Convert both a date and time string in the French locale. Month and day of the
month are interpreted differently.
Power Apps
Device set to en locale shows the label as Monday, November 10, 2014 1:50:24
PM.
Convert both a date and time string in the user's locale, and display the result with
a fractional second.
Power Apps
Device set to en locale shows the label as Saturday, October 11, 2014 01:50:24.765
PM.
TimeValue
Name a text-input control FinishedAt, and set the Text property of a label to this
formula:
Power Apps
"Too late!"
If you type 4:59:59.999 PM in the FinishedAt control, the label shows "You made
it!"
If you type 5:00:00.000 PM in the FinishedAt control, the label shows "Too late!"
DateValue, TimeValue, and
DateTimeValue functions in Power Apps
Article • 02/23/2023 • 4 minutes to read
Description
DateValue function converts a date string (for example, "10/01/2014") to a
date/time value.
TimeValue function converts a time string (for example, "12:15 PM") to a date/time
value.
DateTimeValue function converts a date and time string (for example, "January 10,
2013 12:13 AM") to a date/time value.
DateValue function ignores any time information in the date string, and the TimeValue
function ignores any date information in the time string.
7 Note
MM/DD/YYYY or MM-DD-YYYY
DD/MM/YYYY or DD-MM-YYYY
YYYY/MM/DD or YYYY-MM-DD
MM/DD/YY or MM-DD-YY
DD/MM/YY or DD-MM-YY
DD Mon YYYY
Month DD, YYYY
To convert from numeric date, month and year components, read Date.
To convert from numeric hour, minute and second components, read Time.
For more information, read:
Syntax
DateValue( String [, Language ])
String - Required. A text string that contains a date, time, or combination date and
time value.
Language - Optional. A language string, such as would be returned by the first two
characters from the Language function. If not provided, the language of the
current user's settings is used.
DateValue( Untyped )
DateTimeValue( Untyped )
TimeValue( Untyped )
Examples
DateValue
If you type 10/11/2014 into a text-input control named Startdate, and then set the Text
property of a label to these formulas:
Convert a date from a string in the user's locale and show the result as a long date.
Power Apps
Device set to en locale shows the label as Saturday, October 11, 2014.
7 Note
You can use several options with the DateTimeFormat enum. To display a list
of options, type the parameter followed by a dot or period (.) in the formula
bar or check Text function reference.
Convert date from a string in the French locale and show the result as a long date.
In this example, the months and day of the month are interpreted differently from
English.
Power Apps
Device set to en locale shows the label as Monday, November 10, 2014.
Convert a date from a string in the user's locale and calculate the difference
between two days, in days
Power Apps
Device set to en locale shows the label as 9, indicating the number of days
between October 11 and October 20. The DateDiff function can also show the
difference in months, quarters, or years.
DateTimeValue
If you typed 10/11/2014 1:50:24.765 PM into a text-input control named Start, and then
set the Text property of a label to the following formula:
Power Apps
Device set to en locale shows the label as Saturday, October 11, 2014 1:50:24 PM.
7 Note
You can use several options with the DateTimeFormat enum. To display a list
of options, type the parameter followed by a dot or period (.) in the formula
bar or check Text function reference.
Convert both a date and time string in the French locale. Month and day of the
month are interpreted differently.
Power Apps
Device set to en locale shows the label as Monday, November 10, 2014 1:50:24
PM.
Convert both a date and time string in the user's locale, and display the result with
a fractional second.
Power Apps
Device set to en locale shows the label as Saturday, October 11, 2014 01:50:24.765
PM.
TimeValue
Name a text-input control FinishedAt, and set the Text property of a label to this
formula:
Power Apps
"Too late!"
If you type 4:59:59.999 PM in the FinishedAt control, the label shows "You made
it!"
If you type 5:00:00.000 PM in the FinishedAt control, the label shows "Too late!"
Day, Month, Year, Hour, Minute, Second,
and Weekday functions in Power Apps
Article • 02/23/2023 • 2 minutes to read
Description
The Day function returns the day component of a Date/Time value, ranging from 1 to
31.
The Month function returns the month component of a Date/Time value, ranging from
1 to 12.
The Year function returns the year component of a Date/Time value, starting with 1900.
The Hour function returns the hour component of a Date/Time value, ranging from 0
(12:00 AM) to 23 (11:00 PM).
The Minute function returns the minute component of a Date/Time value, ranging from
0 to 59.
The Second function returns the second component of a Date/Time value, ranging from
0 to 59.
The Weekday function returns the weekday of a Date/Time value. By default, the result
ranges from 1 (Sunday) to 7 (Saturday). You can specify a different range with an
Microsoft Excel Weekday function code or a StartOfWeek enumeration value:
Syntax
Day( DateTime )
Month( DateTime )
Year( DateTime )
Hour( DateTime )
Minute( DateTime )
Second( DateTime )
Examples
For the following example, the current time is 3:59:37 PM on Thursday, April 9, 2015.
Description
Use the Defaults function to pre-populate a data entry form, making it easier to fill.
This function returns a record that contains the default values for the data source. If a
column within the data source doesn't have a default value, that property won't be
present.
Data sources vary in how much default information they provide, including not
providing any at all. When you work with a collection or another data source that
doesn't support default values, the Defaults function will return an empty record.
You can combine the Defaults function with the Patch function to create a record.
Syntax
Defaults( DataSource )
DataSource – Required. The data source for which you want default values.
Examples
Formula Description Result
Defaults( Scores ) Returns the default values for the Scores data source. { Score: 0 }
Acos, Acot, Asin, Atan, Atan2, Cos, Cot,
Degrees, Pi, Radians, Sin, and Tan
functions in Power Apps
Article • 03/17/2023 • 5 minutes to read
Description
Primary functions
The Cos function returns the cosine of its argument, an angle specified in radians.
The Cot function returns the cotangent of its argument, an angle specified in radians.
The Sin function returns the sine of its argument, an angle specified in radians.
The Tan function returns the tangent of its argument, an angle specified in radians.
Inverse functions
The Acos function returns the arccosine, or inverse cosine, of its argument. The
arccosine is the angle whose cosine is the argument. The returned angle is given in
radians in the range 0 (zero) to π.
The Acot function returns the principal value of the arccotangent, or inverse cotangent,
of its argument. The returned angle is given in radians in the range 0 (zero) to π.
The Asin function returns the arcsine, or inverse sine, of its argument. The arcsine is the
angle whose sine is the argument. The returned angle is given in radians in the range
-π/2 to π/2.
The Atan function returns the arctangent, or inverse tangent, of its argument. The
arctangent is the angle whose tangent is the argument. The returned angle is given in
radians in the range -π/2 to π/2.
The Atan2 function returns the arctangent, or inverse tangent, of the specified x and y
coordinates as arguments. The arctangent is the angle from the x-axis to a line that
contains the origin (0, 0) and a point with coordinates (x, y). The angle is given in radians
between -π and π, excluding -π. A positive result represents a counterclockwise angle
from the x-axis; a negative result represents a clockwise angle. Atan2( a, b ) equals
Atan( b/a ), except that a can equal 0 (zero) with the Atan2 function.
Helper functions
The Degrees function converts radians to degrees. π radians equals 180 degrees.
Notes
If you pass a single number to these functions, the return value is a single result. If you
pass a single-column table that contains numbers, the return value is a single-column
table of results with a Value column, one result for each record in the argument's table.
If you have a multi-column table, you can shape it into a single-column table, as
working with tables describes.
If an argument would result in an undefined value, the result is blank. This can happen,
for example, when using inverse functions with arguments that are out of range.
Syntax
Primary Functions
Cos( Radians )
Cot( Radians )
Sin( Radians )
Tan( Radians )
Cos( SingleColumnTable )
Cot( SingleColumnTable )
Sin( SingleColumnTable )
Tan( SingleColumnTable )
Inverse Functions
Acos( Number )
Acot( Number )
Asin( Number )
Atan( Number )
Acos( SingleColumnTable )
Acot( SingleColumnTable )
Asin( SingleColumnTable )
Atan( SingleColumnTable )
Atan2( X, Y )
Helper Functions
Degrees( Radians )
Pi()
Radians( Degrees )
Examples
Single number
Atan2( 5, 3 ) Returns the arctangent of the angle from the x-axis of the line 0.540419...
that contains the origin (0,0) and the coordinate (5,3), which is
approximately 31 degrees.
Atan2( 4, 4 ) Returns the arctangent of the angle from the x-axis of the line 0.785398...
that contains the origin (0,0) and the coordinate (4,4), which is
exactly π/4 radians or 45 degrees.
Single-column table
The examples in this section use a data source that's named ValueTable and that
contains the following data. The last record in the table is π/2 radians or 90 degrees.
Value
0.5
-2
1.570796...
Sin( ValueTable ) Returns the sine of each number A single-column table with a Value
in the table. column containing the following
values: 0.479425, -0.909297..., 1
Overview
Some signals can change often, requiring the app to recalculate as they do. Rapid
changes over a long period of time can drain a device's battery. You can use these
functions to manually turn a signal on or off.
Description
The Enable and Disable functions turn a signal on and off, respectively.
These functions have no return value. You can use them only in behavior formulas.
Syntax
Enable( Signal )
Disable( Signal )
Description
The Distinct function evaluates a formula across each record of a table and returns a
one-column table of the results with duplicate values removed. The name of the column
is Result.
Fields of the record currently being processed are available within the formula. Use the
ThisRecord operator or simply reference fields by name as you would any other value.
The As operator can also be used to name the record being processed which can help
make your formula easier to understand and make nested records accessible. For more
information, see the examples below and working with record scope.
When used with a data source, this function can't be delegated. Only the first portion of
the data source will be retrieved and then the function applied. The result may not
represent the complete story. A warning may appear at authoring time to remind you of
this limitation and to suggest switching to delegable alternatives where possible. For
more information, see the delegation overview.
Syntax
Distinct( Table, Formula )
Example
1. Insert a Button control, and set its OnSelect property to this formula.
Power Apps
ClearCollect( CityPopulations,
);
The formula is evaluatd and the CityPopulations collection is created which you
can show by selecting CityPopulations in the formula bar:
3. Insert a Data table control, and set its Items property to this formula:
Power Apps
You can view the result of this formula in the formula bar by selecting the entire
formula:
4. Use the Edit fields link in the data table's properties pane to add the Result
column:
5. Insert a Label control, and set its Text property to the formula:
Power Apps
This formula sorts the results from Distinct with the Sort function, takes the first
record from the resulting table with the First function, and extracts the Result field
to obtain just the country name.
Download function in Power Apps
Article • 02/23/2023 • 2 minutes to read
Description
The Download function downloads a file from the web to the local device.
In native players (Windows, Android, and iOS), the user is prompted for a location to
save the file.
When used on the web, Download is dependent on the browser's settings to determine
what happens with the file. For images, videos, PDFs, and other file types that the
browser natively supports, a new browser tab is opened to display the file. Many
browsers support saving the contents to the local file system.
Only on Windows, Download returns the location where the file was stored locally as a
text string.
Syntax
Download( Address )
7 Note
Power Apps cannot authenticate download requests to the address provided in the
Download() function.
For example, when using this function to download a file stored on a SharePoint
site that requires authentication, the request might work when using a web browser
since the browser session might authenticate against the SharePoint site using
cached credentials. However, in Power Apps mobile app, the request will not work
since authenticating the download request is not handled by the mobile device.
Examples
Simple Download
The following formula will download the user's guide for the Surface Book, a PDF file:
Power Apps
Download( "https://go.microsoft.com/fwlink/?linkid=827480" )
When run in a mobile device, the user will be prompted for a location to save the file.
When run in most web browsers, a new tab will be opened to display the PDF file as
most browsers natively support this file type.
Step by Step
The Product Showcase tablet layout template was used for the following example. To
create an app with this template, follow the steps from create an app article and select
the Product Showcase template. You can also use your own app.
1. Go to Power Apps .
6. From the properties pane on the right-side, select Color as white and set Border
thickness at 1.
7. Select the Text property from right-side and enter text as Download User Guide.
12. Select the Download User Guide button to download the guide.
7 Note
Your browser settings determine whether to download the file or open the file
directly in a new tab. For more details, go to Download function description.
See also
Canvas app formula reference
AddColumns, DropColumns,
RenameColumns, and ShowColumns
functions in Power Apps
Article • 02/23/2023 • 6 minutes to read
Overview
These functions shape a table by adjusting its columns:
Reduce a table that contains multiple columns down to a single column for use
with single-column functions, such as Lower or Abs.
Add a calculated column to a table (for example, a Total Price column that shows
the results of multiplying Quantity by Unit Price).
Rename a column to something more meaningful, for display to users or for use in
formulas.
A table is a value in Power Apps, just like a string or a number. You can specify a table as
an argument in a formula, and functions can return a table as a result.
7 Note
The functions that this topic describes don't modify the original table. Instead, they
take that table as an argument and return a new table with a transform applied. See
working with tables for more details.
You can't modify the columns of a data source by using these functions. You must
modify the data at its source. You can add columns to a collection with the Collect
function. See working with data sources for more details.
Description
The AddColumns function adds a column to a table, and a formula defines the values in
that column. Existing columns remain unmodified.
The DropColumns function excludes columns from a table. All other columns remain
unmodified. DropColumns excludes columns, and ShowColumns includes columns.
The ShowColumns function includes columns of a table and drops all other columns.
You can use ShowColumns to create a single-column table from a multi-column table.
ShowColumns includes columns, and DropColumns excludes columns.
For all these functions, the result is a new table with the transform applied. The original
table isn't modified. You can't modify an existing table with a formula. SharePoint,
Microsoft Dataverse, SQL Server, and other data sources provide tools for modifying the
columns of lists, tables, and tables, which are often referred to as the schema. The
functions in this topic only transform an input table, without modifying the original, into
an output table for further use.
The arguments to these functions support delegation. For example, a Filter function
used as an argument to pull in related records searches through all listings, even if the
'[dbo].[AllListings]' data source contains a million rows:
Power Apps
AddColumns( RealEstateAgents,
"Listings",
However, the output of these functions is subject to the non-delegation record limit. In
this example, only 500 records are returned even if the RealEstateAgents data source
has 501 or more records.
If you use AddColumns in this manner, Filter must make separate calls to the data
source for each of those first records in RealEstateAgents, which causes a lot of network
chatter. If [dbo](.[AllListings] is small enough and doesn't change often, you could call
the Collect function in OnStart to cache the data source in your app when it starts. As
an alternative, you could restructure your app so that you pull in the related records
only when the user asks for them.
Syntax
AddColumns( Table, ColumnName1, Formula1 [, ColumnName2, Formula2, ... ] )
None of these examples modify the IceCreamSales data source. Each function
transforms the value of the data source as a table and returns that value as the result.
DropColumns(
Performs the following table transforms in
RenameColumns(
order, starting from the inside of the formula:
AddColumns(
IceCreamSales, 1. Adds a Revenue column based on the
"Revenue",
per-record calculation of UnitPrice *
UnitPrice * QuantitySold ),
Quantity.
"UnitPrice", "Price" ),
2. Renames UnitPrice to Price.
"Quantity" ) 3. Excludes the Quantity column.
Step by step
Let's try some of the examples from earlier in this topic.
1. Create a collection by adding a Button control and setting its OnSelect property to
this formula:
Power Apps
ClearCollect( IceCreamSales,
Table(
2. Run the formula by selecting the button while holding down the Alt key.
3. Add a second Button control, set its OnSelect property to this formula, and then
run it:
Power Apps
ClearCollect( FirstExample,
4. On the File menu, select Collections, and then select IceCreamSales to show that
collection.
As this graphic shows, the second formula didn't modify this collection. The
AddColumns function used IceCreamSales as a read-only argument; the function
didn't modify the table to which that argument refers.
5. Select FirstExample.
As this graphic shows, the second formula returned a new table with the added
column. The ClearCollect function captured the new table in the FirstExample
collection, adding something to the original table as it flowed through the function
without modifying the source:
Map columns in a component
See Map columns.
EditForm, NewForm, SubmitForm,
ResetForm, and ViewForm functions in
Power Apps
Article • 02/23/2023 • 5 minutes to read
View, edit, or create an item, save the contents, and reset the controls in an Edit form
control.
Overview
These functions change the state of the Edit form control. The form control can be in
one of these modes:
Mode Description
FormMode.Edit The form is populated with an existing record and the user can modify the
values of the fields. Once complete, the user can save the changes to the
record.
FormMode.New The form is populated with default values and the user can modify the values
of the fields. Once complete, the user can add the record to the data source.
FormMode.View The form is populated with an existing record but the user cannot modify the
values of the fields.
Description
These functions are often invoked from the OnSelect formula of a Button or Image
control so that the user can save edits, abandon edits, or create a record. You can use
controls and these functions together to create a complete solution.
SubmitForm
Use the SubmitForm function in the OnSelect property of a Button control to save any
changes in a Form control to the data source.
Before submitting any changes, this function checks for validation issues with any field
that's marked as required or that has one or more constraints on its value. This behavior
matches that of the Validate function.
SubmitForm also checks the Valid property of the Form, which is an aggregation of all
the Valid properties of the Card controls that the Form control contains. If a problem
occurs, the data isn't submitted, and the Error and ErrorKind properties of the Form
control are set accordingly.
If successful, the Form's OnSuccess behavior runs, and the Error and ErrorKind
properties are cleared. If the form was in FormMode.New mode, it is returned to
FormMode.Edit mode.
If unsuccessful, the Form's OnFailure behavior runs, and the Error and ErrorKind
properties are set accordingly. The mode of the form is unchanged.
EditForm
The EditForm function changes the Form control's mode to FormMode.Edit. In this
mode, the contents of the Form control's Item property are used to populate the form.
If the SubmitForm function runs when the form is in this mode, a record is changed, not
created. FormMode.Edit is the default for the Form control.
NewForm
The NewForm function changes the Form control's mode to FormMode.New. In this
mode, the contents of the Form control's Item property are ignored, and the default
values of the Form's DataSource property populate the form. If the SubmitForm
function runs when the form is in this mode, a record is created, not changed.
ResetForm
The ResetForm function resets the contents of a form to their initial values, before the
user made any changes. If the form is in FormMode.New mode, the form is reset to
FormMode.Edit mode. The OnReset behavior of the form control also runs. You can also
reset individual controls with the Reset function but only from within the form.
ViewForm
The ViewForm function changes the Form control's mode to FormMode.View. In this
mode, the contents of the Form control's Item property are used to populate the form.
The SubmitForm and ResetForm functions have no effect when in this mode.
DisplayMode Property
The current mode can be read through the Mode property. The mode also determines
the value of the DisplayMode property, which can be used by data cards and controls
within the form control. Often, the data card's DisplayMode property will be set to
Parent.DisplayMode (referencing the form) as will the control's DisplayMode property
(referencing the data card):
FormMode.Edit DisplayMode.Edit Data cards and controls are editable, ready to accept
changes to a record.
FormMode.New DisplayMode.Edit Data cards and controls are editable, ready to accept a
new record.
FormMode.View DisplayMode.View Data cards and controls are not editable and optimized
for viewing.
Syntax
SubmitForm( FormName )
EditForm( FormName )
NewForm( FormName )
ResetForm( FormName )
FormName - Required. Form control to reset to initial values. Also switches the
form from FormMode.New mode to FormMode.Edit mode.
ViewForm( FormName )
1. Add a Button control, set its Text property to show Save, and set its OnSelect
property to this formula:
SubmitForm( EditForm )
2. Set the OnFailure property of a Form control to blank and its OnSuccess property
to this formula:
Back()
3. Name a Label control ErrorText, and set its Text property to this formula:
EditForm.Error
When the user selects the Save button, any changes in the Form control are
submitted to the underlying data source.
If the submission succeeds, any changes are saved or, if the Form control is in
New mode, a record is created. ErrorText is blank and the previous screen
reappears.
If the submission fails, ErrorText shows a user-friendly error message, and the
current screen remains visible so that the user can correct the problem and
try again.
4. Add a Button control, set its Text property to show Cancel, and set its OnSelect
property to this formula:
When the user selects the Cancel button, the values in the Form control are reset
to what they were before the user started to edit it, the previous screen reappears,
and the Form control is returned to Edit mode if it was in New mode.
5. Add a Button control, set its Text property to show New, and set its OnSelect
property to this formula:
When the user selects the New button, the Form control switches to New mode,
the default values for the Form control's data source populate that control, and the
screen that contains the Form control appears. When the SubmitForm function
runs, a record is created instead of updated.
Enable and Disable functions in Power
Apps
Article • 02/23/2023 • 2 minutes to read
Overview
Some signals can change often, requiring the app to recalculate as they do. Rapid
changes over a long period of time can drain a device's battery. You can use these
functions to manually turn a signal on or off.
Description
The Enable and Disable functions turn a signal on and off, respectively.
These functions have no return value. You can use them only in behavior formulas.
Syntax
Enable( Signal )
Disable( Signal )
Description
The EncodeUrl function encodes a URL string, replacing certain non-alphanumeric
characters with % and a hexadecimal number.
The PlainText function removes HTML and XML tags, converting certain tags such as
these to an appropriate symbol:
"
The return value from these functions is the encoded or decoded string. This function
doesn't remove all HTML and XML tags.
Syntax
EncodeUrl( String )
PlainText( String )
String - Required. String from which HTML and XML tags will be stripped.
Examples
If you show an RSS feed in a text gallery and then set the Text property of a label in that
gallery to ThisItem.description, the label might show raw HTML or XML code as in this
example:
HTML
<p>
localization.
</p>
If you set the Text property of the label to PlainText(ThisItem.description), the text
appears as in this example:
Description
The EndsWith function tests whether one text string ends with another.
The StartsWith function tests whether one text string begins with another.
For both functions, the tests are case insensitive. The return value of both is a Boolean
true or false.
Use EndsWith and StartsWith with the Filter function to search the data within your
app. You can also use the in operator or the Search function to look anywhere within
text strings, not just at the beginning or end. Your choice of functions will depend on
the needs of your app and which function can be delegated for your particular data
source. If one of these functions can't be delegated, a delegation warning will appear at
authoring time to warn you of this limitation.
Syntax
EndsWith( Text, EndText )
Examples
Formula Description Result
Formula Description Result
EndsWith( Tests whether "Hello World" ends with "world". The test is case true
"Hello World", insensitive.
"world" )
EndsWith( Tests whether "Good bye" ends with "good". The EndText argument false
"Good bye", ("good") appears in the text but not at the end.
"good" )
EndsWith( Tests whether "Always say hello" ends with "hello". true
"Always say
hello", "hello" )
EndsWith( "Bye Tests whether "Bye bye" ends with an empty text string (Len returns true
bye", "" ) 0). Easing its use in Filter expressions, EndsWith is defined to return
true in this case.
StartsWith( Tests whether "Hello World" begins with "hello". The test is case true
"Hello World", insensitive.
"hello" )
StartsWith( Tests whether "Always say hello" begins with "hello". Although false
"Always say "hello" appears in the text, it doesn't appear at the beginning.
hello", "hello" )
StartsWith( "Bye Tests whether "Bye bye" starts with an empty text string (Len returns true
bye", "" ) 0). Easing its use in Filter expressions, StartsWith is defined to return
true in this case.
The examples in the rest of this topic show the results of searching a Customers list that
contains this data:
To create this data source as a collection, create a Button control and set its OnSelect
property to this formula:
As in this example, you can show a list of records in a Gallery control at the bottom of a
screen. Near the top of the screen, you can add a Text input control, named
SearchInput, so that users can specify which records interest them.
As the user types characters in SearchInput, the results in the gallery are automatically
filtered. In this case, the gallery is configured to show records for which the name of the
customer (not the name of the company) starts with the sequence of characters in
SearchInput.If the user types co in the search box, the gallery shows these results:
To filter based on the Name column, set the Items property of the gallery control to one
of these formulas:
Filter( Filters the Customers data source for records in which the search
Customers, string appears at the start of the Name column. The test is case
StartsWith( insensitive. If the user types co in the search box, the gallery shows
Name, Colleen Jones and Cole Miller. The gallery doesn't show Mike
SearchInput.Text Collins because the Name column for that record doesn't start with
)) the search string.
Filter( Filters the Customers data source for records in which the search
Customers, string appears anywhere in the Name column. The test is case
SearchInput.Text insensitive. If the user types co in the search box, the gallery shows
in Name ) Colleen Jones, Cole Miller, and Mike Collins because the search
string appears somewhere in the Name column of all of those
records.
Search( Similar to using the in operator, the Search function searches for a
Customers, match anywhere within the Name column of each record. Note that
SearchInput.Text, you must enclose the column name in double quotation marks.
"Name" )
You can expand your search to include the Company column as well as the Name
column:
Filter( Filters the Customers data source for records in which either the
Customers, Name column or the Company column starts with the search string
StartsWith( (for example, co). The || operator is true if either StartsWith function
Name, is true.
SearchInput.Text
) || StartsWith(
Company,
SearchInput.Text
))
Filter( Filters the Customers data source for records in which either the
Customers, Name column or the Company column contains the search string
SearchInput.Text (for example, co) anywhere within it.
in Name ||
SearchInput.Text
in Company )
Search( Similar to using the in operator, the Search function searches the
Customers, Customers data source for records in which either the Name column
SearchInput.Text, or the Company column contains the search string (for example, co)
"Name", anywhere within it. The Search function is easier to read and write
"Company" ) than Filter if you want to specify multiple columns and multiple in
operators. Note that you must enclose the names of the columns in
double quotation marks.
Error, IfError, IsError, IsBlankOrError
functions in Power Apps
Article • 02/23/2023 • 9 minutes to read
Detects errors and provides an alternative value or takes action. Create a custom error
or pass through an error.
7 Note
The behavior that this article describes is available only when the Formula-
level error management preview feature in Settings > Upcoming features >
Preview is turned on.
IfError
The IfError function tests values until it finds an error. If the function discovers an error,
the function evaluates and returns a corresponding replacement value and stops further
evaluation. A default value can also be supplied for when no errors are found. The
structure of IfError resembles that of the If function: IfError tests for errors, while If tests
for true.
Use IfError to replace an error with a valid value so that downstream calculations can
continue. For example, use this function if user input might result in a division by zero:
Power Apps
IfError( 1/x, 0 )
This formula returns 0 if the value of x is zero, as 1/x will produce an error. If x isn't
zero, then 1/x is returned.
Power Apps
The second Patch function to DS2 will be attempted even if the Patch to DS1 fails. The
scope of an error is limited to each formula that is chained.
Use IfError to do an action and only continue processing if the action was successful.
Applying IfError to this example:
Power Apps
IfError(
If the Patch of DS1 has a problem, the first Notify is executed. No further processing
occurs including the second Patch of DS2 . If the first Patch succeeds, the second Patch
will execute.
Building on the last example, the return value from IfError can be checked to determine
if there were any problems:
Power Apps
IfError(
true
Type compatibility
IfError will return the value of one of its arguments. The types of all values that might be
returned by IfError must be compatible.
In the last example, Patch will return a record that isn't compatible with the Booleans
used for the Replacement formulas or the DefaultResult. Which is fine, since there's no
situation in which the return value from these Patch calls would be returned by IfError.
7 Note
While the behavior in process for a change, the types of all arguments to IfError
must be compatible currently.
Power Apps
IfError( 1/x, 0 )
The types of 1/x and 0 were compatible as both were numbers. If they're not, the
second argument will be coerced to match the type of the first argument.
Power Apps
The above formula won't work. The text string "#DIV/0!" will be coerced to the type of
the first argument to IfError, which is a number. The result of IfError will be yet another
error since the text string can't be coerced. As a fix, convert the first argument to a text
string so that IfError always returns a text string:
Power Apps
As seen above, IfError can return an error if the Replacement or DefaultResult is an error.
FirstError / AllErrors
Within in the replacement formulas, information about the errors found is available
through the FirstError record and AllErrors table. AllErrors is a table of error information
records with FirstError being a shortcut to the first record of this table. FirstError will
always return the same value as First( AllErrors ).
Message Text Message about the error, suitable to be displayed to the end user.
string
Source Text Location in where the error originated, used for reporting. For example,
string for a formula bound to a control property, this will be in the form
ControlName.PropertyName.
Observed Text Location in where the error is surfaced to the user, used for reporting. For
string example, for a formula bound to a control property, this will be in the
form ControlName.PropertyName.
Details Record Details about the error. At present, details are provided only for network
errors. This record includes HttpStatusCode whcih contains the HTTP
status code and HttpResponse which contains the body of the response
from the connector or service.
For example, consider the following formula as a Button control's OnSelect property:
Power Apps
Set( a, 1/0 )
Power Apps
The example formula above would display the following banner when the two buttons
are activated in sequence:
Typically, there'll be only one error that FirstError can sufficiently work with. However,
there are scenarios where multiple errors may be returned. For example, when using a
formula chaining operator or the Concurrent function. Even in these situations,
reporting FirstError might be enough to reveal a problem instead overloading a user
with multiple errors. If you still have a requirement to work with each error individually,
you can use the AllErrors table.
IsError
The IsError function tests for an error value.
IsBlankOrError
The IsBlankOrError function tests for either a blank value or an error value and is the
equivalent of Or( IsBlank( X ), IsError( X ) ) .
When enabling error handling for existing apps, consider replacing IsBlank with
IsBlankOrError to preserve existing app behavior. Prior to the addition of error handling,
a blank value was used to represent both null values from databases and error values.
Error handling separates these two interpretations of blank which could change the
behavior of existing apps that continue to use IsBlank.
Error
Use the Error function to create and report a custom error. For example, you might have
logic to determine whether any given value is valid for your context or not—something
not checked for a problem automatically. You can create and return your own error,
complete with Kind and Message, using the same record described above for the IfError
function.
In the context of IfError, use the Error function to rethrow or pass through an error. For
example, your logic in IfError may decide that in some cases an error can be safely
ignored, but in other cases the error is important to send through. Within IfError or
App.OnError, use Error( FirstError ) to pass through an error.
The Error function can also be passed a table of errors, as would be found in the
AllErrors table. Use Error( AllErrors ) to rethrow all the errors and not just the first.
A blank record or empty table passed to Error results in no error.
Syntax
Error( ErrorRecord )
Error( ErrorTable )
IsError( Value )
IsBlankOrError( Value )
Examples
Simple IfError
IfError( 1, The first argument isn't an error. The function has no other errors to check 1
2) and no default return value. The function returns the last value argument
evaluated.
IfError( The first argument returns an error value (because of division by zero). The 2
1/0, 2 ) function evaluates the second argument and returns it as the result.
IfError( The first argument isn't an error. The function has no other errors to check 30
10, 20, 30 but does have a default return value. The function returns the DefaultResult
) argument.
Formula Description Result
IfError( The first argument 10 isn't an error, so the function doesn't evaluate that 300
10, 11, 20, argument's corresponding replacement 11. The third argument 20 isn't an
21, 300 ) error either, so the function doesn't evaluate that argument's corresponding
replacement 21. The fifth argument 300 has no corresponding replacement
and is the default result. The function returns that result because the
formula contains no errors.
IfError( The first argument returns an error value (due to division by zero). The 1
1/0, function evaluates the second argument and displays a message to the user.
Notify( The return value of IfError is the return value of Notify, coerced to the same
"There type as the first argument to IfError (a number).
was an
internal
problem"
))
Simple IsError
If( IsError( The argument to IsError returns an error value (because of division by true
1/0 ), Notify( zero). This function returns true, which causes the If to display a
"There was message to the user with the Notify function. The return value of If is
an internal the return value of Notify, coerced to the same type as the first
problem" ) ) argument to If (a boolean).
Simple IsBlankOrError
Simple Error
In this example, dates are validated relative to one another, resulting in an error if there
is a problem.
Power Apps
In this example, some errors are allowed to pass through while others are supressed and
replaced with a value. In the first case, b will be in an error state because the Value
function has an invalid argument. Because this is unexpcted by the formula writer, it is
passed through so the user will see it. In the second case, with the same formula, b will
have the value 0, resulting in a division by zero. In this case, the formula writer may
know that this is acceptable for this logic, suppress the error (no banner is shown), and
return -1 instead.
Power Apps
With( {a: 1, b: 0} )
// returns -1
The AllErrors table can be filtered like any other table. Used with the Error function,
expected errors can be removed and the remaining errors retained and reported. For
example, if we knew that division by zero was not going to be a problem in a particular
context, those errors could be filtered out, leaving all other errors intact with the
following formula:
Power Apps
Step by step
1. Add a Text input control, and name it TextInput1 if it doesn't have that name by
default.
2. Add a Label control, and name it Label1 if it doesn't have that name by default.
Power Apps
Label1 will show the value 1234 as this is a valid input to the Value function.
Label1 will show the value -1 as this isn't a valid input to the Value function.
Without wrapping the Value function with IfError, the label would show no value as
the error value is treated as a blank.
See also
Formula reference for Power Apps
Errors function in Power Apps
Article • 02/23/2023 • 4 minutes to read
Overview
Errors can happen when a record of a data source is changed. Many causes are possible,
including network outages, inadequate permissions, and edit conflicts.
The functions that modify data in data sources, such as Patch, Collect, Remove,
RemoveIf, Update, UpdateIf, and SubmitForm report errors in two ways:
Each of these functions will return an error value as the result of the operation.
Errors can be detected with IsError and replaced or suppressed with IfError and
App.OnError as usual. See Error Handling for more information.
After the operation, the Errors function will also return the errors for previous
operations. This can be useful for displaying the error message on a form screen
without needing to capture the error in a state variable.
You can avoid some errors before they happen by using the Validate and
DataSourceInfo functions. See working with data sources for more suggestions on how
to work with and avoid errors.
Description
The Errors function returns a table of errors that contains the following columns:
Record. The record in the data source that had the error. If the error occurred
during the creation of a record, this column will be blank.
Column. The column that caused the error, if the error can be attributed to a single
column. If not, this will be blank.
Message. A description of the error. This error string can be displayed for the end
user. Be aware that this message may be generated by the data source and could
be long and contain raw column names that may not have any meaning to the
user.
Error. An error code that can be used in formulas to help resolve the error:
ErrorKind Description
ErrorKind Description
ErrorKind.CreatePermission An attempt was made to create a record, and the current user
doesn't have permission to create records.
ErrorKind.DeletePermission An attempt was made to delete a record, and the current user
doesn't have permission to delete records.
ErrorKind.EditPermission An attempt was made to edit a record, and the current user
doesn't have permission to edit records.
ErrorKind.GeneratedValue An attempt was made to change a column that the data source
generates automatically.
ErrorKind.MissingRequired The value for a required column is missing from the record.
ErrorKind.NotFound An attempt was made to edit or delete a record, but the record
couldn't be found. Another user may have changed the record.
ErrorKind.Sync An error was reported by the data source. Check the Message
column for more information.
ErrorKind.Validation There was a general validation issue detected, that did not fit one
of the other kinds.
Errors can be returned for the entire data source, or for only a selected row by providing
the Record argument to the function.
Patch or another data function may return a blank value if, for example, a record
couldn't be created. You can pass blank to Errors, and it will return appropriate error
information in these cases. Subsequent use of data functions on the same data source
will clear this error information.
If there are no errors, the table that Errors returns will be empty and can be tested with
the IsEmpty function.
Syntax
Errors( DataSource [, Record ] )
DataSource – Required. The data source for which you want to return errors.
Record – Optional. A specific record for which you want to return errors. If you
don't specify this argument, the function returns errors for the entire data source.
Examples
Step by Step
For this example, we'll be working with the IceCream data source:
Through the app, a user loads the Chocolate record into a data-entry form and then
changes the value of Quantity to 90. The record to be worked with is placed in the
context variable EditRecord:
To make this change in the data source, the Patch function is used:
Unfortunately, just before the Patch function was invoked, somebody else modifies the
Quantity for Chocolate to 80. Power Apps will detect this and not allow the conflicting
change to occur. You can check for this situation with the formula:
which returns false, because the Errors function returned the following table:
{ Flavor: blank "Another user has modified the record that ErrorKind.Conflict
"Chocolate", you're trying to modify. Please reload the
Quantity: 100 } record and try again."
You can place a label on the form to show this error to the user.
To show the error, set the label's Text property to this formula:
You can also add a Reload button on the form, so that the user can efficiently resolve
the conflict.
To show the button only when a conflict has occurred, set the button's Visible
property to this formula:
Some of these operators are dependent on the language of the author. For more
information about language support in canvas apps, see Global apps.
"..." Text string "Hello, World" Text strings are enclosed in double
quotes
. Property Slider1.Value
Extracts a property from a table,
Selector Color.Red
control, signal, or enumeration. For
Acceleration.X backward compatibility, ! may also be
used.
.
Decimal 1.23 Separator between whole and fractional
[language separator parts of a number. The character
dependent] depends on the language.
* 2*3 Multiplication
& String "hello" & " " & Makes multiple strings appear
concatenation "world" continuous
operator
&& or And Logical Price < 100 && Logical conjunction, equivalent to the
operators Slider1.Value = 20
And function
or Price < 100 And
Slider1.Value = 20
! or Not !(Price < 100) or Not Logical negation, equivalent to the Not
(Price < 100) function
,
List separator If( X < 10, "Low", Separates:
[language "Good" )
arguments in function calls
dependent] { X: 12, Y: 32 }
fields in a record
[ 1, 2, 3 ] records in a table
;
Formula Collect(T, A); Separate invocations of functions in
[language chaining Navigate(S1, "") behavior properties. The chaining
dependent] operator depends on the language.
7 Note
The @ operator can also be used to validate the type of the record object against a
data source. For example, Collect(coll,Account@{'Account Number: 1111')
The gallery shows all products except Callisto because the name of that product is
the only one that doesn't contain the letter you specified.
The gallery shows only Europa because only its name contains the letter that you
specified in the case that you specified.
ThisItem Gallery control
The default name for the current record in a Gallery or form
Edit form control
control.
Display form control
ThisRecord ForAll, Filter, With, The default name for the current record in ForAll and other
Sum and other record scope functions.
record scope
functions
As name Gallery control
Defines a name for the current record, replacing default
ForAll, Filter, With, ThisItem or ThisRecord. Use As to make formulas easier to
Sum and other understand and resolve ambiguity when nesting.
record scope
functions
ThisItem operator
For example, in the following Gallery control, the Items property is set to the Employees
data source (such as the Employees table included with the Northwind Traders sample):
Power Apps
Employees
The first item in the gallery is a template that is replicated for each employee. In the
template, the formula for the picture uses ThisItem to refer to the current item:
Power Apps
ThisItem.Picture
Power Apps
ThisRecord operator
ThisRecord is used in functions that have a record scope. For example, we can use the
Filter function with our gallery's Items property to only show first names that being with
M:
Power Apps
ThisRecord is optional and implied by using the fields directly, for example, in this case,
we could have written:
Power Apps
Although optional, using ThisRecord can make formulas easier to understand and may
be required in ambiguous situations where a field name may also be a relationship
name. ThisRecord is optional while ThisItem is always required.
Use ThisRecord to reference the whole record with Patch, Collect, and other record
scope functions. For example, the following formula sets the status for all inactive
employees to active:
Power Apps
ForAll( InactiveEmployees,
As operator
Use the As operator to name a record in a gallery or record scope function, overriding
the default ThisItem or ThisRecord. Naming the record can make your formulas easier
to understand and may be required in nested situations to access records in other
scopes.
For example, you can modify the Items property of our gallery to use As to identify that
we are working with an Employee:
Power Apps
Employees As Employee
The formulas for the picture and name are adjusted to use this name for the current
record:
Power Apps
Employee.Picture
Power Apps
Employee.'First Name' & " " & Employee.'Last Name'
As can also be used with record scope functions to replace the default name
ThisRecord. We can apply this to our previous example to clarify the record we're
working with:
Power Apps
When nesting galleries and record scope functions, ThisItem and ThisRecord always
refers to the inner most scope, leaving records in outer scopes unavailable. Use As to
make all record scopes available by giving each a unique name.
For example, this formula produces a chessboard pattern as a text string by nesting two
ForAll functions:
Power Apps
Concat(
Concat(
),
Value
) & Char(10)
),
Value
A similar example is possible with nested Gallery controls instead of ForAll functions.
Let's start with the vertical gallery for the Rank. This gallery control will have an Items
formula of:
Power Apps
Sequence(8) as Rank
Within this gallery, we'll place a horizontal gallery for the File, that will be replicated for
each Rank, with an Items property of:
Power Apps
Sequence(8) as File
And finally, within this gallery, we'll add a Label control that will be replicated for each
File and each Rank. We'll size it to fill the entire space and use the Fill property to
provide the color with this formula:
Power Apps
Method Description
By Any control can be referenced by name from anywhere within the app.
control
name For example, Label1.Fill refers to the fill property of the control who's name is Label1.
Self It's often convenient to reference another property of the same control when writing a
operator formula. Instead of using an absolute reference by name, it's easier and more portable
to use a relative reference to oneself. The Self operator provides that easy access to
the current control.
For example, Self.Fill refers to the fill color of the current control.
Parent Some controls host other controls, such as the Screen and Gallery controls. The
operator hosting control of the controls within it's called the parent. Like the Self operator, the
Parent operator provides an easy relative reference to the container control.
For example, Parent.Fill refers to the fill property of the control that is the container for
the current control.
Self and Parent are operators and not properties on the controls themselves. Referring
to Parent.Parent, Self.Parent or Parent.Self is not supported.
Identifier names
The names of variables, data sources, columns, and other objects can contain any
Unicode .
Use single quotes around a name that contains a space or other special character.
Use two single quotes together to represent one single quote in the name. Names that
don't contain special characters don't require single quotes.
Here are some example column names you might encounter in a table, and how they're
represented in a formula:
SimpleName SimpleName
NameWith123Numbers NameWith123Numbers
Display name - A name that is user-friendly and intended to be seen by end users.
This name may not be unique, may change over time, may contain spaces and any
Unicode character, and may be localized into different languages. Corresponding
to the example above, the display name may be Custom Field with space in
between the words.
Since display names are easier to understand, Canvas apps will suggest them as choices
and not suggest logical names. Although logical names aren't suggested, they can still
be used if typed indirectly.
For example, imagine you've added a Custom Field to a table in Dataverse. A logical
name will be assigned for you by the system, which you can modify only when creating
the field. The result would look similar to:
When authoring a reference to a field of Accounts, the suggestion will be made to use
'Custom Field' since this is the display name. Single quotes must be used because this
name has a space in it:
After selecting the suggestion, 'Custom Field' is shown in the formula bar and the data is
retrieved:
Although it isn't suggested, we could also use the logical name for this field. This will
result in the same data being retrieved. Single quotes are not required since this name
doesn't contain spaces or special characters:
Behind the scenes, a mapping is maintained between the display names seen in
formulas and the underlying logical names. Since logical names must be used to interact
with the data source, this mapping is used to convert from the current display name to
the logical name automatically and that is what is seen in the network traffic. This
mapping is also used to convert back to logical names to switch into new display names,
for example, if a display name changes or a maker in a different language edits the app.
7 Note
Logical names are not translated when moving an app between environments. For
Dataverse system table and field names, this should not be a problem as logical
names are consistent across environments. But any custom fields, such as
cra3a_customfield in this example above, may have a different environment prefix
(cra3a in this case). Display names are preferred as they can be matched against
display names in the new environment.
Name disambiguation
Since display names aren't unique, the same display name may appear more than once
in the same table. When this happens, the logical name will be added to the end of the
display name in parenthesis for one of more of the conflicting names. Building on the
example above, if there was a second field with the same display name of Custom Field
with a logical name of cra3a_customfieldalt then the suggestions would show:
Name disambiguation strings are added in other situations where name conflicts occur,
such as the names of table, choices, and other Dataverse items.
Disambiguation operator
Some functions create record scopes for accessing the fields of table while processing
each record, such as Filter, AddColumns, and Sum. Field names added with the record
scope override the same names from elsewhere in the app. When this happens, you can
still access values from outside the record scope with the @ disambiguation operator:
To access values from nested record scopes, use the @ operator with the name of
the table being operated upon using this pattern:
Table[@FieldName]
To access global values, such as data sources, collections, and context variables,
use the pattern [@ObjectName] (without a table designation).
Exits the currently running app and optionally signs out the current user.
Description
The Exit function exits the currently running app. The user is returned to the list of apps.
The user can then select another app to open.
Exit stops any further formula evaluation. Any function calls chained with a semicolon
operator after the Exit aren't carried out.
Use the optional Signout argument to sign the current user out of Power Apps. Signout
is useful when devices are shared to ensure user security.
While authoring the app, calling Exit doesn't exit or sign out the user. However, it stops
the evaluation of the rest of the formula.
Syntax
Exit( [Signout] )
Signout – Optional. A Boolean value that if true will sign the current user out of
Power Apps. The default is false and the user remains signed in.
Examples
Formula Description
Exit() Exits the current app and leaves the user signed in. The user is returned to the list of
apps.
Exit( true ) Exits the current app and the user is signed out. The user will need to sign back in
with their credentials before running an app.
Abs, Exp, Ln, Power, Log, and Sqrt
functions in Power Apps
Article • 03/17/2023 • 2 minutes to read
Calculates absolute values, logarithms, square roots, and the results of raising e or any
number to specified powers.
Description
The Abs function returns the non-negative value of its argument. If a number is
negative, Abs returns the positive equivalent.
The Exp function returns e raised to the power of its argument. The transcendental
number e begins 2.7182818...
The Power function returns a number raised to a power. It's equivalent to using the ^
operator.
The Log function returns the logarithm of its first argument in the base specified by its
second argument (or 10 if not specified).
The Sqrt function returns the number that, when multiplied by itself, equals its
argument.
If you pass a single number, the return value is a single result based on the function
called. If you pass a single-column table that contains numbers, the return value is a
single-column table of results in a Value column, one result for each record in the
argument's table. If you have a multi-column table, you can shape it into a single-
column table, as working with tables describes.
If an argument would result in an undefined valued, the result is blank. Which can
happen with square roots and logarithms of negative numbers.
Syntax
Abs( Number )
Exp( Number )
Ln( Number )
Sqrt( Number )
Number - Required. Number to operate on.
Abs( SingleColumnTable )
Exp( SingleColumnTable )
Ln( SingleColumnTable )
Sqrt( SingleColumnTable )
Examples
Single number
Ln( 100 ) Returns the natural logarithm (base e) of the number 100. 4.605170...
Single-column table
The examples in this section use a data source that's named ValueTable and that
contains this data:
Value
-4
Sqrt( ValueTable ) Returns the square root A single-column table with a Value column
of each number in the containing the following values: 3, Blank(),
table 1.414213...
Step-by-step example
1. Add a Text input control, and name it Source.
2. Add a Label control, and set its Text property to this formula:
Watch this video to learn how to use Filter, Search and LookUp functions:
https://www.microsoft.com/en-us/videoplayer/embed/RWLj3m?postJsllMsg=true
Description
The Filter function finds records in a table that satisfy a formula. Use Filter to find a set
of records that match one or more criteria and to discard those that don't.
The LookUp function finds the first record in a table that satisfies a formula. Use LookUp
to find a single record that matches one or more criteria.
For both, the formula is evaluated for each record of the table. Records that result in
true are included in the result. Besides the normal formula operators, you can use the in
and exactin operators for substring matches.
Fields of the record currently being processed are available within the formula. Use the
ThisRecord operator or simply reference fields by name as you would any other value.
The As operator can also be used to name the record being processed which can help
make your formula easier to understand and make nested records accessible. For more
information, see the examples below and working with record scope.
The Search function finds records in a table that contain a string in one of their columns.
The string may occur anywhere within the column; for example, searching for "rob" or
"bert" would find a match in a column that contains "Robert". Searching is case-
insensitive. Unlike Filter and LookUp, the Search function uses a single string to match
instead of a formula.
Filter and Search return a table that contains the same columns as the original table and
the records that match the criteria. LookUp returns only the first record found, after
applying a formula to reduce the record to a single value. If no records are found, Filter
and Search return an empty table, and LookUp returns blank.
Tables are a value in Power Apps, just like a string or number. They can be passed to and
returned from functions. Filter, Search, and LookUp don't modify a table. Instead, they
take a table as an argument and return a table, a record, or a single value from it. See
working with tables for more details.
Delegation
When possible, Power Apps will delegate filter and sort operations to the data source
and page through the results on demand. For example, when you start an app that
shows a Gallery control filled with data, only the first set of records will be initially
brought to the device. As the user scrolls, additional data is brought down from the data
source. The result is a faster start time for the app and access to very large data sets.
However, delegation may not always be possible. Data sources vary on what functions
and operators they support with delegation. If complete delegation of a formula isn't
possible, the authoring environment will flag the portion that can't be delegated with a
warning. When possible, consider changing the formula to avoid functions and
operators that can't be delegated. The delegation list details which data sources and
operations can be delegated.
If delegation is not possible, Power Apps will pull down only a small set of records to
work on locally. Filter and sort functions will operate on a reduced set of records. What
is available in the Gallery may not be the complete story, which could be confusing to
users.
Syntax
Filter(Table*, Formula1 [, *Formula2*, ... ] )
7 Note
For SharePoint and Excel data sources that contain column names with spaces,
specify each space as "_x0020_". For example, specify "Column Name" as
"Column_x0020_Name".
Table - Required. Table to search. In the UI, the syntax is shown as source above the
function box.
Formula - Required.
The formula by which each record of the table is evaluated.
The function returns the first record that results in true. You can reference columns
within the table. In the UI, the syntax is shown as condition above the function box.
ReductionFormula - Optional. This formula is evaluated over the record that was
found, and then reduces the record to a single value. You can reference columns
within the table. If you don't use this parameter, the function returns the full record
from the table. In the UI, the syntax is shown as result above the function box.
Examples
The following examples use the IceCream data source:
Search(IceCream, Because the search term is empty, all records are returned.
"", "Flavor")
LookUp(IceCream, Searches for a record with Quantity greater than 150, of 250
Quantity > 150, which there are multiple. For the first record that's found,
Quantity + which is "Vanilla" Flavor, returns the sum of Quantity and
OnOrder) OnOrder columns.
LookUp(IceCream, Searches for a record with Flavor equal to "Vanilla", of which { Flavor:
Flavor = "Vanilla") there is one. Since no reduction formula was supplied, the "Vanilla",
entire record is returned. Quantity:
200,
OnOrder: 75
}
Step by step
4. On the Properties tab of the right-hand pane, open Data Source and then select
Accounts.
6. On the Insert tab, select Input and then select Combo box. Repeat the step to add
two more combo box controls.
7. For each combo box control, on the Properties tab of the right-hand pane, open
Data Source and then select Accounts. Select Edit next to Fields option and then
select the Primary text and SearchField values. The Primary text should be the
choices column you want to add to the combo box. Repeat the step for other two
combo box controls.
8. Now select Gallery control and set the Items property to the following formula:
Filter(Accounts,
'Industry' =
ComboBox3.Selected.Industry||IsBlank(ComboBox3.Selected.Industry),
IsBlank(ComboBox2.Selected.'Relationship Type'),
In many apps, you can type one or more characters into a search box to filter a list of
records in a large data set. As you type, the list shows only those records that match the
search criteria.
The examples in the rest of this topic show the results of searching a list, named
Customers, that contain this data:
To create this data source as a collection, create a Button control and set its OnSelect
property to this formula:
As in this example, you can show a list of records in a Gallery control at the bottom of a
screen. Near the top of the screen, you can add a Text input control, named
SearchInput, so that users can specify which records interest them.
As the user types characters in SearchInput, the results in the gallery are automatically
filtered. In this case, the gallery is configured to show records for which the name of the
customer (not the name of the company) starts with the sequence of characters in
SearchInput. If the user types co in the search box, the gallery shows these results:
To filter based on the Name column, set the Items property of the gallery control to one
of these formulas:
Filter(Customers, Filters the Customers data source for records in which the search
StartsWith(Name, string appears at the start of the Name column. The test is case
SearchInput.Text) insensitive. If the user types co in the search box, the gallery shows
) Colleen Jones and Cole Miller. The gallery doesn't show Mike
Collins because the Name column for that record doesn't start
with the search string.
Filter(Customers, Filters the Customers data source for records in which the search
SearchInput.Text string appears anywhere in the Name column. The test is case
in Name) insensitive. If the user types co in the search box, the gallery shows
Colleen Jones, Cole Miller, and Mike Collins because the search
string appears somewhere in the Name column of all of those
records.
Search(Customers, Similar to using the in operator, the Search function searches for a
SearchInput.Text, match anywhere within the Name column of each record. You
"Name") must enclose the column name in double quotation marks.
You can expand your search to include the Company column and the Name column:
Filter(Customers, Filters the Customers data source for records in which either the
StartsWith(Name, Name column or the Company column starts with the search
SearchInput.Text) || string (for example, co). The || operator is true if either
StartsWith(Company, StartsWith function is true.
SearchInput.Text) )
Filter(Customers, Filters the Customers data source for records in which either the
SearchInput.Text in Name column or the Company column contains the search
Name || SearchInput. string (for example, co) anywhere within it.
Text in Company)
Description
The Find function looks for a string within another string and is case sensitive. To ignore
case, first use the Lower function on the arguments.
Find returns the starting position of the string that was found. Position 1 is the first
character of the string. Find returns blank if the string in which you're searching doesn't
contain the string for which you're searching.
Syntax
Find( FindString, WithinString [, StartingPosition ] )
Returns the first, last, or a specific record, or a set of first or last records, from a table.
Description
The First function returns the first record of a table.
The FirstN function returns the first set of records of a table; the second argument
specifies the number of records to return.
The LastN function returns the last set of records of a table; the second argument
specifies the number of records to return.
The Index function returns a record of a table based on its ordered position in the table.
Record numbering begins with 1 so First( table ) returning the same record as
Index( table, 1 ) . Index returns an error if the requested record index is less than 1,
greater than the number of records in the table, or the table is empty.
First, Index, and Last return a single record. FirstN and LastN return a table, even if you
specify only a single record.
Delegation
When used with a data source, these functions can't be delegated. Only the first portion
of the data source will be retrieved and then the function applied. The result may not
represent the complete story. A warning may appear at authoring time to remind you of
this limitation and to suggest switching to delegable alternatives where possible. For
more information, see the delegation overview.
For example, when used with a data source containing a large table with 1 million
records, Last will be subject to the non-delegation limit and will not return the last
record of the entire data source. Likewise, using Index to request a record in the middle
of 1 million records will result in an error because the index is out of range based on the
non-delegation limit.
Syntax
First( Table )
Last( Table )
Examples
For the following examples, we'll use the IceCream data source, which contains the data
in this table:
This table can be placed in a collection with this formula (put in the OnStart formula for
a Button control and press the button):
Power Apps
Returns the first, last, or a specific record, or a set of first or last records, from a table.
Description
The First function returns the first record of a table.
The FirstN function returns the first set of records of a table; the second argument
specifies the number of records to return.
The LastN function returns the last set of records of a table; the second argument
specifies the number of records to return.
The Index function returns a record of a table based on its ordered position in the table.
Record numbering begins with 1 so First( table ) returning the same record as
Index( table, 1 ) . Index returns an error if the requested record index is less than 1,
greater than the number of records in the table, or the table is empty.
First, Index, and Last return a single record. FirstN and LastN return a table, even if you
specify only a single record.
Delegation
When used with a data source, these functions can't be delegated. Only the first portion
of the data source will be retrieved and then the function applied. The result may not
represent the complete story. A warning may appear at authoring time to remind you of
this limitation and to suggest switching to delegable alternatives where possible. For
more information, see the delegation overview.
For example, when used with a data source containing a large table with 1 million
records, Last will be subject to the non-delegation limit and will not return the last
record of the entire data source. Likewise, using Index to request a record in the middle
of 1 million records will result in an error because the index is out of range based on the
non-delegation limit.
Syntax
First( Table )
Last( Table )
Examples
For the following examples, we'll use the IceCream data source, which contains the data
in this table:
This table can be placed in a collection with this formula (put in the OnStart formula for
a Button control and press the button):
Power Apps
Calculates values and performs actions for all the records in a table.
Description
The ForAll function evaluates a formula for all the records in a table. The formula can
calculate a value and/or perform actions, such as modifying data or working with a
connection. Use the With function to evaluate the formula for a single record.
Use the Sequence function with the ForAll function to iterate based on a count.
Fields of the record currently being processed are available within the formula. Use the
ThisRecord operator or simply reference fields by name as you would any other value.
The As operator can also be used to name the record being processed which can help
make your formula easier to understand and make nested records accessible. For more
information, see the examples below and working with record scope.
Return value
The result of each formula evaluation is returned in a table, in the same order as the
input table.
If the result of the formula is a single value, the resulting table will be a single-column
table. If the result of the formula is a record, the resulting table contains records with the
same columns as the result record.
If the result of the formula is a blank value, then there is no record in the result table for
that input record. In this case, there will be fewer records in the result table than the
source table.
Taking action
The formula can include functions that take action, such as modifying the records of a
data source with the Patch and Collect functions. The formula can also call methods on
connections. Multiple actions can be performed per record by using the ; operator. You
can't modify the table that is the subject of the ForAll function.
When writing your formula, keep in mind that records can be processed in any order
and, when possible, in parallel. The first record of the table may be processed after the
last record.
Take care to avoid ordering dependencies. For this reason, you can't use the
UpdateContext, Clear, and ClearCollect functions within a ForAll function because they
could easily be used to hold variables that would be susceptible to this effect. You can
use Collect, but the order in which records are added is undefined.
Several functions that modify data sources, including Collect, Remove, and Update,
return the changed data source as their return value. These return values can be large
and consume significant resources if returned for every record of the ForAll table. You
may also find that these return values are not what you expect because ForAll can
operate in parallel and may separate the side effects of these functions from obtaining
their result. If the return value from ForAll is not used, which is often the case with data
modification functions, then the return value will not be created and there are no
resource or order concerns. But if you are using the result of a ForAll and one of the
functions that returns a data source, think carefully about how you structure the result
and try it out first on small data sets.
Alternatives
Many functions in Power Apps can process more than one value at a time through the
use of a single-column table. For example, the Len function can process a table of text
values, returning a table of lengths, in the same manner, that ForAll could. This can
eliminate the need to use ForAll in many cases, can be more efficient, and is easier to
read.
Another consideration is that ForAll is not delegable while other functions may be, such
as Filter.
Delegation
When used with a data source, this function can't be delegated. Only the first portion of
the data source will be retrieved and then the function applied. The result may not
represent the complete story. A warning may appear at authoring time to remind you of
this limitation and to suggest switching to delegable alternatives where possible. For
more information, see the delegation overview.
Syntax
ForAll(Table, Formula)
Table - Required. Table to be acted upon.
Formula - Required. The formula to evaluate for all records of the Table.
Examples
Calculations
The following examples use the Squares data source:
To create this data source as a collection, set the OnSelect property of a Button control
to this formula, open Preview mode, and then select the button:
ForAll( Squares, For all the records of the input table, calculates the square root of
Sqrt( Value ) )
the Value column. The Sqrt function can also be used with a single-
column table, making it possible perform this example without
Sqrt( Squares ) using ForAll.
ForAll( Squares, For all the records of the input table, raises the Value column to the
Power( Value, 3 ) ) third power. The Power function does not support single-column
tables. Therefore, ForAll must be used in this case.
Using a connection
The following examples use the Expressions data source:
To create this data source as a collection, set the OnSelect property of a Button control
to this formula, open Preview mode, and then select the button:
ClearCollect( Expressions, [ "Hello", "Good morning", "Thank you", "Goodbye" ] )
This example also uses a Microsoft Translator connection. To add this connection to your
app, see the article about how to manage connections.
Copying a table
Sometimes you need to filter, shape, sort, and manipulate data. Power Apps provides
many functions for doing this, such as Filter, AddColumns, and Sort. Power Apps treat
each table as a value, allowing it to flow through formulas and be consumed easily.
And sometimes you want to make a copy of this result for later use, or you want to
move information from one data source to another. Power Apps provides the Collect
function to copy data.
But before you make that copy, think carefully if it is needed. Many situations can be
addressed by filtering and shaping the underlying data source on-demand with a
formula. Some of the downsides to making a copy include:
Two copies of the same information mean that one of them can fall out of sync.
Making a copy can consume much of the computer memory, network bandwidth,
and/or time.
For most data sources, copying cannot be delegated, limiting how much data can
be moved.
Power Apps
ClearCollect( Products,
Table(
Our goal is to work with a derivative table that includes only the items where more has
been requested than is available, and for which we need to place an order:
We can perform this task in a couple of different ways, all of which produce the same
result, with various pros and cons.
Power Apps
ShowColumns(
AddColumns(
),
"Product",
"Quantity To Order"
A record scope is created by the Filter and AddColumns functions to perform the
comparison and subtraction operations, respectively, with the 'Quantity Requested' and
'Quantity Available' fields of each record.
In this example, the Filter function can be delegated. This is important, as it can find all
the products that meet the criteria, even if that is only a few records out of a table of
millions. At this time, ShowColumns and AddColumns cannot be delegated, so the
actual number of products that need to be ordered will be limited. If you know the size
of this result will always be relatively small, this approach is fine.
And because we didn't make a copy, there is no additional copy of the information to
manage or fall out of date.
ForAll on demand
Another approach is to use the ForAll function to replace the table-shaping functions:
Power Apps
ForAll( Products,
Product: Product,
This formula may be simpler for some people to read and write.
No part of the ForAll is delegable. Only the first portion of the Products table will be
evaluated, which could be a problem if this table is large. Because Filter could be
delegated in the previous example, it could work better with large data sets.
In some situations, a copy of data may be required. You may need to move information
from one data source to another. In this example, orders are placed through a
NewOrder table on a vendor's system. For high-speed user interactions, you may want
to cache a local copy of a table so that there is no server latency.
We use the same table shaping as the previous two examples, but we capture the result
into a collection:
Power Apps
ClearCollect( NewOrder,
ShowColumns(
AddColumns(
),
"Product",
"Quantity To Order"
Power Apps
ClearCollect( NewOrder,
ForAll( Products,
Product: Product,
'Quantity To Order': 'Quantity Requested' - 'Quantity
Available'
ClearCollect and Collect can't be delegated. As a result, the amount of data that can be
moved in this manner is limited.
Power Apps
Clear( ProductsToOrder );
ForAll( Products,
Collect( NewOrder,
Product: Product,
'Quantity To Order': 'Quantity Requested' - 'Quantity
Available'
Again, the ForAll function can't be delegated at this time. If our Products table is large,
ForAll will look at the first set of records only and we may miss some products that need
to be ordered. But for tables that we know will remain small, this approach is fine.
Note that we are not capturing the result of the ForAll. The Collect function calls made
from within it will return the NewOrder data source for all the records, which could add
up to numerous data if we were capturing it.
Description
The GroupBy function returns a table with records grouped together based on the
values in one or more columns. Records in the same group are placed into a single
record, with a column added that holds a nested table of the remaining columns.
The Ungroup function reverses the GroupBy process. This function returns a table,
breaking into separate records any records that were grouped together.
You can group records by using GroupBy, modify the table that it returns, and then
ungroup records in the modified table by using Ungroup. For example, you can remove
a group of records by following this approach:
Ungroup tries to preserve the original order of the records that were fed to GroupBy.
This isn't always possible (for example, if the original table contains blank records).
A table is a value in Power Apps, just like a string or a number. You can specify a table as
an argument for a function, and a function can return a table. GroupBy and Ungroup
don't modify a table; instead they take a table as an argument and return a different
table. See working with tables for more details.
Syntax
GroupBy( Table, ColumnName1 [, ColumnName2, ... ], GroupColumnName )
Table - Required. Table to be grouped.
GroupColumnName - Required. The column name for the storage of record data
not in the ColumnName(s).
7 Note
For SharePoint and Excel data sources that contain column names with
spaces, specify each space as "_x0020_". For example, specify "Column
Name" as "Column_x0020_Name".
GroupColumnName - Required. The column that contains the record data setup
with the GroupBy function.
7 Note
For SharePoint and Excel data sources that contain column names with
spaces, specify each space as "_x0020_". For example, specify "Column
Name" as "Column_x0020_Name".
Examples
Create a collection
1. Add a button, and set its Text property so that the button shows Original.
2. Set the OnSelect property of the Original button to this formula:
Power Apps
ClearCollect( CityPopulations,
3. While holding down the Alt key, select the Original button.
You just created a collection, named CityPopulations, that contains this data:
You just created a collection, named CityPopulations, that contains this data:
4. To display this collection, select Collections on the File menu and then select the
CityPopulations collection. The first five records in the collection appear:
Group records
1. Add another button, and set its Text property to "Group".
2. Set the OnSelect property of this button to this formula:
3. While holding down the Alt key, select the Group button.
You just created a collection, named CitiesByCountry, in which the records of the
previous collection are grouped by the Country column.
4. To display the first five records in this collection, select Collections on the File
menu.
5. To display the populations of cities in a country, select the table icon in the Cities
column for that country (for example, Germany):
3. While holding down the Alt key, select the button that you added.
Aggregate results
Something else we can do with a grouped table is to aggregate the results. In this
example, we will sum the population of the major cities in each country.
1. Add another button, and set its Text property so that the button shows "Sum".
Now that we have the sum that we want, we can use DropColumns to remove the
sub tables.
3. Add another button, and set its Text property so that the button shows
"SumOnly".
Converts a GUID (Globally Unique Identifier ) string to a GUID value or creates a new
GUID value.
Description
Use the GUID function to convert a string that contains the hexadecimal representation
of a GUID into a GUID value that can be passed to a database. GUID values are used as
keys by database systems such as Microsoft Dataverse and SQL Server.
The string passed can contain uppercase or lowercase letters, but it must be 32
hexadecimal digits in either of these formats:
To convert a GUID value to a string, simply use it in a string context. The GUID value will
be converted to a hexadecimal representation string with hyphens and lowercase letters.
When generating a new GUID, this function uses pseudo-random numbers to create a
version 4 IETF RFC 4122 GUID. When converting a string to a GUID, this function
supports any GUID version by accepting any string of 32 hexadecimal digits.
Volatile functions
GUID is a volatile function when used without an argument. Each time the function is
evaluated, it returns a different value.
When used in a data-flow formula, a volatile function will return a different value only if
the formula in which it appears is reevaluated. If nothing else changes in the formula, it
will have the same value throughout the execution of your app.
For example, a label control for which the Text property is set to GUID() won't change
while your app is active. Only closing and reopening the app will result in a different
value.
The function will be reevaluated if it's part of a formula in which something else has
changed. If we set the Text property of a Label control to this formula, for example, a
GUID is generated each time the user changes the value of the Text input control:
When used in a behavior formula, GUID will be evaluated each time the formula is
evaluated. For more information, see the examples later in this topic.
Syntax
GUID( [ GUIDString ] )
GUID( Untyped )
Untyped - Required. Untyped object that represents a GUID. Acceptable values are
dependent on the untyped provider. For JSON, the untyped object is expected to
be GUID represented as a JSON string.
Examples
Basic usage
To return a GUID value based on the hexadecimal string representation:
Power Apps
GUID( "0f8fad5b-d9cb-469f-a165-70867728950e" )
You can also provide the GUID string without hyphens. This formula returns the same
GUID value:
Power Apps
GUID( "0f8fad5bd9cb469fa16570867728950e" )
Used in context, to set the Status field of a new database record to a well-established
value:
Power Apps
Patch( Products, Default( Products ), { Status: GUID( "F9168C5E-CEB2-4faa-
B6BF-329BF39FA1E4" ) } )
You probably don't want to show GUIDs to your users, but GUIDs can help you debug
your app. To show the value of the Status field in the record that you created in the
previous example, set the Text property of a Label control to this formula:
Power Apps
Power Apps
This formula creates a single-column table that's used to iterate five times,
resulting in five GUIDs.
2. Add a Data table control, set its Items property to NewGUIDs, and show the Value
field.
3. While holding down the Alt key, select the button by clicking or tapping it.
Power Apps
Description
The HashTags function scans a string for hashtags. Hashtags start with a pound
character (#), which is followed by any combination of:
HashTags returns a one-column table that contains the hashtags in the string. If the
string contains no hashtags, the function returns a one-column table that's empty.
Syntax
HashTags( String )
Examples
Step by step
1. Add a Text input control, name it Tweet, and type this sentence into it:
This #app is #AMAZING and can #coUnt123 or #123abc but not #1-23 or #$*
(#@")
2. Add a vertical custom gallery, and set its Items property to this function:
HashTags(Tweet.Text)
Description
The Day function returns the day component of a Date/Time value, ranging from 1 to
31.
The Month function returns the month component of a Date/Time value, ranging from
1 to 12.
The Year function returns the year component of a Date/Time value, starting with 1900.
The Hour function returns the hour component of a Date/Time value, ranging from 0
(12:00 AM) to 23 (11:00 PM).
The Minute function returns the minute component of a Date/Time value, ranging from
0 to 59.
The Second function returns the second component of a Date/Time value, ranging from
0 to 59.
The Weekday function returns the weekday of a Date/Time value. By default, the result
ranges from 1 (Sunday) to 7 (Saturday). You can specify a different range with an
Microsoft Excel Weekday function code or a StartOfWeek enumeration value:
Syntax
Day( DateTime )
Month( DateTime )
Year( DateTime )
Hour( DateTime )
Minute( DateTime )
Second( DateTime )
Examples
For the following example, the current time is 3:59:37 PM on Thursday, April 9, 2015.
Some of these operators are dependent on the language of the author. For more
information about language support in canvas apps, see Global apps.
"..." Text string "Hello, World" Text strings are enclosed in double
quotes
. Property Slider1.Value
Extracts a property from a table,
Selector Color.Red
control, signal, or enumeration. For
Acceleration.X backward compatibility, ! may also be
used.
.
Decimal 1.23 Separator between whole and fractional
[language separator parts of a number. The character
dependent] depends on the language.
* 2*3 Multiplication
& String "hello" & " " & Makes multiple strings appear
concatenation "world" continuous
operator
&& or And Logical Price < 100 && Logical conjunction, equivalent to the
operators Slider1.Value = 20
And function
or Price < 100 And
Slider1.Value = 20
! or Not !(Price < 100) or Not Logical negation, equivalent to the Not
(Price < 100) function
,
List separator If( X < 10, "Low", Separates:
[language "Good" )
arguments in function calls
dependent] { X: 12, Y: 32 }
fields in a record
[ 1, 2, 3 ] records in a table
;
Formula Collect(T, A); Separate invocations of functions in
[language chaining Navigate(S1, "") behavior properties. The chaining
dependent] operator depends on the language.
7 Note
The @ operator can also be used to validate the type of the record object against a
data source. For example, Collect(coll,Account@{'Account Number: 1111')
The gallery shows all products except Callisto because the name of that product is
the only one that doesn't contain the letter you specified.
The gallery shows only Europa because only its name contains the letter that you
specified in the case that you specified.
ThisItem Gallery control
The default name for the current record in a Gallery or form
Edit form control
control.
Display form control
ThisRecord ForAll, Filter, With, The default name for the current record in ForAll and other
Sum and other record scope functions.
record scope
functions
As name Gallery control
Defines a name for the current record, replacing default
ForAll, Filter, With, ThisItem or ThisRecord. Use As to make formulas easier to
Sum and other understand and resolve ambiguity when nesting.
record scope
functions
ThisItem operator
For example, in the following Gallery control, the Items property is set to the Employees
data source (such as the Employees table included with the Northwind Traders sample):
Power Apps
Employees
The first item in the gallery is a template that is replicated for each employee. In the
template, the formula for the picture uses ThisItem to refer to the current item:
Power Apps
ThisItem.Picture
Power Apps
ThisRecord operator
ThisRecord is used in functions that have a record scope. For example, we can use the
Filter function with our gallery's Items property to only show first names that being with
M:
Power Apps
ThisRecord is optional and implied by using the fields directly, for example, in this case,
we could have written:
Power Apps
Although optional, using ThisRecord can make formulas easier to understand and may
be required in ambiguous situations where a field name may also be a relationship
name. ThisRecord is optional while ThisItem is always required.
Use ThisRecord to reference the whole record with Patch, Collect, and other record
scope functions. For example, the following formula sets the status for all inactive
employees to active:
Power Apps
ForAll( InactiveEmployees,
As operator
Use the As operator to name a record in a gallery or record scope function, overriding
the default ThisItem or ThisRecord. Naming the record can make your formulas easier
to understand and may be required in nested situations to access records in other
scopes.
For example, you can modify the Items property of our gallery to use As to identify that
we are working with an Employee:
Power Apps
Employees As Employee
The formulas for the picture and name are adjusted to use this name for the current
record:
Power Apps
Employee.Picture
Power Apps
Employee.'First Name' & " " & Employee.'Last Name'
As can also be used with record scope functions to replace the default name
ThisRecord. We can apply this to our previous example to clarify the record we're
working with:
Power Apps
When nesting galleries and record scope functions, ThisItem and ThisRecord always
refers to the inner most scope, leaving records in outer scopes unavailable. Use As to
make all record scopes available by giving each a unique name.
For example, this formula produces a chessboard pattern as a text string by nesting two
ForAll functions:
Power Apps
Concat(
Concat(
),
Value
) & Char(10)
),
Value
A similar example is possible with nested Gallery controls instead of ForAll functions.
Let's start with the vertical gallery for the Rank. This gallery control will have an Items
formula of:
Power Apps
Sequence(8) as Rank
Within this gallery, we'll place a horizontal gallery for the File, that will be replicated for
each Rank, with an Items property of:
Power Apps
Sequence(8) as File
And finally, within this gallery, we'll add a Label control that will be replicated for each
File and each Rank. We'll size it to fill the entire space and use the Fill property to
provide the color with this formula:
Power Apps
Method Description
By Any control can be referenced by name from anywhere within the app.
control
name For example, Label1.Fill refers to the fill property of the control who's name is Label1.
Self It's often convenient to reference another property of the same control when writing a
operator formula. Instead of using an absolute reference by name, it's easier and more portable
to use a relative reference to oneself. The Self operator provides that easy access to
the current control.
For example, Self.Fill refers to the fill color of the current control.
Parent Some controls host other controls, such as the Screen and Gallery controls. The
operator hosting control of the controls within it's called the parent. Like the Self operator, the
Parent operator provides an easy relative reference to the container control.
For example, Parent.Fill refers to the fill property of the control that is the container for
the current control.
Self and Parent are operators and not properties on the controls themselves. Referring
to Parent.Parent, Self.Parent or Parent.Self is not supported.
Identifier names
The names of variables, data sources, columns, and other objects can contain any
Unicode .
Use single quotes around a name that contains a space or other special character.
Use two single quotes together to represent one single quote in the name. Names that
don't contain special characters don't require single quotes.
Here are some example column names you might encounter in a table, and how they're
represented in a formula:
SimpleName SimpleName
NameWith123Numbers NameWith123Numbers
Display name - A name that is user-friendly and intended to be seen by end users.
This name may not be unique, may change over time, may contain spaces and any
Unicode character, and may be localized into different languages. Corresponding
to the example above, the display name may be Custom Field with space in
between the words.
Since display names are easier to understand, Canvas apps will suggest them as choices
and not suggest logical names. Although logical names aren't suggested, they can still
be used if typed indirectly.
For example, imagine you've added a Custom Field to a table in Dataverse. A logical
name will be assigned for you by the system, which you can modify only when creating
the field. The result would look similar to:
When authoring a reference to a field of Accounts, the suggestion will be made to use
'Custom Field' since this is the display name. Single quotes must be used because this
name has a space in it:
After selecting the suggestion, 'Custom Field' is shown in the formula bar and the data is
retrieved:
Although it isn't suggested, we could also use the logical name for this field. This will
result in the same data being retrieved. Single quotes are not required since this name
doesn't contain spaces or special characters:
Behind the scenes, a mapping is maintained between the display names seen in
formulas and the underlying logical names. Since logical names must be used to interact
with the data source, this mapping is used to convert from the current display name to
the logical name automatically and that is what is seen in the network traffic. This
mapping is also used to convert back to logical names to switch into new display names,
for example, if a display name changes or a maker in a different language edits the app.
7 Note
Logical names are not translated when moving an app between environments. For
Dataverse system table and field names, this should not be a problem as logical
names are consistent across environments. But any custom fields, such as
cra3a_customfield in this example above, may have a different environment prefix
(cra3a in this case). Display names are preferred as they can be matched against
display names in the new environment.
Name disambiguation
Since display names aren't unique, the same display name may appear more than once
in the same table. When this happens, the logical name will be added to the end of the
display name in parenthesis for one of more of the conflicting names. Building on the
example above, if there was a second field with the same display name of Custom Field
with a logical name of cra3a_customfieldalt then the suggestions would show:
Name disambiguation strings are added in other situations where name conflicts occur,
such as the names of table, choices, and other Dataverse items.
Disambiguation operator
Some functions create record scopes for accessing the fields of table while processing
each record, such as Filter, AddColumns, and Sum. Field names added with the record
scope override the same names from elsewhere in the app. When this happens, you can
still access values from outside the record scope with the @ disambiguation operator:
To access values from nested record scopes, use the @ operator with the name of
the table being operated upon using this pattern:
Table[@FieldName]
To access global values, such as data sources, collections, and context variables,
use the pattern [@ObjectName] (without a table designation).
Determines whether any condition in a set is true (If) or the result of a formula matches
any value in a set (Switch) and then returns a result or executes an action.
Description
The If function tests one or more conditions until a true result is found. If such a result is
found, a corresponding value is returned. If no such result is found, a default value is
returned. In either case, the returned value might be a string to show, a formula to
evaluate, or another form of result.
The Switch function evaluates a formula and determines whether the result matches any
value in a sequence that you specify. If a match is found, a corresponding value is
returned. If no match is found, a default value is returned. In either case, the returned
value might be a string to show, a formula to evaluate, or another form of result.
If and Switch are very similar, but you should use the best function for your situation:
Use If to evaluate a single condition. The most common syntax for this function is
If( Condition, ThenResult, DefaultResult ), which provides the common “if … then …
else …” pattern seen in other programming tools.
Use If to evaluate multiple unrelated conditions. In Power Apps (unlike Microsoft
Excel), you can specify multiple conditions without having to nest If formulas.
Use Switch to evaluate a single condition against multiple possible matches. You
can also use If in this case, but you'd need to repeat the formula for each possible
match.
You can use both of these functions in behavior formulas to branch between two or
more actions. Only one branch will trigger an action. Conditions and matches are
evaluated in order, and they stop if a condition is true or a match is found.
Blank is returned if no conditions are true, no matches are found, and you don't specify
a default result.
Syntax
If( Condition, ThenResult [, DefaultResult ] )
Examples
Values in formulas
In the following examples, a Slider control (named Slider1) has a value of 25.
If( Slider1.Value = 25, The condition is true, and the corresponding result "Result1"
"Result1" ) is returned.
If( Slider1.Value = 25, The condition is true, and the corresponding result "Result1"
"Result1", "Result2" ) is returned.
If( Slider1.Value = 25, The first condition is true, and the corresponding "Result1"
"Result1", result is returned. The second condition is also
Slider1.Value > 0, true, but it isn't evaluated because it appears later
"Result2" ) in the argument list than a condition that evaluates
to true.
Formula Description Result
If( IsBlank( Slider1.Value ), The first condition is false because the slider isn't "Result2"
"Result1", blank. The second condition is true because the
IsNumeric( Slider1.Value ), slider's value is a number, and the corresponding
"Result2" ) result is returned.
If( Slider1.Value > 1000, Both the first and second conditions are false, a "Result3"
"Result1", DefaultResult was provided, and it's returned.
Slider1.Value > 50,
"Result2", "Result3")
Switch( Slider1.Value, 25, The slider's value matches the first value to be "Result1"
"Result1" ) checked, and the corresponding result is returned.
Switch( Slider1.Value, 20, The slider's value matches the second value to be "Result2"
"Result1", 25, "Result2", checked, and the corresponding result is returned.
30, "Result3" )
Switch( Slider1.Value, 20, The slider's value doesn't match any value to be "DefaultResult"
"Result1", 10, "Result2", 0, checked. A DefaultResult was provided, so it's
"Result3", "DefaultResult" returned.
)
Step by step
1. Add a Text input control, and name it Text1 if it doesn't have that name by default.
3. Add a Label control, and set its Text property to this formula:
If( Value(Text1.Text) < 20, "Order MANY more!", Value(Text1.Text) < 40, "Order
more!", Text1.Text )
The Label control shows Order more! because the value of Text1 is more than 20
but less than 40.
The Label control shows Order MANY more! because the value of Text1 is less
than 20.
The Label control shows the value that you typed because it's more than 40.
Error, IfError, IsError, IsBlankOrError
functions in Power Apps
Article • 02/23/2023 • 9 minutes to read
Detects errors and provides an alternative value or takes action. Create a custom error
or pass through an error.
7 Note
The behavior that this article describes is available only when the Formula-
level error management preview feature in Settings > Upcoming features >
Preview is turned on.
IfError
The IfError function tests values until it finds an error. If the function discovers an error,
the function evaluates and returns a corresponding replacement value and stops further
evaluation. A default value can also be supplied for when no errors are found. The
structure of IfError resembles that of the If function: IfError tests for errors, while If tests
for true.
Use IfError to replace an error with a valid value so that downstream calculations can
continue. For example, use this function if user input might result in a division by zero:
Power Apps
IfError( 1/x, 0 )
This formula returns 0 if the value of x is zero, as 1/x will produce an error. If x isn't
zero, then 1/x is returned.
Power Apps
The second Patch function to DS2 will be attempted even if the Patch to DS1 fails. The
scope of an error is limited to each formula that is chained.
Use IfError to do an action and only continue processing if the action was successful.
Applying IfError to this example:
Power Apps
IfError(
If the Patch of DS1 has a problem, the first Notify is executed. No further processing
occurs including the second Patch of DS2 . If the first Patch succeeds, the second Patch
will execute.
Building on the last example, the return value from IfError can be checked to determine
if there were any problems:
Power Apps
IfError(
true
Type compatibility
IfError will return the value of one of its arguments. The types of all values that might be
returned by IfError must be compatible.
In the last example, Patch will return a record that isn't compatible with the Booleans
used for the Replacement formulas or the DefaultResult. Which is fine, since there's no
situation in which the return value from these Patch calls would be returned by IfError.
7 Note
While the behavior in process for a change, the types of all arguments to IfError
must be compatible currently.
Power Apps
IfError( 1/x, 0 )
The types of 1/x and 0 were compatible as both were numbers. If they're not, the
second argument will be coerced to match the type of the first argument.
Power Apps
The above formula won't work. The text string "#DIV/0!" will be coerced to the type of
the first argument to IfError, which is a number. The result of IfError will be yet another
error since the text string can't be coerced. As a fix, convert the first argument to a text
string so that IfError always returns a text string:
Power Apps
As seen above, IfError can return an error if the Replacement or DefaultResult is an error.
FirstError / AllErrors
Within in the replacement formulas, information about the errors found is available
through the FirstError record and AllErrors table. AllErrors is a table of error information
records with FirstError being a shortcut to the first record of this table. FirstError will
always return the same value as First( AllErrors ).
Message Text Message about the error, suitable to be displayed to the end user.
string
Source Text Location in where the error originated, used for reporting. For example,
string for a formula bound to a control property, this will be in the form
ControlName.PropertyName.
Observed Text Location in where the error is surfaced to the user, used for reporting. For
string example, for a formula bound to a control property, this will be in the
form ControlName.PropertyName.
Details Record Details about the error. At present, details are provided only for network
errors. This record includes HttpStatusCode whcih contains the HTTP
status code and HttpResponse which contains the body of the response
from the connector or service.
For example, consider the following formula as a Button control's OnSelect property:
Power Apps
Set( a, 1/0 )
Power Apps
The example formula above would display the following banner when the two buttons
are activated in sequence:
Typically, there'll be only one error that FirstError can sufficiently work with. However,
there are scenarios where multiple errors may be returned. For example, when using a
formula chaining operator or the Concurrent function. Even in these situations,
reporting FirstError might be enough to reveal a problem instead overloading a user
with multiple errors. If you still have a requirement to work with each error individually,
you can use the AllErrors table.
IsError
The IsError function tests for an error value.
IsBlankOrError
The IsBlankOrError function tests for either a blank value or an error value and is the
equivalent of Or( IsBlank( X ), IsError( X ) ) .
When enabling error handling for existing apps, consider replacing IsBlank with
IsBlankOrError to preserve existing app behavior. Prior to the addition of error handling,
a blank value was used to represent both null values from databases and error values.
Error handling separates these two interpretations of blank which could change the
behavior of existing apps that continue to use IsBlank.
Error
Use the Error function to create and report a custom error. For example, you might have
logic to determine whether any given value is valid for your context or not—something
not checked for a problem automatically. You can create and return your own error,
complete with Kind and Message, using the same record described above for the IfError
function.
In the context of IfError, use the Error function to rethrow or pass through an error. For
example, your logic in IfError may decide that in some cases an error can be safely
ignored, but in other cases the error is important to send through. Within IfError or
App.OnError, use Error( FirstError ) to pass through an error.
The Error function can also be passed a table of errors, as would be found in the
AllErrors table. Use Error( AllErrors ) to rethrow all the errors and not just the first.
A blank record or empty table passed to Error results in no error.
Syntax
Error( ErrorRecord )
Error( ErrorTable )
IsError( Value )
IsBlankOrError( Value )
Examples
Simple IfError
IfError( 1, The first argument isn't an error. The function has no other errors to check 1
2) and no default return value. The function returns the last value argument
evaluated.
IfError( The first argument returns an error value (because of division by zero). The 2
1/0, 2 ) function evaluates the second argument and returns it as the result.
IfError( The first argument isn't an error. The function has no other errors to check 30
10, 20, 30 but does have a default return value. The function returns the DefaultResult
) argument.
Formula Description Result
IfError( The first argument 10 isn't an error, so the function doesn't evaluate that 300
10, 11, 20, argument's corresponding replacement 11. The third argument 20 isn't an
21, 300 ) error either, so the function doesn't evaluate that argument's corresponding
replacement 21. The fifth argument 300 has no corresponding replacement
and is the default result. The function returns that result because the
formula contains no errors.
IfError( The first argument returns an error value (due to division by zero). The 1
1/0, function evaluates the second argument and displays a message to the user.
Notify( The return value of IfError is the return value of Notify, coerced to the same
"There type as the first argument to IfError (a number).
was an
internal
problem"
))
Simple IsError
If( IsError( The argument to IsError returns an error value (because of division by true
1/0 ), Notify( zero). This function returns true, which causes the If to display a
"There was message to the user with the Notify function. The return value of If is
an internal the return value of Notify, coerced to the same type as the first
problem" ) ) argument to If (a boolean).
Simple IsBlankOrError
Simple Error
In this example, dates are validated relative to one another, resulting in an error if there
is a problem.
Power Apps
In this example, some errors are allowed to pass through while others are supressed and
replaced with a value. In the first case, b will be in an error state because the Value
function has an invalid argument. Because this is unexpcted by the formula writer, it is
passed through so the user will see it. In the second case, with the same formula, b will
have the value 0, resulting in a division by zero. In this case, the formula writer may
know that this is acceptable for this logic, suppress the error (no banner is shown), and
return -1 instead.
Power Apps
With( {a: 1, b: 0} )
// returns -1
The AllErrors table can be filtered like any other table. Used with the Error function,
expected errors can be removed and the remaining errors retained and reported. For
example, if we knew that division by zero was not going to be a problem in a particular
context, those errors could be filtered out, leaving all other errors intact with the
following formula:
Power Apps
Step by step
1. Add a Text input control, and name it TextInput1 if it doesn't have that name by
default.
2. Add a Label control, and name it Label1 if it doesn't have that name by default.
Power Apps
Label1 will show the value 1234 as this is a valid input to the Value function.
Label1 will show the value -1 as this isn't a valid input to the Value function.
Without wrapping the Value function with IfError, the label would show no value as
the error value is treated as a blank.
See also
Formula reference for Power Apps
Operators and Identifiers in Power Apps
Article • 03/01/2023 • 12 minutes to read
Some of these operators are dependent on the language of the author. For more
information about language support in canvas apps, see Global apps.
"..." Text string "Hello, World" Text strings are enclosed in double
quotes
. Property Slider1.Value
Extracts a property from a table,
Selector Color.Red
control, signal, or enumeration. For
Acceleration.X backward compatibility, ! may also be
used.
.
Decimal 1.23 Separator between whole and fractional
[language separator parts of a number. The character
dependent] depends on the language.
* 2*3 Multiplication
& String "hello" & " " & Makes multiple strings appear
concatenation "world" continuous
operator
&& or And Logical Price < 100 && Logical conjunction, equivalent to the
operators Slider1.Value = 20
And function
or Price < 100 And
Slider1.Value = 20
! or Not !(Price < 100) or Not Logical negation, equivalent to the Not
(Price < 100) function
,
List separator If( X < 10, "Low", Separates:
[language "Good" )
arguments in function calls
dependent] { X: 12, Y: 32 }
fields in a record
[ 1, 2, 3 ] records in a table
;
Formula Collect(T, A); Separate invocations of functions in
[language chaining Navigate(S1, "") behavior properties. The chaining
dependent] operator depends on the language.
7 Note
The @ operator can also be used to validate the type of the record object against a
data source. For example, Collect(coll,Account@{'Account Number: 1111')
The gallery shows all products except Callisto because the name of that product is
the only one that doesn't contain the letter you specified.
The gallery shows only Europa because only its name contains the letter that you
specified in the case that you specified.
ThisItem Gallery control
The default name for the current record in a Gallery or form
Edit form control
control.
Display form control
ThisRecord ForAll, Filter, With, The default name for the current record in ForAll and other
Sum and other record scope functions.
record scope
functions
As name Gallery control
Defines a name for the current record, replacing default
ForAll, Filter, With, ThisItem or ThisRecord. Use As to make formulas easier to
Sum and other understand and resolve ambiguity when nesting.
record scope
functions
ThisItem operator
For example, in the following Gallery control, the Items property is set to the Employees
data source (such as the Employees table included with the Northwind Traders sample):
Power Apps
Employees
The first item in the gallery is a template that is replicated for each employee. In the
template, the formula for the picture uses ThisItem to refer to the current item:
Power Apps
ThisItem.Picture
Power Apps
ThisRecord operator
ThisRecord is used in functions that have a record scope. For example, we can use the
Filter function with our gallery's Items property to only show first names that being with
M:
Power Apps
ThisRecord is optional and implied by using the fields directly, for example, in this case,
we could have written:
Power Apps
Although optional, using ThisRecord can make formulas easier to understand and may
be required in ambiguous situations where a field name may also be a relationship
name. ThisRecord is optional while ThisItem is always required.
Use ThisRecord to reference the whole record with Patch, Collect, and other record
scope functions. For example, the following formula sets the status for all inactive
employees to active:
Power Apps
ForAll( InactiveEmployees,
As operator
Use the As operator to name a record in a gallery or record scope function, overriding
the default ThisItem or ThisRecord. Naming the record can make your formulas easier
to understand and may be required in nested situations to access records in other
scopes.
For example, you can modify the Items property of our gallery to use As to identify that
we are working with an Employee:
Power Apps
Employees As Employee
The formulas for the picture and name are adjusted to use this name for the current
record:
Power Apps
Employee.Picture
Power Apps
Employee.'First Name' & " " & Employee.'Last Name'
As can also be used with record scope functions to replace the default name
ThisRecord. We can apply this to our previous example to clarify the record we're
working with:
Power Apps
When nesting galleries and record scope functions, ThisItem and ThisRecord always
refers to the inner most scope, leaving records in outer scopes unavailable. Use As to
make all record scopes available by giving each a unique name.
For example, this formula produces a chessboard pattern as a text string by nesting two
ForAll functions:
Power Apps
Concat(
Concat(
),
Value
) & Char(10)
),
Value
A similar example is possible with nested Gallery controls instead of ForAll functions.
Let's start with the vertical gallery for the Rank. This gallery control will have an Items
formula of:
Power Apps
Sequence(8) as Rank
Within this gallery, we'll place a horizontal gallery for the File, that will be replicated for
each Rank, with an Items property of:
Power Apps
Sequence(8) as File
And finally, within this gallery, we'll add a Label control that will be replicated for each
File and each Rank. We'll size it to fill the entire space and use the Fill property to
provide the color with this formula:
Power Apps
Method Description
By Any control can be referenced by name from anywhere within the app.
control
name For example, Label1.Fill refers to the fill property of the control who's name is Label1.
Self It's often convenient to reference another property of the same control when writing a
operator formula. Instead of using an absolute reference by name, it's easier and more portable
to use a relative reference to oneself. The Self operator provides that easy access to
the current control.
For example, Self.Fill refers to the fill color of the current control.
Parent Some controls host other controls, such as the Screen and Gallery controls. The
operator hosting control of the controls within it's called the parent. Like the Self operator, the
Parent operator provides an easy relative reference to the container control.
For example, Parent.Fill refers to the fill property of the control that is the container for
the current control.
Self and Parent are operators and not properties on the controls themselves. Referring
to Parent.Parent, Self.Parent or Parent.Self is not supported.
Identifier names
The names of variables, data sources, columns, and other objects can contain any
Unicode .
Use single quotes around a name that contains a space or other special character.
Use two single quotes together to represent one single quote in the name. Names that
don't contain special characters don't require single quotes.
Here are some example column names you might encounter in a table, and how they're
represented in a formula:
SimpleName SimpleName
NameWith123Numbers NameWith123Numbers
Display name - A name that is user-friendly and intended to be seen by end users.
This name may not be unique, may change over time, may contain spaces and any
Unicode character, and may be localized into different languages. Corresponding
to the example above, the display name may be Custom Field with space in
between the words.
Since display names are easier to understand, Canvas apps will suggest them as choices
and not suggest logical names. Although logical names aren't suggested, they can still
be used if typed indirectly.
For example, imagine you've added a Custom Field to a table in Dataverse. A logical
name will be assigned for you by the system, which you can modify only when creating
the field. The result would look similar to:
When authoring a reference to a field of Accounts, the suggestion will be made to use
'Custom Field' since this is the display name. Single quotes must be used because this
name has a space in it:
After selecting the suggestion, 'Custom Field' is shown in the formula bar and the data is
retrieved:
Although it isn't suggested, we could also use the logical name for this field. This will
result in the same data being retrieved. Single quotes are not required since this name
doesn't contain spaces or special characters:
Behind the scenes, a mapping is maintained between the display names seen in
formulas and the underlying logical names. Since logical names must be used to interact
with the data source, this mapping is used to convert from the current display name to
the logical name automatically and that is what is seen in the network traffic. This
mapping is also used to convert back to logical names to switch into new display names,
for example, if a display name changes or a maker in a different language edits the app.
7 Note
Logical names are not translated when moving an app between environments. For
Dataverse system table and field names, this should not be a problem as logical
names are consistent across environments. But any custom fields, such as
cra3a_customfield in this example above, may have a different environment prefix
(cra3a in this case). Display names are preferred as they can be matched against
display names in the new environment.
Name disambiguation
Since display names aren't unique, the same display name may appear more than once
in the same table. When this happens, the logical name will be added to the end of the
display name in parenthesis for one of more of the conflicting names. Building on the
example above, if there was a second field with the same display name of Custom Field
with a logical name of cra3a_customfieldalt then the suggestions would show:
Name disambiguation strings are added in other situations where name conflicts occur,
such as the names of table, choices, and other Dataverse items.
Disambiguation operator
Some functions create record scopes for accessing the fields of table while processing
each record, such as Filter, AddColumns, and Sum. Field names added with the record
scope override the same names from elsewhere in the app. When this happens, you can
still access values from outside the record scope with the @ disambiguation operator:
To access values from nested record scopes, use the @ operator with the name of
the table being operated upon using this pattern:
Table[@FieldName]
To access global values, such as data sources, collections, and context variables,
use the pattern [@ObjectName] (without a table designation).
Returns the first, last, or a specific record, or a set of first or last records, from a table.
Description
The First function returns the first record of a table.
The FirstN function returns the first set of records of a table; the second argument
specifies the number of records to return.
The LastN function returns the last set of records of a table; the second argument
specifies the number of records to return.
The Index function returns a record of a table based on its ordered position in the table.
Record numbering begins with 1 so First( table ) returning the same record as
Index( table, 1 ) . Index returns an error if the requested record index is less than 1,
greater than the number of records in the table, or the table is empty.
First, Index, and Last return a single record. FirstN and LastN return a table, even if you
specify only a single record.
Delegation
When used with a data source, these functions can't be delegated. Only the first portion
of the data source will be retrieved and then the function applied. The result may not
represent the complete story. A warning may appear at authoring time to remind you of
this limitation and to suggest switching to delegable alternatives where possible. For
more information, see the delegation overview.
For example, when used with a data source containing a large table with 1 million
records, Last will be subject to the non-delegation limit and will not return the last
record of the entire data source. Likewise, using Index to request a record in the middle
of 1 million records will result in an error because the index is out of range based on the
non-delegation limit.
Syntax
First( Table )
Last( Table )
Examples
For the following examples, we'll use the IceCream data source, which contains the data
in this table:
This table can be placed in a collection with this formula (put in the OnStart formula for
a Button control and press the button):
Power Apps
Rounds a number.
Round rounds up if the next digit is 5 or higher. Otherwise, this function rounds
down.
RoundDown always rounds down to the previous lower number, towards zero.
RoundUp always rounds up to the next higher number, away from zero.
Greater than The number is rounded to the right of the decimal Round( 12.37, 1 ) returns
0 separator. 12.4.
Less than 0 The number is rounded to the left of the decimal Round( 12.37, -1 )
separator. returns 10.
The difference between Int and Trunc is in the handling of negative numbers. For
example, for an argument of -4.3 , Int will return the integer further away from zero, -5 ,
while Trunc will return the integer closer to zero, -4 . Int returns values that are unique
amongst the five rounding functions, while Trunc returns the same values as
RoundDown.
Use Trunc to extract the decimal portion of a number by subtracting it from the original,
for example X - Trunc(X) .
Decimal places cannot be specified with Trunc as it can with Microsoft Excel. Use
RoundDown instead when this is needed.
Single-column tables
These functions support single-column tables. If you pass a single number, the return
value is the rounded version of that number. If you pass a single-column table that
contains numbers, the return value is a single-column table of rounded numbers. The
DecimalPlaces parameter can be a single value or a single-column table. If the single-
column table has less values that the Number, zero is used for the remaining values. Use
ShowColumns and other table shaping functions to extract a single-column table from
a larger table.
Syntax
Round(Number, DecimalPlaces)
RoundDown(Number, DecimalPlaces)
RoundUp(Number, DecimalPlaces)
Int(Number)
Trunc(Number)
Examples
Rounding to a whole number.
7.9 8 8 7 7 7
-7.9 -8 -8 -7 -8 -7
7.5 8 8 7 7 7
-7.5 -8 -8 -7 -8 -7
7.1 7 8 7 7 7
-7.1 -7 -8 -7 -8 -7
Rounding to two decimal places to the right of the decimal separator (0.01).
Rounding to two decimal places to the left of the decimal separator (100).
[ 123.456,
[ 123,
[ 123.46,
[ 123,
[ 123.46,
987.593,
987,
987.59,
987.5,
988,
Tests whether a value is blank or a table contains no records, and provides a way to
create blank values.
Overview
Blank is a placeholder for "no value" or "unknown value." For example, a Combo box
control's Selected property is blank if the user hasn't made a selection. Many data
sources can store and return NULL values, which are represented in Power Apps as
blank.
Any property or calculated value in Power Apps can be blank. For example, a Boolean
value normally has one of two values: true or false. But in addition to these two, it can
also be blank indicating that the state is not known. This is similar to Microsoft Excel,
where a worksheet cell starts out as blank with no contents but can hold the values
TRUE or FALSE (among others). At any time, the contents of the cell can again be
cleared, returning it to a blank state.
Empty string refers to a string that contains no characters. The Len function returns zero
for such a string and it can be written in a formulas as two double quotes with nothing
in between "" . Some controls and data sources use an empty string to indicate a "no
value" condition. To simplify app creation, the IsBlank and Coalesce functions test for
both blank values or empty strings.
In the context of the IsEmpty function, empty is specific to tables that contain no
records. The table structure may be intact, complete with column names, but no data is
in the table. A table may start as empty, take on records and no longer be empty, and
then have the records removed and again be empty.
7 Note
We are in a period of transition. Until now, blank has also been used to report
errors, making it impossible to differentiate a valid "no value" from an error. For this
reason, at this time, storing blank values is supported only for local collections. You
can store blank values in other data sources if you turn on the Formula-level error
management experimental feature under Settings > Upcoming features >
Experimental. We are actively working to finish this feature and complete the
proper separation of blank values from errors.
Blank
The Blank function returns a blank value. Use this to store a NULL value in a data source
that supports these values, effectively removing any value from the field.
IsBlank
The IsBlank function tests for a blank value or an empty string. The test includes empty
strings to ease app creation since some data sources and controls use an empty string
when there is no value present. To test specifically for a blank value use if( Value =
Blank(), ... instead of IsBlank. The IsBlank function considers empty tables as not
When enabling error handling for existing apps, consider replacing IsBlank with
IsBlankOrError to preserve existing app behavior. Prior to the addition of error handling,
a blank value was used to represent both null values from databases and error values.
Error handling separates these two interpretations of blank which could change the
behavior of existing apps that continue to use IsBlank.
Coalesce
The Coalesce function evaluates its arguments in order and returns the first value that
isn't blank or an empty string. Use this function to replace a blank value or empty string
with a different value but leave non-blank and non-empty string values unchanged. If all
the arguments are blank or empty strings then the function returns blank, making
Coalesce a good way to convert empty strings to blank values.
Coalesce( value1, value2 ) is the more concise equivalent of If( Not IsBlank( value1
), value1, Not IsBlank( value2 ), value2 ) and doesn't require value1 and value2 to
be evaluated twice. The If function returns blank if there is no "else" formula as is the
case here.
All arguments to Coalesce must be of the same type; for example, you can't mix
numbers with text strings. The return value from Coalesce is of this common type.
IsEmpty
The IsEmpty function tests whether a table contains any records. It's equivalent to using
the CountRows function and checking for zero. You can check for data-source errors by
combining IsEmpty with the Errors function.
Syntax
Blank()
Value(s) – Required. Values to test. Each value is evaluated in order until a value
that is not blank and not an empty string is found. Values after this point are not
evaluated.
IsBlank( Value )
IsEmpty( Table )
Examples
Blank
7 Note
At this time, the following example only works for local collections. You can store
blank values in other data sources if you turn on the Formula-level error
management experimental feature under Settings > Upcoming features >
Experimental. We are actively working to finish this feature and complete the
separation of blank values from errors.
3. Preview your app, click or tap the button that you added, and then close Preview.
The Cities collection appears, showing one record with "Seattle" and "Rainy":
6. Add a Label control, and set its Text property to this formula:
Power Apps
The label shows false because the Weather field contains a value ("Rainy").
7. Add a second button, and set its OnSelect property to this formula:
Power Apps
8. Preview your app, click or tap the button that you added, and then close Preview.
The Weather field of the first record in Cities is replaced with a blank, removing
the "Rainy" that was there previously.
The label shows true because the Weather field no longer contains a value.
Coalesce
Coalesce( Blank(), 1 ) Tests the return value from the Blank function, which always 1
returns a blank value. Because the first argument is blank,
evaluation continues with the next argument until a non-blank
value and non-empty string is found.
Coalesce( "", "2" ) Tests the first argument which is an empty string. Because the 2
first argument is an empty string, evaluation continues with the
next argument until a non-blank value and non-empty string is
found.
Coalesce( Blank(), Coalesce starts at the beginning of the argument list and 3
"", Blank(), "", "3", evaluates each argument in turn until a non-blank value and
"4" ) non-empty string is found. In this case, the first four arguments
all return blank or an empty string, so evaluation continues to
the fifth argument. The fifth argument is non-blank and non-
empty string, so evaluation stops here. The value of the fifth
argument is returned, and the sixth argument isn't evaluated.
Coalesce( "" ) Tests the first argument which is an empty string. Because the blank
first argument is an empty string, and there are no more
arguments, the function returns blank.
IsBlank
1. Create an app from scratch, add a text-input control, and name it FirstName.
Power Apps
If( IsBlank( FirstName.Text ), "First Name is a required field." )
By default, the Text property of a text-input control is set to "Text input". Because
the property contains a value, it isn't blank, and the label doesn't display any
message.
3. Remove all the characters from the text-input control, including any spaces.
Because the Text property no longer contains any characters, it's an empty string,
and IsBlank( FirstName.Text ) will be true. The required field message is displayed.
For information about how to perform validation by using other tools, see the Validate
function and working with data sources.
Other examples:
IsBlank( Blank() ) Tests the return value from the Blank function, which always returns true
a blank value.
IsBlank( Because the collection exists, it isn't blank, even if it doesn't contain false
AnyCollection ) any records. To check for an empty collection, use IsEmpty instead.
IsBlank( Mid( The starting character for Mid is beyond the end of the string. The true
"Hello", 17, 2 ) ) result is an empty string.
IsBlank( If( false, An If function with no ElseResult. Because the condition is always true
false ) ) false, this If always returns blank.
IsEmpty
1. Create an app from scratch, and add a Button control.
3. Preview your app, click or tap the button that you added, and then close Preview.
4. Add a second button, and set its OnSelect property to this formula:
Clear( IceCream )
5. Preview your app, click or tap the second button, and then close Preview.
The Clear function removes all the records from a collection, resulting in an empty
collection. IsEmpty( IceCream ) returns true, and CountRows( IceCream ) returns
0.
You can also use IsEmpty to test whether a calculated table is empty, as these examples
show:
IsEmpty( [ 1, 2, 3 ] The single-column table contains three records and, therefore, isn't false
) empty.
IsEmpty( [ ] ) The single-column table contains no records and is empty. true
IsEmpty( Filter( The single-column table contains no values that are greater than 5. true
[ 1, 2, 3 ], Value > The result from the filter doesn't contain any records and is empty.
5))
Error, IfError, IsError, IsBlankOrError
functions in Power Apps
Article • 02/23/2023 • 9 minutes to read
Detects errors and provides an alternative value or takes action. Create a custom error
or pass through an error.
7 Note
The behavior that this article describes is available only when the Formula-
level error management preview feature in Settings > Upcoming features >
Preview is turned on.
IfError
The IfError function tests values until it finds an error. If the function discovers an error,
the function evaluates and returns a corresponding replacement value and stops further
evaluation. A default value can also be supplied for when no errors are found. The
structure of IfError resembles that of the If function: IfError tests for errors, while If tests
for true.
Use IfError to replace an error with a valid value so that downstream calculations can
continue. For example, use this function if user input might result in a division by zero:
Power Apps
IfError( 1/x, 0 )
This formula returns 0 if the value of x is zero, as 1/x will produce an error. If x isn't
zero, then 1/x is returned.
Power Apps
The second Patch function to DS2 will be attempted even if the Patch to DS1 fails. The
scope of an error is limited to each formula that is chained.
Use IfError to do an action and only continue processing if the action was successful.
Applying IfError to this example:
Power Apps
IfError(
If the Patch of DS1 has a problem, the first Notify is executed. No further processing
occurs including the second Patch of DS2 . If the first Patch succeeds, the second Patch
will execute.
Building on the last example, the return value from IfError can be checked to determine
if there were any problems:
Power Apps
IfError(
true
Type compatibility
IfError will return the value of one of its arguments. The types of all values that might be
returned by IfError must be compatible.
In the last example, Patch will return a record that isn't compatible with the Booleans
used for the Replacement formulas or the DefaultResult. Which is fine, since there's no
situation in which the return value from these Patch calls would be returned by IfError.
7 Note
While the behavior in process for a change, the types of all arguments to IfError
must be compatible currently.
Power Apps
IfError( 1/x, 0 )
The types of 1/x and 0 were compatible as both were numbers. If they're not, the
second argument will be coerced to match the type of the first argument.
Power Apps
The above formula won't work. The text string "#DIV/0!" will be coerced to the type of
the first argument to IfError, which is a number. The result of IfError will be yet another
error since the text string can't be coerced. As a fix, convert the first argument to a text
string so that IfError always returns a text string:
Power Apps
As seen above, IfError can return an error if the Replacement or DefaultResult is an error.
FirstError / AllErrors
Within in the replacement formulas, information about the errors found is available
through the FirstError record and AllErrors table. AllErrors is a table of error information
records with FirstError being a shortcut to the first record of this table. FirstError will
always return the same value as First( AllErrors ).
Message Text Message about the error, suitable to be displayed to the end user.
string
Source Text Location in where the error originated, used for reporting. For example,
string for a formula bound to a control property, this will be in the form
ControlName.PropertyName.
Observed Text Location in where the error is surfaced to the user, used for reporting. For
string example, for a formula bound to a control property, this will be in the
form ControlName.PropertyName.
Details Record Details about the error. At present, details are provided only for network
errors. This record includes HttpStatusCode whcih contains the HTTP
status code and HttpResponse which contains the body of the response
from the connector or service.
For example, consider the following formula as a Button control's OnSelect property:
Power Apps
Set( a, 1/0 )
Power Apps
The example formula above would display the following banner when the two buttons
are activated in sequence:
Typically, there'll be only one error that FirstError can sufficiently work with. However,
there are scenarios where multiple errors may be returned. For example, when using a
formula chaining operator or the Concurrent function. Even in these situations,
reporting FirstError might be enough to reveal a problem instead overloading a user
with multiple errors. If you still have a requirement to work with each error individually,
you can use the AllErrors table.
IsError
The IsError function tests for an error value.
IsBlankOrError
The IsBlankOrError function tests for either a blank value or an error value and is the
equivalent of Or( IsBlank( X ), IsError( X ) ) .
When enabling error handling for existing apps, consider replacing IsBlank with
IsBlankOrError to preserve existing app behavior. Prior to the addition of error handling,
a blank value was used to represent both null values from databases and error values.
Error handling separates these two interpretations of blank which could change the
behavior of existing apps that continue to use IsBlank.
Error
Use the Error function to create and report a custom error. For example, you might have
logic to determine whether any given value is valid for your context or not—something
not checked for a problem automatically. You can create and return your own error,
complete with Kind and Message, using the same record described above for the IfError
function.
In the context of IfError, use the Error function to rethrow or pass through an error. For
example, your logic in IfError may decide that in some cases an error can be safely
ignored, but in other cases the error is important to send through. Within IfError or
App.OnError, use Error( FirstError ) to pass through an error.
The Error function can also be passed a table of errors, as would be found in the
AllErrors table. Use Error( AllErrors ) to rethrow all the errors and not just the first.
A blank record or empty table passed to Error results in no error.
Syntax
Error( ErrorRecord )
Error( ErrorTable )
IsError( Value )
IsBlankOrError( Value )
Examples
Simple IfError
IfError( 1, The first argument isn't an error. The function has no other errors to check 1
2) and no default return value. The function returns the last value argument
evaluated.
IfError( The first argument returns an error value (because of division by zero). The 2
1/0, 2 ) function evaluates the second argument and returns it as the result.
IfError( The first argument isn't an error. The function has no other errors to check 30
10, 20, 30 but does have a default return value. The function returns the DefaultResult
) argument.
Formula Description Result
IfError( The first argument 10 isn't an error, so the function doesn't evaluate that 300
10, 11, 20, argument's corresponding replacement 11. The third argument 20 isn't an
21, 300 ) error either, so the function doesn't evaluate that argument's corresponding
replacement 21. The fifth argument 300 has no corresponding replacement
and is the default result. The function returns that result because the
formula contains no errors.
IfError( The first argument returns an error value (due to division by zero). The 1
1/0, function evaluates the second argument and displays a message to the user.
Notify( The return value of IfError is the return value of Notify, coerced to the same
"There type as the first argument to IfError (a number).
was an
internal
problem"
))
Simple IsError
If( IsError( The argument to IsError returns an error value (because of division by true
1/0 ), Notify( zero). This function returns true, which causes the If to display a
"There was message to the user with the Notify function. The return value of If is
an internal the return value of Notify, coerced to the same type as the first
problem" ) ) argument to If (a boolean).
Simple IsBlankOrError
Simple Error
In this example, dates are validated relative to one another, resulting in an error if there
is a problem.
Power Apps
In this example, some errors are allowed to pass through while others are supressed and
replaced with a value. In the first case, b will be in an error state because the Value
function has an invalid argument. Because this is unexpcted by the formula writer, it is
passed through so the user will see it. In the second case, with the same formula, b will
have the value 0, resulting in a division by zero. In this case, the formula writer may
know that this is acceptable for this logic, suppress the error (no banner is shown), and
return -1 instead.
Power Apps
With( {a: 1, b: 0} )
// returns -1
The AllErrors table can be filtered like any other table. Used with the Error function,
expected errors can be removed and the remaining errors retained and reported. For
example, if we knew that division by zero was not going to be a problem in a particular
context, those errors could be filtered out, leaving all other errors intact with the
following formula:
Power Apps
Step by step
1. Add a Text input control, and name it TextInput1 if it doesn't have that name by
default.
2. Add a Label control, and name it Label1 if it doesn't have that name by default.
Power Apps
Label1 will show the value 1234 as this is a valid input to the Value function.
Label1 will show the value -1 as this isn't a valid input to the Value function.
Without wrapping the Value function with IfError, the label would show no value as
the error value is treated as a blank.
See also
Formula reference for Power Apps
Blank, Coalesce, IsBlank, and IsEmpty
functions in Power Apps
Article • 02/23/2023 • 8 minutes to read
Tests whether a value is blank or a table contains no records, and provides a way to
create blank values.
Overview
Blank is a placeholder for "no value" or "unknown value." For example, a Combo box
control's Selected property is blank if the user hasn't made a selection. Many data
sources can store and return NULL values, which are represented in Power Apps as
blank.
Any property or calculated value in Power Apps can be blank. For example, a Boolean
value normally has one of two values: true or false. But in addition to these two, it can
also be blank indicating that the state is not known. This is similar to Microsoft Excel,
where a worksheet cell starts out as blank with no contents but can hold the values
TRUE or FALSE (among others). At any time, the contents of the cell can again be
cleared, returning it to a blank state.
Empty string refers to a string that contains no characters. The Len function returns zero
for such a string and it can be written in a formulas as two double quotes with nothing
in between "" . Some controls and data sources use an empty string to indicate a "no
value" condition. To simplify app creation, the IsBlank and Coalesce functions test for
both blank values or empty strings.
In the context of the IsEmpty function, empty is specific to tables that contain no
records. The table structure may be intact, complete with column names, but no data is
in the table. A table may start as empty, take on records and no longer be empty, and
then have the records removed and again be empty.
7 Note
We are in a period of transition. Until now, blank has also been used to report
errors, making it impossible to differentiate a valid "no value" from an error. For this
reason, at this time, storing blank values is supported only for local collections. You
can store blank values in other data sources if you turn on the Formula-level error
management experimental feature under Settings > Upcoming features >
Experimental. We are actively working to finish this feature and complete the
proper separation of blank values from errors.
Blank
The Blank function returns a blank value. Use this to store a NULL value in a data source
that supports these values, effectively removing any value from the field.
IsBlank
The IsBlank function tests for a blank value or an empty string. The test includes empty
strings to ease app creation since some data sources and controls use an empty string
when there is no value present. To test specifically for a blank value use if( Value =
Blank(), ... instead of IsBlank. The IsBlank function considers empty tables as not
When enabling error handling for existing apps, consider replacing IsBlank with
IsBlankOrError to preserve existing app behavior. Prior to the addition of error handling,
a blank value was used to represent both null values from databases and error values.
Error handling separates these two interpretations of blank which could change the
behavior of existing apps that continue to use IsBlank.
Coalesce
The Coalesce function evaluates its arguments in order and returns the first value that
isn't blank or an empty string. Use this function to replace a blank value or empty string
with a different value but leave non-blank and non-empty string values unchanged. If all
the arguments are blank or empty strings then the function returns blank, making
Coalesce a good way to convert empty strings to blank values.
Coalesce( value1, value2 ) is the more concise equivalent of If( Not IsBlank( value1
), value1, Not IsBlank( value2 ), value2 ) and doesn't require value1 and value2 to
be evaluated twice. The If function returns blank if there is no "else" formula as is the
case here.
All arguments to Coalesce must be of the same type; for example, you can't mix
numbers with text strings. The return value from Coalesce is of this common type.
IsEmpty
The IsEmpty function tests whether a table contains any records. It's equivalent to using
the CountRows function and checking for zero. You can check for data-source errors by
combining IsEmpty with the Errors function.
Syntax
Blank()
Value(s) – Required. Values to test. Each value is evaluated in order until a value
that is not blank and not an empty string is found. Values after this point are not
evaluated.
IsBlank( Value )
IsEmpty( Table )
Examples
Blank
7 Note
At this time, the following example only works for local collections. You can store
blank values in other data sources if you turn on the Formula-level error
management experimental feature under Settings > Upcoming features >
Experimental. We are actively working to finish this feature and complete the
separation of blank values from errors.
3. Preview your app, click or tap the button that you added, and then close Preview.
The Cities collection appears, showing one record with "Seattle" and "Rainy":
6. Add a Label control, and set its Text property to this formula:
Power Apps
The label shows false because the Weather field contains a value ("Rainy").
7. Add a second button, and set its OnSelect property to this formula:
Power Apps
8. Preview your app, click or tap the button that you added, and then close Preview.
The Weather field of the first record in Cities is replaced with a blank, removing
the "Rainy" that was there previously.
The label shows true because the Weather field no longer contains a value.
Coalesce
Coalesce( Blank(), 1 ) Tests the return value from the Blank function, which always 1
returns a blank value. Because the first argument is blank,
evaluation continues with the next argument until a non-blank
value and non-empty string is found.
Coalesce( "", "2" ) Tests the first argument which is an empty string. Because the 2
first argument is an empty string, evaluation continues with the
next argument until a non-blank value and non-empty string is
found.
Coalesce( Blank(), Coalesce starts at the beginning of the argument list and 3
"", Blank(), "", "3", evaluates each argument in turn until a non-blank value and
"4" ) non-empty string is found. In this case, the first four arguments
all return blank or an empty string, so evaluation continues to
the fifth argument. The fifth argument is non-blank and non-
empty string, so evaluation stops here. The value of the fifth
argument is returned, and the sixth argument isn't evaluated.
Coalesce( "" ) Tests the first argument which is an empty string. Because the blank
first argument is an empty string, and there are no more
arguments, the function returns blank.
IsBlank
1. Create an app from scratch, add a text-input control, and name it FirstName.
Power Apps
If( IsBlank( FirstName.Text ), "First Name is a required field." )
By default, the Text property of a text-input control is set to "Text input". Because
the property contains a value, it isn't blank, and the label doesn't display any
message.
3. Remove all the characters from the text-input control, including any spaces.
Because the Text property no longer contains any characters, it's an empty string,
and IsBlank( FirstName.Text ) will be true. The required field message is displayed.
For information about how to perform validation by using other tools, see the Validate
function and working with data sources.
Other examples:
IsBlank( Blank() ) Tests the return value from the Blank function, which always returns true
a blank value.
IsBlank( Because the collection exists, it isn't blank, even if it doesn't contain false
AnyCollection ) any records. To check for an empty collection, use IsEmpty instead.
IsBlank( Mid( The starting character for Mid is beyond the end of the string. The true
"Hello", 17, 2 ) ) result is an empty string.
IsBlank( If( false, An If function with no ElseResult. Because the condition is always true
false ) ) false, this If always returns blank.
IsEmpty
1. Create an app from scratch, and add a Button control.
3. Preview your app, click or tap the button that you added, and then close Preview.
4. Add a second button, and set its OnSelect property to this formula:
Clear( IceCream )
5. Preview your app, click or tap the second button, and then close Preview.
The Clear function removes all the records from a collection, resulting in an empty
collection. IsEmpty( IceCream ) returns true, and CountRows( IceCream ) returns
0.
You can also use IsEmpty to test whether a calculated table is empty, as these examples
show:
IsEmpty( [ 1, 2, 3 ] The single-column table contains three records and, therefore, isn't false
) empty.
IsEmpty( [ ] ) The single-column table contains no records and is empty. true
IsEmpty( Filter( The single-column table contains no values that are greater than 5. true
[ 1, 2, 3 ], Value > The result from the filter doesn't contain any records and is empty.
5))
Error, IfError, IsError, IsBlankOrError
functions in Power Apps
Article • 02/23/2023 • 9 minutes to read
Detects errors and provides an alternative value or takes action. Create a custom error
or pass through an error.
7 Note
The behavior that this article describes is available only when the Formula-
level error management preview feature in Settings > Upcoming features >
Preview is turned on.
IfError
The IfError function tests values until it finds an error. If the function discovers an error,
the function evaluates and returns a corresponding replacement value and stops further
evaluation. A default value can also be supplied for when no errors are found. The
structure of IfError resembles that of the If function: IfError tests for errors, while If tests
for true.
Use IfError to replace an error with a valid value so that downstream calculations can
continue. For example, use this function if user input might result in a division by zero:
Power Apps
IfError( 1/x, 0 )
This formula returns 0 if the value of x is zero, as 1/x will produce an error. If x isn't
zero, then 1/x is returned.
Power Apps
The second Patch function to DS2 will be attempted even if the Patch to DS1 fails. The
scope of an error is limited to each formula that is chained.
Use IfError to do an action and only continue processing if the action was successful.
Applying IfError to this example:
Power Apps
IfError(
If the Patch of DS1 has a problem, the first Notify is executed. No further processing
occurs including the second Patch of DS2 . If the first Patch succeeds, the second Patch
will execute.
Building on the last example, the return value from IfError can be checked to determine
if there were any problems:
Power Apps
IfError(
true
Type compatibility
IfError will return the value of one of its arguments. The types of all values that might be
returned by IfError must be compatible.
In the last example, Patch will return a record that isn't compatible with the Booleans
used for the Replacement formulas or the DefaultResult. Which is fine, since there's no
situation in which the return value from these Patch calls would be returned by IfError.
7 Note
While the behavior in process for a change, the types of all arguments to IfError
must be compatible currently.
Power Apps
IfError( 1/x, 0 )
The types of 1/x and 0 were compatible as both were numbers. If they're not, the
second argument will be coerced to match the type of the first argument.
Power Apps
The above formula won't work. The text string "#DIV/0!" will be coerced to the type of
the first argument to IfError, which is a number. The result of IfError will be yet another
error since the text string can't be coerced. As a fix, convert the first argument to a text
string so that IfError always returns a text string:
Power Apps
As seen above, IfError can return an error if the Replacement or DefaultResult is an error.
FirstError / AllErrors
Within in the replacement formulas, information about the errors found is available
through the FirstError record and AllErrors table. AllErrors is a table of error information
records with FirstError being a shortcut to the first record of this table. FirstError will
always return the same value as First( AllErrors ).
Message Text Message about the error, suitable to be displayed to the end user.
string
Source Text Location in where the error originated, used for reporting. For example,
string for a formula bound to a control property, this will be in the form
ControlName.PropertyName.
Observed Text Location in where the error is surfaced to the user, used for reporting. For
string example, for a formula bound to a control property, this will be in the
form ControlName.PropertyName.
Details Record Details about the error. At present, details are provided only for network
errors. This record includes HttpStatusCode whcih contains the HTTP
status code and HttpResponse which contains the body of the response
from the connector or service.
For example, consider the following formula as a Button control's OnSelect property:
Power Apps
Set( a, 1/0 )
Power Apps
The example formula above would display the following banner when the two buttons
are activated in sequence:
Typically, there'll be only one error that FirstError can sufficiently work with. However,
there are scenarios where multiple errors may be returned. For example, when using a
formula chaining operator or the Concurrent function. Even in these situations,
reporting FirstError might be enough to reveal a problem instead overloading a user
with multiple errors. If you still have a requirement to work with each error individually,
you can use the AllErrors table.
IsError
The IsError function tests for an error value.
IsBlankOrError
The IsBlankOrError function tests for either a blank value or an error value and is the
equivalent of Or( IsBlank( X ), IsError( X ) ) .
When enabling error handling for existing apps, consider replacing IsBlank with
IsBlankOrError to preserve existing app behavior. Prior to the addition of error handling,
a blank value was used to represent both null values from databases and error values.
Error handling separates these two interpretations of blank which could change the
behavior of existing apps that continue to use IsBlank.
Error
Use the Error function to create and report a custom error. For example, you might have
logic to determine whether any given value is valid for your context or not—something
not checked for a problem automatically. You can create and return your own error,
complete with Kind and Message, using the same record described above for the IfError
function.
In the context of IfError, use the Error function to rethrow or pass through an error. For
example, your logic in IfError may decide that in some cases an error can be safely
ignored, but in other cases the error is important to send through. Within IfError or
App.OnError, use Error( FirstError ) to pass through an error.
The Error function can also be passed a table of errors, as would be found in the
AllErrors table. Use Error( AllErrors ) to rethrow all the errors and not just the first.
A blank record or empty table passed to Error results in no error.
Syntax
Error( ErrorRecord )
Error( ErrorTable )
IsError( Value )
IsBlankOrError( Value )
Examples
Simple IfError
IfError( 1, The first argument isn't an error. The function has no other errors to check 1
2) and no default return value. The function returns the last value argument
evaluated.
IfError( The first argument returns an error value (because of division by zero). The 2
1/0, 2 ) function evaluates the second argument and returns it as the result.
IfError( The first argument isn't an error. The function has no other errors to check 30
10, 20, 30 but does have a default return value. The function returns the DefaultResult
) argument.
Formula Description Result
IfError( The first argument 10 isn't an error, so the function doesn't evaluate that 300
10, 11, 20, argument's corresponding replacement 11. The third argument 20 isn't an
21, 300 ) error either, so the function doesn't evaluate that argument's corresponding
replacement 21. The fifth argument 300 has no corresponding replacement
and is the default result. The function returns that result because the
formula contains no errors.
IfError( The first argument returns an error value (due to division by zero). The 1
1/0, function evaluates the second argument and displays a message to the user.
Notify( The return value of IfError is the return value of Notify, coerced to the same
"There type as the first argument to IfError (a number).
was an
internal
problem"
))
Simple IsError
If( IsError( The argument to IsError returns an error value (because of division by true
1/0 ), Notify( zero). This function returns true, which causes the If to display a
"There was message to the user with the Notify function. The return value of If is
an internal the return value of Notify, coerced to the same type as the first
problem" ) ) argument to If (a boolean).
Simple IsBlankOrError
Simple Error
In this example, dates are validated relative to one another, resulting in an error if there
is a problem.
Power Apps
In this example, some errors are allowed to pass through while others are supressed and
replaced with a value. In the first case, b will be in an error state because the Value
function has an invalid argument. Because this is unexpcted by the formula writer, it is
passed through so the user will see it. In the second case, with the same formula, b will
have the value 0, resulting in a division by zero. In this case, the formula writer may
know that this is acceptable for this logic, suppress the error (no banner is shown), and
return -1 instead.
Power Apps
With( {a: 1, b: 0} )
// returns -1
The AllErrors table can be filtered like any other table. Used with the Error function,
expected errors can be removed and the remaining errors retained and reported. For
example, if we knew that division by zero was not going to be a problem in a particular
context, those errors could be filtered out, leaving all other errors intact with the
following formula:
Power Apps
Step by step
1. Add a Text input control, and name it TextInput1 if it doesn't have that name by
default.
2. Add a Label control, and name it Label1 if it doesn't have that name by default.
Power Apps
Label1 will show the value 1234 as this is a valid input to the Value function.
Label1 will show the value -1 as this isn't a valid input to the Value function.
Without wrapping the Value function with IfError, the label would show no value as
the error value is treated as a blank.
See also
Formula reference for Power Apps
IsMatch, Match, and MatchAll functions
in Power Apps
Article • 03/08/2023 • 12 minutes to read
Description
The IsMatch function tests whether a text string matches a pattern that can comprise
ordinary characters, predefined patterns, or a regular expression. The Match and
MatchAll functions return what was matched, including sub-matches.
Use IsMatch to validate what a user has typed in a Text input control. For example, you
can confirm whether the user has entered a valid email address before the result is
saved to your data source. If the entry doesn't match your criteria, add other controls
that prompt the user to correct the entry.
Use Match to extract the first text string that matches a pattern and MatchAll to extract
all text strings that match. You can also extract sub-matches to parse complex strings.
Match returns a record of information for the first match found, and MatchAll returns a
table of records for every match found. The record or records contain:
named Text Each named sub-match will have its own column. Create a named sub-
sub‑match match by using (?<name>...) in the regular expression. If a named sub-
or match has the same name as one of the predefined columns (below),
sub‑matches the sub-match takes precedence, and a warning is generated. To avoid
this warning, rename the sub-match.
StartMatch Number The starting position of the match within the input text string. The first
character of the string returns 1.
SubMatches Single- The table of named and unnamed sub-matches in the order in which
column they appear in the regular expression. Generally, named sub-matches
table of are easier to work with and are encouraged. Use the ForAll function or
Text Last( FirstN( ... ) ) functions to work with an individual sub-match. If no
(column sub-matches are defined in the regular expression, this table will be
Value) present but empty.
IsMatch returns true if the text string matches the pattern or false if it doesn't. Match
returns blank if no match is found that can be tested with the IsBlank function. MatchAll
returns an empty table if no match is found that can be tested with the IsEmpty
function.
If you're using MatchAll to split a text string, consider using the Split function, which is
simpler to use and faster.
Patterns
The key to using these functions is in describing the pattern to match. You describe the
pattern in a text string as a combination of:
Combine these elements by using the string-concatenation operator &. For example,
"abc" & Digit & "\s+" is a valid pattern that matches the characters "a", "b", and "c",
followed by a digit from 0 to 9, followed by at least one whitespace character.
Ordinary characters
The simplest pattern is a sequence of ordinary characters to be matched exactly.
For example, when used with the IsMatch function, the string "Hello" matches the
pattern "Hello" exactly. No more and no less. The string "hello!" doesn't match the
pattern because of the exclamation point on the end and because the case is wrong for
the letter "h". (See MatchOptions for ways to modify this behavior.)
In the pattern language, certain characters are reserved for special purposes. To use
these characters, either prefix the character with a \ (backslash) to indicate that the
character should be taken literally, or use one of the predefined patterns described later
in this topic. This table lists the special characters:
Special character Description
. dot or period
? question mark
* asterisk
+ plus
() parentheses
[] square brackets
{} curly braces
^ caret
$ dollar sign
\ backslash
For example, you can match "Hello?" by using the pattern "Hello\?" with a backslash
before the question mark.
Predefined patterns
Predefined patterns provide a simple way to match either one of a set of characters or a
sequence of multiple characters. Use the string-concatenation operator & to combine
your own text strings with members of the Match enum:
Email Matches an email address that contains an "at" symbol ("@") .+\@.+\\.
and a domain name that contains a dot (".") [^\\.]{2,}
MultipleNonSpaces Matches one or more characters that don't add whitespace \S+
(not space, tab, or newline).
MultipleSpaces Matches one or more characters that add whitespace (space, \s+
tab, or newline).
OptionalNonSpaces Matches zero, one, or more characters that don't add \S*
whitespace.
OptionalSpaces Matches zero, one, or more characters that add whitespace. \s*
For example, the pattern "A" & MultipleDigits will match the letter "A" followed by one
or more digits.
Regular expressions
The pattern that these functions use is a regular expression . The ordinary characters
and predefined patterns that are described earlier in this topic help build regular
expressions.
Regular expressions are very powerful, available in many programming languages, and
used for a wide variety of purposes. They can also often look like a random sequence of
punctuation marks. This article doesn't describe all aspects of regular expressions, but a
wealth of information, tutorials, and tools are available on the web.
Regular expressions come in different dialects, and Power Apps uses a variant of the
JavaScript dialect. See regular-expression syntax for an introduction to the syntax.
Named sub-matches (sometimes called named capture groups) are supported:
In the Match enum table earlier in this topic, each enum appears in the same row as its
corresponding regular expression.
Match options
You can modify the behavior of these functions by specifying one or more options,
which you can combine by using the string- concatenation operator (&).
MatchOptions.BeginsWith The pattern must match from Adds a ^ to the start of the
the beginning of the text. regular expression.
MatchOptions.Complete Default for IsMatch. The pattern Adds a ^ to the start and a $ to
must match the entire string of the end of the regular
text, from beginning to end. expression.
MatchOptions.EndsWith The pattern must match the end Adds a $ to the end of the
of the string of text. regular expression.
Using MatchAll is equivalent to using the standard "g" modifier for regular expressions.
Syntax
IsMatch( Text, Pattern [, Options ] )
IsMatch examples
Ordinary characters
Imagine that your app contains a Text input control named TextInput1. The user enters
values into this control to be stored in a database.
IsMatch( TextInput1.Text, "Hello Tests whether the user's input matches, true
world" ) exactly, the string "Hello world".
IsMatch( TextInput1.Text, "Good bye" Tests whether the user's input matches, false
) exactly, the string "Good bye".
IsMatch( TextInput1.Text, "hello", Tests whether the user's input contains the false
Contains ) word "hello" (case sensitive).
IsMatch( TextInput1.Text, "hello", Tests whether the user's input contains the true
Contains & IgnoreCase ) word "hello" (case insensitive).
Predefined patterns
IsMatch( "123-45-7890", Digit & Matches a United States Social Security true
Digit & Digit & Hyphen & Digit & Number
Digit & Hyphen & Digit & Digit &
Digit & Digit )
IsMatch( "123.456", MultipleDigits & Matches a sequence of digits, a period, and true
Period & OptionalDigits ) then zero or more digits.
IsMatch( "123", MultipleDigits & Matches a sequence of digits, a period, and false
Period & OptionalDigits ) then zero or more digits. A period doesn't
appear in the text to match, so this pattern
isn't matched.
Regular expressions
IsMatch( "1.02", Matches a positive currency amount. If the input contains a true
"\d+(\.\d\d)?" ) decimal point, the input must also contain two numeric
characters after the decimal point. For example, 3.00 is valid,
but 3.1 isn't.
Formula Description Result
IsMatch( "-4.95", " Matches a positive or negative currency amount. If the input true
(-)?\d+(\.\d\d)?" ) contains a decimal point, the input must also contain two
numeric characters after the decimal point.
IsMatch( "111-11- Matches a United States Social Security number. Validates the true
1111", "\d{3}-\d{2}- format, type, and length of the supplied input field. The string
\d{4}" ) to match must consist of three numeric characters followed by
a dash, then two numeric characters followed by a dash, and
then four numeric characters.
IsMatch( "111-111- Same as the previous example, but one of the hyphens is out of false
111", "\d{3}-\d{2}- place in the input.
\d{4}" )
IsMatch( Validates a strong password, which must contain eight, nine, or false
"AStrongPasswordNot", 10 characters, in addition to at least one digit and at least one
"(?!^[0-9]\*$)(?!^[a- alphabetic character. The string must not contain special
zA-Z]\*$)([a-zA-Z0-9] characters.
{8,10})" )
StartMatch: 11
convert it to a number }
before mathematical
operations are
performed on it.
Let's drill into that last example. If you wanted to convert this string to a date/time value
using the Time function, you must pass in the named sub-matches individually. To do
this, you can use the With function operating on the record that Match returns:
Power Apps
With(
For these examples, add a Button control, set its OnSelect property to this formula, and
then select the button:
Power Apps
Set( pangram, "The quick brown fox jumps over the lazy dog." )
StartMatch: 17
The gallery is filled with each word in our example text. Resize the gallery's
template and the label control in order to see all the words on one screen.
IsNumeric function in Power Apps
Article • 02/23/2023 • 2 minutes to read
Description
The IsNumeric function tests whether a value is numeric. Other kinds of values include
Boolean, string, table, and record.
Syntax
IsNumeric( Value )
Description
Use the WeekNum and ISOWeekNum functions to determine the week number of a date.
These functions differ in how they determine the first week of the year (week 1):
WeekNum uses the week containing January 1 as the first week of the year. The result
from this function can range from 1 to 54.
ISOWeekNum uses the week containing the first Thursday of the year as the first week
of the year. This follows the ISO 8601 date and time standard definition for week
numbering. The result from this function can range from 1 to 53. It is possible that 52
or 53 may be returned for the first days of January since the dates could belong to the
last week of the previous year.
Use the second parameter to WeekNum to specify which day begins a week. You can
provide either an Excel code number or use the StartOfWeek enumeration:
ISOWeekNum always uses Monday as the start of the week. In Excel, the WeekNum
function supports an addition code 21 that is not supported here; use ISOWeekNum
instead.
If you pass a single number to these functions, the return value is a single result. If you pass
a single-column table that contains numbers, the return value is a single-column table of
results, one result for each record in the argument's table. If you have a multi-column table,
you can shape it into a single-column table, as working with tables describes.
Syntax
WeekNum(DateTime [, StartOfWeek ])
ISOWeekNum(DateTime)
DateTime - Required. Date/Time value to operate on. The week always begins on
Monday.
Examples
First and last calendar weeks of 2021
Friday, January 1, 2021 1 53 1
Saturday, January 2, 2021 1 53 1
Sunday, January 3, 2021 2 53 1
Monday, January 4, 2021 2 1 1
Tuesday, January 5, 2021 2 1 1
Wednesday, January 6, 2021 2 1 2
Thursday, January 7, 2021 2 1 2
Saturday, December 25, 2021 52 51 52
Sunday, December 26, 2021 53 51 52
Monday, December 27, 2021 53 52 52
Tuesday, December 28, 2021 53 52 52
Wednesday, December 29, 2021 53 52 53
Thursday, December 30, 2021 53 52 53
Friday, December 31, 2021 53 52 53
Now, Today, IsToday, UTCNow,
UTCToday, IsUTCToday functions in
Power Apps
Article • 02/23/2023 • 4 minutes to read
Returns the current date and time, and tests whether a date/time value is today.
Description
The Now function returns the current date and time as a date/time value.
The Today function returns the current date as a date/time value. The time portion is
midnight. Today has the same value throughout a day, from midnight today to midnight
tomorrow.
The IsToday function tests whether a date/time value is between midnight today and
midnight tomorrow. This function returns a Boolean (true or false) value.
Now, Today, and IsToday functions work with the local time of the current user.
UTCNow, UTCToday, and IsUTCToday functions are the same as their non-UTC
countrparts but work with time zone independent values and use Coordinated Universal
Time (UTC).
7 Note
More information: Work with formula table columns in Dataverse for Teams
See Date, Time, and DateTime in the data types documentation and working with dates
and times for more information.
Volatile Functions
Now, Today, UTCNow, and UTCToday are volatile functions. These functions return a
different value for each evaluation.
When used in a data flow formula, a volatile function will only return a different value if
the formula in which it appears is reevaluated. If nothing else changes in the formula
then it will have the same value throughout the execution of your app.
For example, a label control with Label1.Text = Now() will not change while your app is
active. Only closing and reopening the app will result in a new value.
The function will be reevaluated if it is part of a formula in which something else has
changed. For example, if we change our example to involve a slider control with
Label1.Text = DateAdd( Now(), Slider1.Value, Minutes ) then the current time is
retrieved each time the Slider control's value changes and the label's text property is
reevaluated.
When used in a behavior formula, volatile functions will be evaluated each time the
behavior formula is evaluated. See below for an example.
Syntax
Now()
Today()
IsToday( DateTime )
UTCNow()
UTCToday()
IsUTCToday( TimeZoneIndependentTime )
Text( Now(), Retrieves the current date and time in the user's time "07/11/2021
"mm/dd/yyyy hh:mm:ss" ) zone, and displays it as a string. 20:58:00"
Text( Today(), Retrieves the current date only, leaving the time "07/12/2021
"mm/dd/yyyy hh:mm:ss" ) portion as midnight, and displays it as a string. 00:00:00"
IsToday( Now() ) Tests whether the current date and time is between true
midnight today and midnight tomorrow.
IsToday( Today() ) Tests whether the current date is between midnight true
today and midnight tomorrow.
Text( DateAdd( Now(), 12 Retrieves the current date and time, adds 12 days to "07/23/2021
), "mm/dd/yyyy the result, and displays it as a string. 20:58:00"
hh:mm:ss" )
Text( DateAdd( Today(), 12 Retrieves the current date, adds 12 days to the result, "07/23/2021
), "mm/dd/yyyy and displays it as a string. 00:00:00"
hh:mm:ss" )
IsToday( DateAdd( Now(), Tests whether the current date and time, plus 12 false
12 ) ) days, is between midnight today and midnight
tomorrow.
IsToday( DateAdd( Tests whether the current date, plus 12 days, is false
Today(), 12 ) ) between midnight today and midnight tomorrow.
Hour( UTCNow() ) Retrieves the current date and time in UTC and 4
extracts the hour only, which is 8 hours ahead of
local time.
Day( UTCToday() ) Retrives the current date only in UTC and extracts the 12
day, which is 1 day ahead of local time.
IsUTCToday( UTCNow() ) Tests whether the current date and time is between true
midnight today and midnight tomorrow, all in UTC
time.
IsUTCToday( UTCToday() ) Tests whether the current date is between midnight true
today and midnight tomorrow, all in UTC time.
The timer will run for one second, automatically start over, and continue that
pattern.
Whenever the timer starts over (after each second), this formula sets the
CurrentTime global variable to the current value of the Now function.
3. Add a Label control, and set its Text property to this formula:
Use the Text function to format the date and time however you want, or set this
property to just CurrentTime to show hours and minutes but not seconds.
4. Preview the app by pressing F5, and then start the timer by clicking or tapping it.
The label continually shows the current time, down to the second.
5. Set the timer's AutoStart property to true and its Visible property to false.
6. Set the screen's OnStart property so that the CurrentTime variable has a valid
value, as in this example:
Set(CurrentTime, Now())
The label appears as soon as the app starts (before the timer runs for a full
second).
AsType and IsType functions in Power
Apps
Article • 02/23/2023 • 4 minutes to read
Checks a record reference for a specific table type (IsType) and treats the reference as a
specific type (AsType).
Description
Read Understand record references and polymorphic lookups for a broader introduction
and more details.
A lookup field usually refers to records in a particular table. Because the table type is
well established, you can access the fields of the lookup by using a simple dot notation.
For example, First( Accounts ).'Primary Contact'.'Full Name' walks from the Accounts
table to the Primary Contact record in the Contacts table and extracts the Full Name
field.
Microsoft Dataverse also supports polymorphic lookup fields, which can refer to records
from a set of tables, as in these examples.
The IsType function tests whether a record reference refers to a specific table type. The
function returns a Boolean TRUE or FALSE.
The AsType function treats a record reference as a specific table type, sometimes
referred to as casting. You can use the result as if it were a record of the table and again
use the Record.Field notation to access all of the fields of that record. An error occurs if
the reference isn't of the specific type.
Use these functions together to first test the table type of a record and then treat it as a
record of that type so that the fields are available:
Power Apps
You need these functions only if you're accessing the fields of a record reference. For
example, you can use record references in the Filter function without IsType or AsType:
Power Apps
Similarly, you can use record references with the Patch function:
Power Apps
If used in a record context, such as within a Gallery or Edit form control, you might need
to use the global disambiguation operator to reference the table type. For example, this
formula would be effective for a gallery that's displaying a list of contacts where
Company Name is a Customer lookup:
Power Apps
For both functions, you specify the type through the name of the data source that's
connected to the table. For the formula to work, you must also add a data source to the
app for any types that you want to test or cast. For example, you must add the Users
table as a data source if you want to use IsType and AsType with an Owner lookup and
records from that table. You can add only the data sources that you actually use in your
app; you don't need to add all the tables that a lookup could reference.
If the record reference is blank, IsType returns FALSE, and AsType returns blank. All fields
of a blank record will be blank.
Syntax
AsType( RecordReference, TableType )
RecordReference - Required. A record reference, often a lookup field that can refer
to a record in any of multiple tables.
TableType - Required. The specific table to which the record should be cast.
RecordReference - Required. A record reference, often a lookup field that can refer
to a record in any of multiple tables.
TableType - Required. The specific table for which to test.
Example
Understand record references and polymorphic lookups contains extensive examples.
2. On the left-pane, select Data > Add data. And then, add Accounts and Contacts
tables.
3. On the left-pane, select + (Insert) > Layout > Blank vertical gallery.
4. Select Connect to data, and then select Contacts as the data source.
Power Apps
If( IsBlank( ThisItem.'Company Name' ), "--",
Your results might differ from those in this topic because it uses sample data that
was modified to show additional types of results.
Now, Today, IsToday, UTCNow,
UTCToday, IsUTCToday functions in
Power Apps
Article • 02/23/2023 • 4 minutes to read
Returns the current date and time, and tests whether a date/time value is today.
Description
The Now function returns the current date and time as a date/time value.
The Today function returns the current date as a date/time value. The time portion is
midnight. Today has the same value throughout a day, from midnight today to midnight
tomorrow.
The IsToday function tests whether a date/time value is between midnight today and
midnight tomorrow. This function returns a Boolean (true or false) value.
Now, Today, and IsToday functions work with the local time of the current user.
UTCNow, UTCToday, and IsUTCToday functions are the same as their non-UTC
countrparts but work with time zone independent values and use Coordinated Universal
Time (UTC).
7 Note
More information: Work with formula table columns in Dataverse for Teams
See Date, Time, and DateTime in the data types documentation and working with dates
and times for more information.
Volatile Functions
Now, Today, UTCNow, and UTCToday are volatile functions. These functions return a
different value for each evaluation.
When used in a data flow formula, a volatile function will only return a different value if
the formula in which it appears is reevaluated. If nothing else changes in the formula
then it will have the same value throughout the execution of your app.
For example, a label control with Label1.Text = Now() will not change while your app is
active. Only closing and reopening the app will result in a new value.
The function will be reevaluated if it is part of a formula in which something else has
changed. For example, if we change our example to involve a slider control with
Label1.Text = DateAdd( Now(), Slider1.Value, Minutes ) then the current time is
retrieved each time the Slider control's value changes and the label's text property is
reevaluated.
When used in a behavior formula, volatile functions will be evaluated each time the
behavior formula is evaluated. See below for an example.
Syntax
Now()
Today()
IsToday( DateTime )
UTCNow()
UTCToday()
IsUTCToday( TimeZoneIndependentTime )
Text( Now(), Retrieves the current date and time in the user's time "07/11/2021
"mm/dd/yyyy hh:mm:ss" ) zone, and displays it as a string. 20:58:00"
Text( Today(), Retrieves the current date only, leaving the time "07/12/2021
"mm/dd/yyyy hh:mm:ss" ) portion as midnight, and displays it as a string. 00:00:00"
IsToday( Now() ) Tests whether the current date and time is between true
midnight today and midnight tomorrow.
IsToday( Today() ) Tests whether the current date is between midnight true
today and midnight tomorrow.
Text( DateAdd( Now(), 12 Retrieves the current date and time, adds 12 days to "07/23/2021
), "mm/dd/yyyy the result, and displays it as a string. 20:58:00"
hh:mm:ss" )
Text( DateAdd( Today(), 12 Retrieves the current date, adds 12 days to the result, "07/23/2021
), "mm/dd/yyyy and displays it as a string. 00:00:00"
hh:mm:ss" )
IsToday( DateAdd( Now(), Tests whether the current date and time, plus 12 false
12 ) ) days, is between midnight today and midnight
tomorrow.
IsToday( DateAdd( Tests whether the current date, plus 12 days, is false
Today(), 12 ) ) between midnight today and midnight tomorrow.
Hour( UTCNow() ) Retrieves the current date and time in UTC and 4
extracts the hour only, which is 8 hours ahead of
local time.
Day( UTCToday() ) Retrives the current date only in UTC and extracts the 12
day, which is 1 day ahead of local time.
IsUTCToday( UTCNow() ) Tests whether the current date and time is between true
midnight today and midnight tomorrow, all in UTC
time.
IsUTCToday( UTCToday() ) Tests whether the current date is between midnight true
today and midnight tomorrow, all in UTC time.
The timer will run for one second, automatically start over, and continue that
pattern.
Whenever the timer starts over (after each second), this formula sets the
CurrentTime global variable to the current value of the Now function.
3. Add a Label control, and set its Text property to this formula:
Use the Text function to format the date and time however you want, or set this
property to just CurrentTime to show hours and minutes but not seconds.
4. Preview the app by pressing F5, and then start the timer by clicking or tapping it.
The label continually shows the current time, down to the second.
5. Set the timer's AutoStart property to true and its Visible property to false.
6. Set the screen's OnStart property so that the CurrentTime variable has a valid
value, as in this example:
Set(CurrentTime, Now())
The label appears as soon as the app starts (before the timer runs for a full
second).
JSON function in Power Apps
Article • 03/08/2023 • 6 minutes to read
Description
The JSON function returns the JavaScript Object Notation (JSON) representation of a
data structure as text so that it's suitable for storing or transmitting across a network.
ECMA-404 and IETF RFC 8259 describe the format, which is widely used by
JavaScript and other programming languages.
Canvas apps support the data types that this table lists with details about their text
representation:
Use the ShowColumns and DropColumns functions to control which data the result
includes and to remove unsupported data types.
Because JSON can be both memory and compute intensive, you can use this function
only in behavior functions. You can capture the result from JSON into a variable, which
you can then use in data flow.
If a column has both a display name and a logical name, the result contains the logical
name. Display names reflect the language of the app user and are, therefore,
inappropriate for data transfer to a common service.
Syntax
JSON( DataStructure [, Format ] )
Examples
Hierarchical data
1. Insert a Button control, and set its OnSelect property to this formula.
Power Apps
ClearCollect( CityPopulations,
);
The CitiesByCountry collection is created with this data structure, which you can
show by selecting Collections on the File menu and then selecting the name of the
collection.
You can also show this collection by selecting Settings > Upcoming features >
Enable formula bar result view, selecting the name of the collection in the formula
bar, and then selecting the down arrow next to the name of the collection under
the formula bar.
3. Insert another button, and set its OnSelect property to this formula:
Power Apps
5. Insert a Label control, and set its Text property to this variable.
Power Apps
CitiesByCountryJSON
The label shows this result, all on a single line with no spaces, suitable for
transmission across a network:
JSON
},
"Cities": [
],
"Country": "Germany"
},
"Cities": [
],
"Country": "Spain"
6. Change the second button's formula to make the output more readable.
Power Apps
7. Select the second button while holding down the Alt key.
JSON
[
"Cities": [
"City": "London",
"Population": 8615000
],
},
"Cities": [
"City": "Berlin",
"Population": 3562000
},
"City": "Hamburg",
"Population": 1760000
},
"City": "Munich",
"Population": 1494000
],
"Country": "Germany"
},
"Cities": [
"City": "Madrid",
"Population": 3165000
},
"City": "Barcelona",
"Population": 1602000
],
"Country": "Spain"
2. Add a Button control, and set its OnSelect property to this formula.
Power Apps
Set( ImageJSON, JSON( SampleImage, JSONFormat.IncludeBinaryData ) )
Power Apps
ImageJSON
5. Resize the control and reduce the font size as needed to show most of the result.
The label shows the text string that the JSON function captured.
JSON
"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRm
LTgiPz4NCjxzdmcgdmVyc2lvbj0iMS4xIg0KCSB4bWxucz0iaHR0cDovL3d3dy53My5vcmc
vMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIi
B4bWxuczphPSJodHRwOi8vbnMuYWRvYmUuY29tL0Fkb2JlU1ZHVmlld2VyRXh0ZW5zaW9uc
y8zLjAvIg0KCSB4PSIwcHgiIHk9IjBweCIgd2lkdGg9IjI3MHB4IiBoZWlnaHQ9IjI3MHB4
IiBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDAgMCAyNzAgMjcwIiB4bWw6c3BhY2U9InByZXN
lcnZlIj4NCgk8ZyBjbGFzcz0ic3QwIj4NCgkJPHJlY3QgeT0iMC43IiBmaWxsPSIjRTlFOU
U5IiB3aWR0aD0iMjY5IiBoZWlnaHQ9IjI2OS4zIi8+DQoJCTxwb2x5Z29uIGZpbGw9IiNDQ
kNCQ0EiIHBvaW50cz0iMjc3LjksMTg3LjEgMjQ1LDE0My40IDE4OC42LDIwMi44IDc1LDgw
LjUgLTQuMSwxNjUuMyAtNC4xLDI3MiAyNzcuOSwyNzIiLz4NCgkJPGVsbGlwc2UgZmlsbD0
iI0NCQ0JDQSIgY3g9IjIwMi40IiBjeT0iODQuMSIgcng9IjI0LjQiIHJ5PSIyNC4zIi8+DQ
oJPC9nPg0KPC9zdmc+"
Description
The Language function returns the language, script, and region of the current user as a
language tag.
Use the language information to tailor your app across locales. For example, if you are
creating an app that will be used in Italy and France, you can use Language to
automatically display Italian and French strings to your users in those different locations.
Language tags
A language tag can be in one of three formats:
Return Description
value
"lg‑RE" lg is the two character abbreviation for the language and RE is the two character
abbreviation for the region. This is the most common return type. For example,
"en-GB" is returned for Great Britain.
"lg" lg is the two character abbreviation for the language. This is the format used when
Power Apps has information about the language, but does not have information
for the specific region.
"lg‑scrp‑RE" lg is the two character abbreviation for the language, scrp is the four character
abbreviation for the script, and RE is the two character abbreviation for the region.
To see the list of supported language tags, type Value( "1", ) in the formula bar or
advanced view and scroll through the list of locales suggested for the second argument.
The Text and Value functions also use language tags. Use these functions for translating
to and from text strings in a globally aware manner. When passing a language tag to
these functions and the region would not make a difference, you can use just the
language portion of the tag.
Syntax
Language()
Examples
User's locale
It is assumed that the host operating system and/or browser are using the default locale
for the location.
Localization table
A simple approach to localization is to create an Excel spreadsheet mapping an author
defined TextID to a translated text for the user's language. Although you could use a
collection or any other data source for this table, we chose Excel because it is easy to
edit and manage outside of the app by translators.
For our purposes, we only need to look at the language of the locale and not the
region. If regional considerations were important, we could have included the full
language tag value in the table above.
2. Use the Insert ribbon, Table command, to make this into a proper Excel table. By
default, it will be named Table1 but you can name it whatever you like with the
Table Tools/Design ribbon and the Table Name: text box on the far left hand side.
4. In Power Apps, in the right-hand pane, click or tap the Data Sources tab, and then
click or tap Add data source.
5. Click or tap Add static data to your app, click or tap the Excel file that you saved,
and then click or tap Open.
6. Select the table that you created, and then click or tap Connect.
In your app, wherever you would have used the text "Hello" before, use this formula
instead:
This formula will lookup the appropriate LocalizedText value for the language of the
user, and if that is not found, will fall back on the default blank version.
Be aware that translated strings in other languages could be significantly longer than
they are in your language. In many cases, the labels and other elements that display the
strings in your user interface will need to be wider to accommodate.
Translation service
You can translate text on demand using a translation service, such as the Microsoft
Translator service:
1. In Power Apps, in the right-hand pane, click or tap the Data Sources tab, and then
click or tap Add data source.
2. Click or tap Microsoft Translator.
In your app, wherever you would have used the text "Hello" before, use this formula
instead:
The Microsoft Translator service uses the same language tags that the Language
function returns.
This approach comes with some drawbacks when compared to the previous example
which utilized a pre-translated table of text strings:
The translation will take time to complete, requiring a call to a service across the
network. This will result in a lag to see the translated text in your app.
The translation will be mechanical and may not be what you anticipate or be the
best choice for the situation within your app.
First, FirstN, Index, Last, and LastN
functions in Power Apps
Article • 02/23/2023 • 2 minutes to read
Returns the first, last, or a specific record, or a set of first or last records, from a table.
Description
The First function returns the first record of a table.
The FirstN function returns the first set of records of a table; the second argument
specifies the number of records to return.
The LastN function returns the last set of records of a table; the second argument
specifies the number of records to return.
The Index function returns a record of a table based on its ordered position in the table.
Record numbering begins with 1 so First( table ) returning the same record as
Index( table, 1 ) . Index returns an error if the requested record index is less than 1,
greater than the number of records in the table, or the table is empty.
First, Index, and Last return a single record. FirstN and LastN return a table, even if you
specify only a single record.
Delegation
When used with a data source, these functions can't be delegated. Only the first portion
of the data source will be retrieved and then the function applied. The result may not
represent the complete story. A warning may appear at authoring time to remind you of
this limitation and to suggest switching to delegable alternatives where possible. For
more information, see the delegation overview.
For example, when used with a data source containing a large table with 1 million
records, Last will be subject to the non-delegation limit and will not return the last
record of the entire data source. Likewise, using Index to request a record in the middle
of 1 million records will result in an error because the index is out of range based on the
non-delegation limit.
Syntax
First( Table )
Last( Table )
Examples
For the following examples, we'll use the IceCream data source, which contains the data
in this table:
This table can be placed in a collection with this formula (put in the OnStart formula for
a Button control and press the button):
Power Apps
Returns the first, last, or a specific record, or a set of first or last records, from a table.
Description
The First function returns the first record of a table.
The FirstN function returns the first set of records of a table; the second argument
specifies the number of records to return.
The LastN function returns the last set of records of a table; the second argument
specifies the number of records to return.
The Index function returns a record of a table based on its ordered position in the table.
Record numbering begins with 1 so First( table ) returning the same record as
Index( table, 1 ) . Index returns an error if the requested record index is less than 1,
greater than the number of records in the table, or the table is empty.
First, Index, and Last return a single record. FirstN and LastN return a table, even if you
specify only a single record.
Delegation
When used with a data source, these functions can't be delegated. Only the first portion
of the data source will be retrieved and then the function applied. The result may not
represent the complete story. A warning may appear at authoring time to remind you of
this limitation and to suggest switching to delegable alternatives where possible. For
more information, see the delegation overview.
For example, when used with a data source containing a large table with 1 million
records, Last will be subject to the non-delegation limit and will not return the last
record of the entire data source. Likewise, using Index to request a record in the middle
of 1 million records will result in an error because the index is out of range based on the
non-delegation limit.
Syntax
First( Table )
Last( Table )
Examples
For the following examples, we'll use the IceCream data source, which contains the data
in this table:
This table can be placed in a collection with this formula (put in the OnStart formula for
a Button control and press the button):
Power Apps
Launch
Launches a webpage or a canvas app. The function supports:
Address (required), the URL of the webpage or App ID of the canvas app.
Parameters (optional), named values to pass to the webpage or canvas app. In a
canvas app, parameters can be read with the Param function.
Target (optional), the browser tab in which to launch the webpage or canvas app.
Address
Webpages are launched via a URL address. For example:
Power Apps
Launch( "https://bing.com" )
You can launch canvas apps with Web link or App ID. To find these values for an app:
1. Go to Power Apps .
You can also select ... (More Commands) and then select Details from the drop-
down menu.
5. Copy Web link or App ID.
The Web link can be used in any web page and will launch the canvas app. It can also be
used with the Launch function.
The App ID can be used with the Launch function, but must be prefixed with
/providers/Microsoft.PowerApps/apps/ . For example:
Power Apps
Launch( "/providers/Microsoft.PowerApps/apps/f342faaf-5f82-4ace-a64b-
7c1b01499231" )
Native apps on a device can't be launched directly. There may be indirect options
available on some platforms, such as a native app installing a custom URL scheme or
registering with the web browser to offer an option for specific web sites.
Parameters
Launch can pass parameters to the webpage or canvas app. Parameters can be provided
in two ways:
Power Apps
Power Apps
This form can be easier to work with as it makes the association between name
and value clearer. It's the only form that supports the optional LaunchTarget
argument.
The address and parameters are URL encoded before being passed to replace certain
non-alphanumeric characters with % and a hexadecimal number as if the EncodeUrl
function has been used on each.
When launching a webpage, a query string of parameters can be included at the end
of the URL address. Any additional parameters provided to Launch will be added to the
end of the query string. Query strings don't work when launching a canvas app.
Target
Use the LaunchTarget argument to specify the target browser window in which to open
the webpage or app. Use one of the following LaunchTarget enum values or provide a
custom window name.
LaunchTarget enum Description
name Instead of an enum value, use your own text string to name the window or
tab. Self is an internal only name that is only used by the Launch function.
It has no impact on nor will it match the title of the window that your
users see. If a window or tab with the given name already exists, its
contents will be replaced. Otherwise, a new window or tab will be created.
name can't begin with the underscore character "_".
New is the default enum when running in a web browser with Replace and name as
available options. In a mobile player, New is the default for webpages with name as an
available option; while the current canvas app will always be replaced by another canvas
app.
7 Note
Using a LaunchTarget with any value other than New in embedded scenarios
(for example, Power BI or SharePoint) is not supported and may result in
unexpected behavior. In the future, this behavior may change, or may cause
an error.
Param
The Param function retrieves a parameter passed to the app when it was launched. If the
named parameter wasn't passed, Param returns blank.
When launching a canvas app from another canvas app, use the Parameter
arguments to the Launch function. Parameter names and values will be
automatically URL encoded.
When launching a canvas app from a web page, add parameters to the query
string of the canvas app web link. This involves adding
¶metername=parametervalue assuming the query string has already been
started for the tenantId . For example, adding &First%20Name=Vicki&category=3
would pass two parameters: First Name with a value of "Vicki" and category with
a value of "3" (value type is text). The parameter name and value must be URL
encoded if they contain spaces or special characters, similar to using the
EncodeURL function.
Param names are case-sensitive.
Param names and values will be automatically URL decoded for use in your app.
Even if the parameter contains a number, the type returned by Param will always
be a text string. Conversion to other types will automatically occur or use explicit
conversions such as the Value function to convert explicitly to a number.
Syntax
Launch( Address [, ParameterName1, ParameterValue1, ... ] )
Param( ParameterName )
Reserved parameters
The following keywords are reserved (regardless of case) for internal use, and shouldn't
be used as a custom parameter in the Param() function:
amp%3Bauthmode
amp%3Benableonbehalfof
amp%3Bhidenavbar
amp%3Blocale
appmetadataversion
authmode
channeltype
cordovapath
correlationid
debug
delegatelaunchurl
delegatelaunchurl
disablepreviewredirect
embedderorigin
enableonbehalfof
groupid
hideappsplash
hidenavbar
hint
hostclienttype
hostmode
iframecontainerid
isfullscreen
ispreviewmode
loader
loaderType
locale
location
packagekind
packageproperties
playerresourcespath
playersessionid
powerappslanguage
screencolor
sdkversion
site
skipappmetadata
skipiframecreation
skiplaunchappcache
source
standaloneconsent
teamid
teamtype
tenantId
theme
uselocalpackagehostresources
userteamrole
Examples
Simple Launch
From a canvas app to a web page:
Formula Description
Launch( "http://bing.com/search",
Opens the webpage http://bing.com/search?
"q", "Power Apps", "count", 1 ) q=Power%20Apps&count=1 . A new window or tab is
opened.
Launch( "http://bing.com/search",
The same as the previous examples using the equivalent
{ q: "Power Apps", count: 1 } ) record notation. A new window or tab is opened.
Launch( "http://bing.com/search",
The same as the previous examples, replacing the current
{ q: "Power Apps", count: 1 },
window or tab with the result if running in a web browser.
LaunchTarget.Replace )
Launch( "http://bing.com/search",
The same as the previous example, creating or replacing
{ q: "Power Apps", count: 1 },
the contents of the window or tab named Search Results.
"Search Results" )
Update the app ID, screen name, and record number as appropriate.
Power Apps
Launch( "/providers/Microsoft.PowerApps/apps/YOUR-APP-ID",
Update the app ID, tenant ID, screen name, and record number as appropriate.
HTML
<html>
<body>
<a
href="https://apps.powerapps.com/play/YOUR-APP-ID?tenantId=YOUR-
TENANT-ID&Navigate=Second%20Screen&Record=34"
>
</a>
</body>
</html>
Simple Param
Simple launch examples above to launch canvas app from web page or from another
canvas app show simple examples for Param function:
Param( "Navigate" ) The Navigate parameter was provided when the app was "Second
launched and is returned. Screen"
Param( "Record" ) The Record parameter was provided when the app was "34"
launched. Even though it was passed in as a number to the
Launch function, the result from Param will be a text string that
can be implicitly or explicitly converted to other types.
Param( "User" ) The User parameter wasn't provided. A blank value is returned blank
that can be tested with the IsBlank function.
Example - Launch
1. Go to Power Apps .
6. From the properties pane on the right-side, select Color as white and set Border
thickness at 1.
7. Select the Text property from right-side and enter text as Surface tablets in news.
your choice.
10. Save and publish the app.
12. Select label Surface tablets in news to launch news search with keywords Microsoft
Surface tablets.
Tip
For scalability, you can replace the manually entered keywords in Launch function
with variables.
Example - Param
1. Go to Power Apps .
7. Enter formula as Param("browser") . You can also use a different parameter of your
choice.
8. Save and publish the app.
11. Paste the app web link in the browser and append &browser=Microsoft%20Edge at
the end.
12. When your app launches, the label shows the parameter value passed.
13. Close the app player and edit the app.
7 Note
Replace the TechSpecs control name in the If function with the name of a
screen control in your own app if you're not using the Product Showcase app
template.
19. Paste the app web link in the browser and append &screen=techspecs at the end.
See also
Canvas app formula reference
Left, Mid, and Right functions in Power
Apps
Article • 03/17/2023 • 2 minutes to read
Description
The Left, Mid, and Right functions return a portion of a string.
If you specify a single string as an argument, the function returns the portion that you
requested of the string. If you specify a single-column table that contains strings, the
function returns a single-column table with a Value column containing the portions that
you requested of those strings. If you specify a multi-column table, you can shape it into
a single-column table, as working with tables describes.
If the starting position is negative or beyond the end of the string, Mid returns blank.
You can check the length of a string by using the Len function. If you request more
characters than the string contains, the function returns as many characters as possible.
Syntax
Left( String, NumberOfCharacters )
Examples
Single string
The examples in this section use a text-input control as their data source. The control is
named Author and contains the string "E. E. Cummings".
Left( Author.Text, Extracts up to five characters from the start of the string. "E. E."
5)
Mid( Author.Text, Extracts up to four characters, starting with the seventh "Cumm"
7, 4 ) character, from the string.
Mid( Author.Text, Extracts all characters, starting with the seventh character, "Cummings"
7) from the string.
Right( Extracts up to five characters from the end of the string. "mings"
Author.Text, 5 )
Single-column table
Each example in this section extracts strings from the Address column of this data
source, named People, and returns a single-column table that contains the results:
Name Address
Step-by-step example
1. Import or create a collection named Inventory, and show it in a gallery, as the first
procedure in Show images and text in a gallery describes.
2. Set the Text property of the lower label in the gallery to this function:
Right(ThisItem.ProductName, 3)
The label shows the last three characters of each product name.
Len function in Power Apps
Article • 03/17/2023 • 2 minutes to read
Description
If you specify a single string as the argument, the return value is the length as a number.
If you specify a single-column table that contains strings, the return value is a single-
column table with a Value column that contains the length of each string. If you have a
multi-column table, you can shape it into a single-column table, as working with tables
describes.
Syntax
Len( String )
Len( SingleColumnTable )
Examples
Single string
For the examples in this section, the data source is a text-input control that's named
Author and that contains the string "E. E. Cummings".
Len( Author.Text ) Measures the length of the string in the Author control. 14
Single-column table
For the first example in this section, the data source is named People and contains this
data:
Name Address
Len( [ "Hello", "to the", "World", "" In the Value column of the A single-column table with a
]) inline table:
Value column containing the
following values: 5, 6, 5, 0
Measures the length
of each string.
Returns a single-
column table that
contains the length
of each string.
Abs, Exp, Ln, Power, Log, and Sqrt
functions in Power Apps
Article • 03/17/2023 • 2 minutes to read
Calculates absolute values, logarithms, square roots, and the results of raising e or any
number to specified powers.
Description
The Abs function returns the non-negative value of its argument. If a number is
negative, Abs returns the positive equivalent.
The Exp function returns e raised to the power of its argument. The transcendental
number e begins 2.7182818...
The Power function returns a number raised to a power. It's equivalent to using the ^
operator.
The Log function returns the logarithm of its first argument in the base specified by its
second argument (or 10 if not specified).
The Sqrt function returns the number that, when multiplied by itself, equals its
argument.
If you pass a single number, the return value is a single result based on the function
called. If you pass a single-column table that contains numbers, the return value is a
single-column table of results in a Value column, one result for each record in the
argument's table. If you have a multi-column table, you can shape it into a single-
column table, as working with tables describes.
If an argument would result in an undefined valued, the result is blank. Which can
happen with square roots and logarithms of negative numbers.
Syntax
Abs( Number )
Exp( Number )
Ln( Number )
Sqrt( Number )
Number - Required. Number to operate on.
Abs( SingleColumnTable )
Exp( SingleColumnTable )
Ln( SingleColumnTable )
Sqrt( SingleColumnTable )
Examples
Single number
Ln( 100 ) Returns the natural logarithm (base e) of the number 100. 4.605170...
Single-column table
The examples in this section use a data source that's named ValueTable and that
contains this data:
Value
-4
Sqrt( ValueTable ) Returns the square root A single-column table with a Value column
of each number in the containing the following values: 3, Blank(),
table 1.414213...
Step-by-step example
1. Add a Text input control, and name it Source.
2. Add a Label control, and set its Text property to this formula:
7 Note
These functions can now be used when playing an app in a web browser as an
experimental feature. This feature is disabled by default. To enable, navigate to
Settings > Upcoming features > Experimental > Enabled SaveData, LoadData,
ClearData on web player." and turn the switch on. To submit feedback regarding
this experimental feature, go to Power Apps community forum .
Description
The SaveData function stores a collection for later use under a name.
The LoadData function reloads a collection by name that was previously saved with
SaveData. You can't use this function to load a collection from another source.
The ClearData function clears the storage under a specific name or clears all storage
associated with the app if no name is provided.
7 Note
The name shared between SaveData, LoadData, and ClearData is a key, not a
file name. It need not be complex as names are unique to each app and there
is no danger of name conflict. The name must not contain any of these
characters: *".?:\<>|/ .
SaveData is limited to 1 MB of data for Power Apps running in Teams and in a
web browser. There is no fixed limit for Power Apps running in a mobile player
but there are practical limits discussed below.
Don't use SaveData to store sensitive data in the web since it'll be stored in
plain text.
You can also use these functions to add simple offline capabilities to your app.
To test your app, run it in Power Apps Mobile on an iPhone or Android device.
These functions are limited by the amount of available app memory as they operate on
an in-memory collection. Available memory can vary depending on factors such as:
Test your app with expected scenarios on the type of devices you expect the app to run
when storing large data. Expect to have between 30 MB and 70 MB of available memory
generally.
These functions depend on the collection being implicitly defined with Collect or
ClearCollect. You don't need to call Collect or ClearCollect to load data into the
collection for defining it. It's a common case when using LoadData after a previous
SaveData. All that is needed is the presence of these functions in a formula to implicitly
define the structure of the collection. For more information, see creating and removing
variables.
The loaded data will be appended to the collection. Use the Clear function before
calling LoadData if you want to start with an empty collection.
Data security
Consider carefully the isolation and encryption of data stored with SaveData and decide
if it's appropriate for your needs, especially if devices are shared by multiple users.
Data stored with SaveData is isolated from other Power Apps by the Power Apps
players. Data is stored based on the app's App ID, automatically isolating the SaveData
name space between Power Apps.
The operating system and browser is responsible for isolating data between Power Apps
and other apps on a device and with websites. For example, the operating system is
responsible for isolating data stored in Microsoft Outlook from data stored in Power
Apps, and also isolating that data from websites such as Bing.com or PowerApps.com.
The operating system's built in app sandbox facilities are used for SaveData storage
which is usually not accessible to or hidden from the user.
When using the same app, the operating system and browser is also responsible for
isolating the data between different operating system level users. For example, if two
different users share a computer and use two different Windows login credentials, the
operating system is responsible for isolating data between the two Windows users.
Data may or may not be isolated between different Power Apps users if the operating
system user is the same. Not every Power Apps player treats this the same way. For
example, while logged in as the same Windows user, in the Power Apps player, the user
signs out of Power Apps and signs in as a different Power Apps user. Data stored in an
app before the change of Power Apps user, may be accessible to the second Power
Apps user within the same app. The data may also be removed and the first Power Apps
user may no longer be able to access it. The behavior varies between Power Apps
players.
The operating system may also encrypt the data or you can use a mobile device
management tool such as Microsoft Intune . Data stored when playing an app in a web
browser is not encrypted.
Syntax
SaveData( Collection, Name )
ClearData( [Name] )
Name - Optional. Name of the storage previously saved with SaveData. If Name is
not provided, all storage associated with the app is cleared.
Examples
Formula Description Result
SaveData( Save the LocalCache collection to the user's device Data is saved to the app
LocalCache, under the name "MyCache", suitable for LoadData host under the name
"MyCache" ) to retrieve later. "MyCache".
LoadData( Loads the LocalCache collection from the user's Data is loaded from the
LocalCache, device under the name "MyCache", previously app host under the name
"MyCache" ) stored with a call to SaveData. "MyCache".
ClearData( Clears the storage under the name "MyCache". Any Data is removed from the
"MyCache" ) data stored under this name will no longer be app host under the name
available through LoadData. "MyCache".
ClearData() Clear all storage associated with this app. Data All data is removed from
stored by other apps is not affected. the app host.
7 Note
This example uses a camera control to capture images. Since SaveData is limited to
1 MB of data when running in Teams or a web browser, this example will not work
with more than a few images. Also, depending on the camera, it may not work with
even one image. Use a device to work through this full example, or remove the
camera control and picture part of this example to run in Teams or in a web
browser.
1. Create a blank canvas app with a tablet layout. For more details, read creating an
app from a template and select Tablet layout under Blank app.
2. Add a Text input control and a Camera control and arrange them roughly as
shown:
3. Add a Button control.
4. Double-click the button control to change the button text to Add Item (or modify
the Text property).
5. Set the OnSelect property of the button control to this formula that will add an
item to our collection:
Power Apps
7. Double-click the button control to change the button text to Save Data (or modify
the Text property).
8. Set the OnSelect property of the button control to this formula in order to save
our collection to the local device:
Power Apps
It's tempting to test the button as it doesn't affect anything. But you'll only see an
error as you're authoring in a web browser. Save the app first and open on a
device before you follow the next steps to test this formula:
10. Double-click the button control to change the button text to Load Data (or modify
the Text property).
11. Set the OnSelect property of the button control to this formula in order to load
our collection from the local device:
Power Apps
12. Add a Gallery control with a Vertical layout that includes a picture and text areas:
13. When prompted, select the MyItems collection as the data source for this gallery.
This will set the Items property of the Gallery control:
The image control in the gallery template should default its Image property to
ThisItem.Picture and the label controls should both default their Text properties to
ThisItem.Item. Check these formulas if after adding items in the following steps
you don't see anything in the gallery.
15. Save your app. If it's the first time it has been saved, there's no need to publish it. If
it's not the first time, publish the app after you save.
16. Open your app on a device such as a phone or tablet. SaveData and LoadData
can't be used in Studio or in a web browser. Refresh your app list if you don't see
your app immediately, it can take a few seconds for the app to appear on your
device. Signing out and back in to your account can help too.
Once your app has been downloaded, you can disconnect from the network and
run the app offline.
17. Enter the name and take a picture of an item.
18. Select the Add Item button. Repeat adding items a couple of times to load up your
collection.
19. Select the Save Data button. This will save the data in your collection to your local
device.
20. Close the app. Your collection in memory will be lost including all item names and
pictures, but they'll still be there in the device's storage.
21. Launch the app again. The collection in memory will again show as empty in the
gallery.
22. Select the Load Data button. The collection will be repopulated from the stored
data on your device and your items will be back in the gallery. The collection was
empty before this button calls the LoadData function; there was no need to call
Collect or ClearCollect before loading the data from storage.
23. Select the Load Data button again. The stored data will be appended to the end of
the collection and a scroll bar will appear on the gallery. If you would like to
replace rather than append, use the Clear function first to clear out the collection
before calling the LoadData function.
Returns information about the app's environment, such as where the user is located in
the world and which screen is displayed.
Signals typically return a record of information. You can use and store this information
as a record, or you can extract individual properties by using the . operator.
7 Note
The Acceleration and Compass functions return accurate values in a native player
such as on iOS or Android, but those functions return zero values as you create or
modify an app in the browser.
Acceleration
The Acceleration signal returns the device's acceleration in three dimensions relative to
the device's screen. Acceleration is measured in g units of 9.81 m/second2 or 32.2
ft/second2 (the acceleration that the Earth imparts to objects at its surface due to
gravity).
Property Description
Property Description
App.ActiveScreen Screen that's showing. Returns a screen object, which you can use to
reference properties of the screen or compare to another screen to
determine which screen is showing. You can use the Back or Navigate
function to change the screen that's showing.
Compass
The Compass signal returns the compass heading of the top of the screen. The heading
is based on magnetic north.
Property Description
Connection
The Connection signal returns the information about the network connection. When on
a metered connection, you may want to limit how much data you send or receive over
the network.
Property Description
Connection.Connected Returns a Boolean true or false value that indicates whether the device
is connected to a network.
Connection.Metered Returns a Boolean true or false value that indicates whether the
connection is metered.
Location
The Location signal returns the location of the device based on the Global Positioning
System (GPS) and other device information, such as cell-tower communications and IP
address.
When a user accesses the location information for the first time, the device may prompt
that user to allow access to this information.
Property Description
Location.Altitude Returns a number that indicates the altitude, measured in meters, above
sea level.
Location.Latitude Returns a number, from –90 to 90, that indicates the latitude, as measured
in degrees from the equator. A positive number indicates a location that's
north of the equator.
Location.Longitude Returns a number, from –180 to 180, that indicates the longitude, as
measured in degrees from Greenwich, England. A positive number indicates
a location that's east of Greenwhich.
Examples
In a baseball field, a pitcher throws a phone from the pitcher's mound to a catcher at
home plate. The phone is lying flat with respect to the ground, the top of the screen is
pointed at the catcher, and the pitcher adds no spin. At this location, the phone has
cellular network service that's metered but no WiFi. The PlayBall screen is displayed.
Acceleration.Y Returns the acceleration of the device front to 8.2, while the
back. The pitcher initially gives the device a large pitcher throws the
acceleration when throwing the device, going device.
Acceleration.Z Returns the acceleration of the device top to 0, before the pitcher
bottom. While in the air, the device experiences throws the device.
Watch this video to learn how to use Filter, Search and LookUp functions:
https://www.microsoft.com/en-us/videoplayer/embed/RWLj3m?postJsllMsg=true
Description
The Filter function finds records in a table that satisfy a formula. Use Filter to find a set
of records that match one or more criteria and to discard those that don't.
The LookUp function finds the first record in a table that satisfies a formula. Use LookUp
to find a single record that matches one or more criteria.
For both, the formula is evaluated for each record of the table. Records that result in
true are included in the result. Besides the normal formula operators, you can use the in
and exactin operators for substring matches.
Fields of the record currently being processed are available within the formula. Use the
ThisRecord operator or simply reference fields by name as you would any other value.
The As operator can also be used to name the record being processed which can help
make your formula easier to understand and make nested records accessible. For more
information, see the examples below and working with record scope.
The Search function finds records in a table that contain a string in one of their columns.
The string may occur anywhere within the column; for example, searching for "rob" or
"bert" would find a match in a column that contains "Robert". Searching is case-
insensitive. Unlike Filter and LookUp, the Search function uses a single string to match
instead of a formula.
Filter and Search return a table that contains the same columns as the original table and
the records that match the criteria. LookUp returns only the first record found, after
applying a formula to reduce the record to a single value. If no records are found, Filter
and Search return an empty table, and LookUp returns blank.
Tables are a value in Power Apps, just like a string or number. They can be passed to and
returned from functions. Filter, Search, and LookUp don't modify a table. Instead, they
take a table as an argument and return a table, a record, or a single value from it. See
working with tables for more details.
Delegation
When possible, Power Apps will delegate filter and sort operations to the data source
and page through the results on demand. For example, when you start an app that
shows a Gallery control filled with data, only the first set of records will be initially
brought to the device. As the user scrolls, additional data is brought down from the data
source. The result is a faster start time for the app and access to very large data sets.
However, delegation may not always be possible. Data sources vary on what functions
and operators they support with delegation. If complete delegation of a formula isn't
possible, the authoring environment will flag the portion that can't be delegated with a
warning. When possible, consider changing the formula to avoid functions and
operators that can't be delegated. The delegation list details which data sources and
operations can be delegated.
If delegation is not possible, Power Apps will pull down only a small set of records to
work on locally. Filter and sort functions will operate on a reduced set of records. What
is available in the Gallery may not be the complete story, which could be confusing to
users.
Syntax
Filter(Table*, Formula1 [, *Formula2*, ... ] )
7 Note
For SharePoint and Excel data sources that contain column names with spaces,
specify each space as "_x0020_". For example, specify "Column Name" as
"Column_x0020_Name".
Table - Required. Table to search. In the UI, the syntax is shown as source above the
function box.
Formula - Required.
The formula by which each record of the table is evaluated.
The function returns the first record that results in true. You can reference columns
within the table. In the UI, the syntax is shown as condition above the function box.
ReductionFormula - Optional. This formula is evaluated over the record that was
found, and then reduces the record to a single value. You can reference columns
within the table. If you don't use this parameter, the function returns the full record
from the table. In the UI, the syntax is shown as result above the function box.
Examples
The following examples use the IceCream data source:
Search(IceCream, Because the search term is empty, all records are returned.
"", "Flavor")
LookUp(IceCream, Searches for a record with Quantity greater than 150, of 250
Quantity > 150, which there are multiple. For the first record that's found,
Quantity + which is "Vanilla" Flavor, returns the sum of Quantity and
OnOrder) OnOrder columns.
LookUp(IceCream, Searches for a record with Flavor equal to "Vanilla", of which { Flavor:
Flavor = "Vanilla") there is one. Since no reduction formula was supplied, the "Vanilla",
entire record is returned. Quantity:
200,
OnOrder: 75
}
Step by step
4. On the Properties tab of the right-hand pane, open Data Source and then select
Accounts.
6. On the Insert tab, select Input and then select Combo box. Repeat the step to add
two more combo box controls.
7. For each combo box control, on the Properties tab of the right-hand pane, open
Data Source and then select Accounts. Select Edit next to Fields option and then
select the Primary text and SearchField values. The Primary text should be the
choices column you want to add to the combo box. Repeat the step for other two
combo box controls.
8. Now select Gallery control and set the Items property to the following formula:
Filter(Accounts,
'Industry' =
ComboBox3.Selected.Industry||IsBlank(ComboBox3.Selected.Industry),
IsBlank(ComboBox2.Selected.'Relationship Type'),
In many apps, you can type one or more characters into a search box to filter a list of
records in a large data set. As you type, the list shows only those records that match the
search criteria.
The examples in the rest of this topic show the results of searching a list, named
Customers, that contain this data:
To create this data source as a collection, create a Button control and set its OnSelect
property to this formula:
As in this example, you can show a list of records in a Gallery control at the bottom of a
screen. Near the top of the screen, you can add a Text input control, named
SearchInput, so that users can specify which records interest them.
As the user types characters in SearchInput, the results in the gallery are automatically
filtered. In this case, the gallery is configured to show records for which the name of the
customer (not the name of the company) starts with the sequence of characters in
SearchInput. If the user types co in the search box, the gallery shows these results:
To filter based on the Name column, set the Items property of the gallery control to one
of these formulas:
Filter(Customers, Filters the Customers data source for records in which the search
StartsWith(Name, string appears at the start of the Name column. The test is case
SearchInput.Text) insensitive. If the user types co in the search box, the gallery shows
) Colleen Jones and Cole Miller. The gallery doesn't show Mike
Collins because the Name column for that record doesn't start
with the search string.
Filter(Customers, Filters the Customers data source for records in which the search
SearchInput.Text string appears anywhere in the Name column. The test is case
in Name) insensitive. If the user types co in the search box, the gallery shows
Colleen Jones, Cole Miller, and Mike Collins because the search
string appears somewhere in the Name column of all of those
records.
Search(Customers, Similar to using the in operator, the Search function searches for a
SearchInput.Text, match anywhere within the Name column of each record. You
"Name") must enclose the column name in double quotation marks.
You can expand your search to include the Company column and the Name column:
Filter(Customers, Filters the Customers data source for records in which either the
StartsWith(Name, Name column or the Company column starts with the search
SearchInput.Text) || string (for example, co). The || operator is true if either
StartsWith(Company, StartsWith function is true.
SearchInput.Text) )
Filter(Customers, Filters the Customers data source for records in which either the
SearchInput.Text in Name column or the Company column contains the search
Name || SearchInput. string (for example, co) anywhere within it.
Text in Company)
Converts letters in a string of text to all lowercase, all uppercase, or proper case.
Description
The Lower, Upper, and Proper functions convert the case of letters in strings.
If you pass a single string, the return value is the converted version of that string. If you
pass a single-column table that contains strings, the return value is a single-column
table of converted strings. If you have a multi-column table, you can shape it into a
single-column table, as working with tables describes.
Syntax
Lower( String )
Upper( String )
Proper( String )
Lower( SingleColumnTable )
Upper( SingleColumnTable )
Proper( SingleColumnTable )
Examples
Single string
The examples in this section use a text-input control, named Author, as their data
source. The control contains the string "E. E. CummINGS".
Proper( Author.Text ) Converts the first letter of each word to uppercase if it's "E. E.
lowercase, and converts any other uppercase letters to Cummings"
lowercase.
Single-column table
The examples in this section convert strings from the Address column of the People
data source, which contains this data:
Name Address
Each formula returns a single-column table that contains the converted strings.
Proper(Source.Text)
3. Press F5, and then type WE ARE THE BEST! into the Source box.
Description
The IsMatch function tests whether a text string matches a pattern that can comprise
ordinary characters, predefined patterns, or a regular expression. The Match and
MatchAll functions return what was matched, including sub-matches.
Use IsMatch to validate what a user has typed in a Text input control. For example, you
can confirm whether the user has entered a valid email address before the result is
saved to your data source. If the entry doesn't match your criteria, add other controls
that prompt the user to correct the entry.
Use Match to extract the first text string that matches a pattern and MatchAll to extract
all text strings that match. You can also extract sub-matches to parse complex strings.
Match returns a record of information for the first match found, and MatchAll returns a
table of records for every match found. The record or records contain:
named Text Each named sub-match will have its own column. Create a named sub-
sub‑match match by using (?<name>...) in the regular expression. If a named sub-
or match has the same name as one of the predefined columns (below),
sub‑matches the sub-match takes precedence, and a warning is generated. To avoid
this warning, rename the sub-match.
StartMatch Number The starting position of the match within the input text string. The first
character of the string returns 1.
SubMatches Single- The table of named and unnamed sub-matches in the order in which
column they appear in the regular expression. Generally, named sub-matches
table of are easier to work with and are encouraged. Use the ForAll function or
Text Last( FirstN( ... ) ) functions to work with an individual sub-match. If no
(column sub-matches are defined in the regular expression, this table will be
Value) present but empty.
IsMatch returns true if the text string matches the pattern or false if it doesn't. Match
returns blank if no match is found that can be tested with the IsBlank function. MatchAll
returns an empty table if no match is found that can be tested with the IsEmpty
function.
If you're using MatchAll to split a text string, consider using the Split function, which is
simpler to use and faster.
Patterns
The key to using these functions is in describing the pattern to match. You describe the
pattern in a text string as a combination of:
Combine these elements by using the string-concatenation operator &. For example,
"abc" & Digit & "\s+" is a valid pattern that matches the characters "a", "b", and "c",
followed by a digit from 0 to 9, followed by at least one whitespace character.
Ordinary characters
The simplest pattern is a sequence of ordinary characters to be matched exactly.
For example, when used with the IsMatch function, the string "Hello" matches the
pattern "Hello" exactly. No more and no less. The string "hello!" doesn't match the
pattern because of the exclamation point on the end and because the case is wrong for
the letter "h". (See MatchOptions for ways to modify this behavior.)
In the pattern language, certain characters are reserved for special purposes. To use
these characters, either prefix the character with a \ (backslash) to indicate that the
character should be taken literally, or use one of the predefined patterns described later
in this topic. This table lists the special characters:
Special character Description
. dot or period
? question mark
* asterisk
+ plus
() parentheses
[] square brackets
{} curly braces
^ caret
$ dollar sign
\ backslash
For example, you can match "Hello?" by using the pattern "Hello\?" with a backslash
before the question mark.
Predefined patterns
Predefined patterns provide a simple way to match either one of a set of characters or a
sequence of multiple characters. Use the string-concatenation operator & to combine
your own text strings with members of the Match enum:
Email Matches an email address that contains an "at" symbol ("@") .+\@.+\\.
and a domain name that contains a dot (".") [^\\.]{2,}
MultipleNonSpaces Matches one or more characters that don't add whitespace \S+
(not space, tab, or newline).
MultipleSpaces Matches one or more characters that add whitespace (space, \s+
tab, or newline).
OptionalNonSpaces Matches zero, one, or more characters that don't add \S*
whitespace.
OptionalSpaces Matches zero, one, or more characters that add whitespace. \s*
For example, the pattern "A" & MultipleDigits will match the letter "A" followed by one
or more digits.
Regular expressions
The pattern that these functions use is a regular expression . The ordinary characters
and predefined patterns that are described earlier in this topic help build regular
expressions.
Regular expressions are very powerful, available in many programming languages, and
used for a wide variety of purposes. They can also often look like a random sequence of
punctuation marks. This article doesn't describe all aspects of regular expressions, but a
wealth of information, tutorials, and tools are available on the web.
Regular expressions come in different dialects, and Power Apps uses a variant of the
JavaScript dialect. See regular-expression syntax for an introduction to the syntax.
Named sub-matches (sometimes called named capture groups) are supported:
In the Match enum table earlier in this topic, each enum appears in the same row as its
corresponding regular expression.
Match options
You can modify the behavior of these functions by specifying one or more options,
which you can combine by using the string- concatenation operator (&).
MatchOptions.BeginsWith The pattern must match from Adds a ^ to the start of the
the beginning of the text. regular expression.
MatchOptions.Complete Default for IsMatch. The pattern Adds a ^ to the start and a $ to
must match the entire string of the end of the regular
text, from beginning to end. expression.
MatchOptions.EndsWith The pattern must match the end Adds a $ to the end of the
of the string of text. regular expression.
Using MatchAll is equivalent to using the standard "g" modifier for regular expressions.
Syntax
IsMatch( Text, Pattern [, Options ] )
IsMatch examples
Ordinary characters
Imagine that your app contains a Text input control named TextInput1. The user enters
values into this control to be stored in a database.
IsMatch( TextInput1.Text, "Hello Tests whether the user's input matches, true
world" ) exactly, the string "Hello world".
IsMatch( TextInput1.Text, "Good bye" Tests whether the user's input matches, false
) exactly, the string "Good bye".
IsMatch( TextInput1.Text, "hello", Tests whether the user's input contains the false
Contains ) word "hello" (case sensitive).
IsMatch( TextInput1.Text, "hello", Tests whether the user's input contains the true
Contains & IgnoreCase ) word "hello" (case insensitive).
Predefined patterns
IsMatch( "123-45-7890", Digit & Matches a United States Social Security true
Digit & Digit & Hyphen & Digit & Number
Digit & Hyphen & Digit & Digit &
Digit & Digit )
IsMatch( "123.456", MultipleDigits & Matches a sequence of digits, a period, and true
Period & OptionalDigits ) then zero or more digits.
IsMatch( "123", MultipleDigits & Matches a sequence of digits, a period, and false
Period & OptionalDigits ) then zero or more digits. A period doesn't
appear in the text to match, so this pattern
isn't matched.
Regular expressions
IsMatch( "1.02", Matches a positive currency amount. If the input contains a true
"\d+(\.\d\d)?" ) decimal point, the input must also contain two numeric
characters after the decimal point. For example, 3.00 is valid,
but 3.1 isn't.
Formula Description Result
IsMatch( "-4.95", " Matches a positive or negative currency amount. If the input true
(-)?\d+(\.\d\d)?" ) contains a decimal point, the input must also contain two
numeric characters after the decimal point.
IsMatch( "111-11- Matches a United States Social Security number. Validates the true
1111", "\d{3}-\d{2}- format, type, and length of the supplied input field. The string
\d{4}" ) to match must consist of three numeric characters followed by
a dash, then two numeric characters followed by a dash, and
then four numeric characters.
IsMatch( "111-111- Same as the previous example, but one of the hyphens is out of false
111", "\d{3}-\d{2}- place in the input.
\d{4}" )
IsMatch( Validates a strong password, which must contain eight, nine, or false
"AStrongPasswordNot", 10 characters, in addition to at least one digit and at least one
"(?!^[0-9]\*$)(?!^[a- alphabetic character. The string must not contain special
zA-Z]\*$)([a-zA-Z0-9] characters.
{8,10})" )
StartMatch: 11
convert it to a number }
before mathematical
operations are
performed on it.
Let's drill into that last example. If you wanted to convert this string to a date/time value
using the Time function, you must pass in the named sub-matches individually. To do
this, you can use the With function operating on the record that Match returns:
Power Apps
With(
For these examples, add a Button control, set its OnSelect property to this formula, and
then select the button:
Power Apps
Set( pangram, "The quick brown fox jumps over the lazy dog." )
StartMatch: 17
The gallery is filled with each word in our example text. Resize the gallery's
template and the label control in order to see all the words on one screen.
IsMatch, Match, and MatchAll functions
in Power Apps
Article • 03/08/2023 • 12 minutes to read
Description
The IsMatch function tests whether a text string matches a pattern that can comprise
ordinary characters, predefined patterns, or a regular expression. The Match and
MatchAll functions return what was matched, including sub-matches.
Use IsMatch to validate what a user has typed in a Text input control. For example, you
can confirm whether the user has entered a valid email address before the result is
saved to your data source. If the entry doesn't match your criteria, add other controls
that prompt the user to correct the entry.
Use Match to extract the first text string that matches a pattern and MatchAll to extract
all text strings that match. You can also extract sub-matches to parse complex strings.
Match returns a record of information for the first match found, and MatchAll returns a
table of records for every match found. The record or records contain:
named Text Each named sub-match will have its own column. Create a named sub-
sub‑match match by using (?<name>...) in the regular expression. If a named sub-
or match has the same name as one of the predefined columns (below),
sub‑matches the sub-match takes precedence, and a warning is generated. To avoid
this warning, rename the sub-match.
StartMatch Number The starting position of the match within the input text string. The first
character of the string returns 1.
SubMatches Single- The table of named and unnamed sub-matches in the order in which
column they appear in the regular expression. Generally, named sub-matches
table of are easier to work with and are encouraged. Use the ForAll function or
Text Last( FirstN( ... ) ) functions to work with an individual sub-match. If no
(column sub-matches are defined in the regular expression, this table will be
Value) present but empty.
IsMatch returns true if the text string matches the pattern or false if it doesn't. Match
returns blank if no match is found that can be tested with the IsBlank function. MatchAll
returns an empty table if no match is found that can be tested with the IsEmpty
function.
If you're using MatchAll to split a text string, consider using the Split function, which is
simpler to use and faster.
Patterns
The key to using these functions is in describing the pattern to match. You describe the
pattern in a text string as a combination of:
Combine these elements by using the string-concatenation operator &. For example,
"abc" & Digit & "\s+" is a valid pattern that matches the characters "a", "b", and "c",
followed by a digit from 0 to 9, followed by at least one whitespace character.
Ordinary characters
The simplest pattern is a sequence of ordinary characters to be matched exactly.
For example, when used with the IsMatch function, the string "Hello" matches the
pattern "Hello" exactly. No more and no less. The string "hello!" doesn't match the
pattern because of the exclamation point on the end and because the case is wrong for
the letter "h". (See MatchOptions for ways to modify this behavior.)
In the pattern language, certain characters are reserved for special purposes. To use
these characters, either prefix the character with a \ (backslash) to indicate that the
character should be taken literally, or use one of the predefined patterns described later
in this topic. This table lists the special characters:
Special character Description
. dot or period
? question mark
* asterisk
+ plus
() parentheses
[] square brackets
{} curly braces
^ caret
$ dollar sign
\ backslash
For example, you can match "Hello?" by using the pattern "Hello\?" with a backslash
before the question mark.
Predefined patterns
Predefined patterns provide a simple way to match either one of a set of characters or a
sequence of multiple characters. Use the string-concatenation operator & to combine
your own text strings with members of the Match enum:
Email Matches an email address that contains an "at" symbol ("@") .+\@.+\\.
and a domain name that contains a dot (".") [^\\.]{2,}
MultipleNonSpaces Matches one or more characters that don't add whitespace \S+
(not space, tab, or newline).
MultipleSpaces Matches one or more characters that add whitespace (space, \s+
tab, or newline).
OptionalNonSpaces Matches zero, one, or more characters that don't add \S*
whitespace.
OptionalSpaces Matches zero, one, or more characters that add whitespace. \s*
For example, the pattern "A" & MultipleDigits will match the letter "A" followed by one
or more digits.
Regular expressions
The pattern that these functions use is a regular expression . The ordinary characters
and predefined patterns that are described earlier in this topic help build regular
expressions.
Regular expressions are very powerful, available in many programming languages, and
used for a wide variety of purposes. They can also often look like a random sequence of
punctuation marks. This article doesn't describe all aspects of regular expressions, but a
wealth of information, tutorials, and tools are available on the web.
Regular expressions come in different dialects, and Power Apps uses a variant of the
JavaScript dialect. See regular-expression syntax for an introduction to the syntax.
Named sub-matches (sometimes called named capture groups) are supported:
In the Match enum table earlier in this topic, each enum appears in the same row as its
corresponding regular expression.
Match options
You can modify the behavior of these functions by specifying one or more options,
which you can combine by using the string- concatenation operator (&).
MatchOptions.BeginsWith The pattern must match from Adds a ^ to the start of the
the beginning of the text. regular expression.
MatchOptions.Complete Default for IsMatch. The pattern Adds a ^ to the start and a $ to
must match the entire string of the end of the regular
text, from beginning to end. expression.
MatchOptions.EndsWith The pattern must match the end Adds a $ to the end of the
of the string of text. regular expression.
Using MatchAll is equivalent to using the standard "g" modifier for regular expressions.
Syntax
IsMatch( Text, Pattern [, Options ] )
IsMatch examples
Ordinary characters
Imagine that your app contains a Text input control named TextInput1. The user enters
values into this control to be stored in a database.
IsMatch( TextInput1.Text, "Hello Tests whether the user's input matches, true
world" ) exactly, the string "Hello world".
IsMatch( TextInput1.Text, "Good bye" Tests whether the user's input matches, false
) exactly, the string "Good bye".
IsMatch( TextInput1.Text, "hello", Tests whether the user's input contains the false
Contains ) word "hello" (case sensitive).
IsMatch( TextInput1.Text, "hello", Tests whether the user's input contains the true
Contains & IgnoreCase ) word "hello" (case insensitive).
Predefined patterns
IsMatch( "123-45-7890", Digit & Matches a United States Social Security true
Digit & Digit & Hyphen & Digit & Number
Digit & Hyphen & Digit & Digit &
Digit & Digit )
IsMatch( "123.456", MultipleDigits & Matches a sequence of digits, a period, and true
Period & OptionalDigits ) then zero or more digits.
IsMatch( "123", MultipleDigits & Matches a sequence of digits, a period, and false
Period & OptionalDigits ) then zero or more digits. A period doesn't
appear in the text to match, so this pattern
isn't matched.
Regular expressions
IsMatch( "1.02", Matches a positive currency amount. If the input contains a true
"\d+(\.\d\d)?" ) decimal point, the input must also contain two numeric
characters after the decimal point. For example, 3.00 is valid,
but 3.1 isn't.
Formula Description Result
IsMatch( "-4.95", " Matches a positive or negative currency amount. If the input true
(-)?\d+(\.\d\d)?" ) contains a decimal point, the input must also contain two
numeric characters after the decimal point.
IsMatch( "111-11- Matches a United States Social Security number. Validates the true
1111", "\d{3}-\d{2}- format, type, and length of the supplied input field. The string
\d{4}" ) to match must consist of three numeric characters followed by
a dash, then two numeric characters followed by a dash, and
then four numeric characters.
IsMatch( "111-111- Same as the previous example, but one of the hyphens is out of false
111", "\d{3}-\d{2}- place in the input.
\d{4}" )
IsMatch( Validates a strong password, which must contain eight, nine, or false
"AStrongPasswordNot", 10 characters, in addition to at least one digit and at least one
"(?!^[0-9]\*$)(?!^[a- alphabetic character. The string must not contain special
zA-Z]\*$)([a-zA-Z0-9] characters.
{8,10})" )
StartMatch: 11
convert it to a number }
before mathematical
operations are
performed on it.
Let's drill into that last example. If you wanted to convert this string to a date/time value
using the Time function, you must pass in the named sub-matches individually. To do
this, you can use the With function operating on the record that Match returns:
Power Apps
With(
For these examples, add a Button control, set its OnSelect property to this formula, and
then select the button:
Power Apps
Set( pangram, "The quick brown fox jumps over the lazy dog." )
StartMatch: 17
The gallery is filled with each word in our example text. Resize the gallery's
template and the label control in order to see all the words on one screen.
Average, Max, Min, StdevP, Sum, and
VarP functions in Power Apps
Article • 02/23/2023 • 2 minutes to read
Description
The Average function calculates the average, or arithmetic mean, of its arguments.
Fields of the record currently being processed are available within the formula. Use the
ThisRecord operator or simply reference fields by name as you would any other value.
The As operator can also be used to name the record being processed which can help
make your formula easier to understand and make nested records accessible. For more
information, see the examples below and working with record scope.
These functions operate on numeric values only. Other types of values, such as strings or
records, are ignored. Use the Value function to convert a string into a number.
The Average, Max, Min, and Sum functions can be delegated when used with a data
source that supports delegation for these functions. However, StdevP and VarP can't be
delegated for any data sources. If delegation is not supported, only the first portion of
the data will be retrieved and then the function applied locally. The result may not
represent the complete story. A delegation warning will appear at authoring time to
remind you of this limitation and to suggest switching to delegable alternatives where
possible. For more information, see the delegation overview.
Syntax
Average( NumericalFormula1, [ NumericalFormula2, ... ] )
Examples
Step by step
Let's say that you had a data source named Sales that contained a CostPerUnit column
and a UnitsSold column, and you set the Text property of a label to this function:
The label would show total sales by multiplying the values in those columns for each
record and then adding the results from all records together:
As a different example, let's say that you had sliders that were named Slider1, Slider2,
and Slider3 and a label with its Text property set to this formula:
Sum(Slider1.Value, Slider2.Value, Slider3.Value): The label would show the sum of all
values to which the sliders were set.
Description
The Left, Mid, and Right functions return a portion of a string.
If you specify a single string as an argument, the function returns the portion that you
requested of the string. If you specify a single-column table that contains strings, the
function returns a single-column table with a Value column containing the portions that
you requested of those strings. If you specify a multi-column table, you can shape it into
a single-column table, as working with tables describes.
If the starting position is negative or beyond the end of the string, Mid returns blank.
You can check the length of a string by using the Len function. If you request more
characters than the string contains, the function returns as many characters as possible.
Syntax
Left( String, NumberOfCharacters )
Examples
Single string
The examples in this section use a text-input control as their data source. The control is
named Author and contains the string "E. E. Cummings".
Left( Author.Text, Extracts up to five characters from the start of the string. "E. E."
5)
Mid( Author.Text, Extracts up to four characters, starting with the seventh "Cumm"
7, 4 ) character, from the string.
Mid( Author.Text, Extracts all characters, starting with the seventh character, "Cummings"
7) from the string.
Right( Extracts up to five characters from the end of the string. "mings"
Author.Text, 5 )
Single-column table
Each example in this section extracts strings from the Address column of this data
source, named People, and returns a single-column table that contains the results:
Name Address
Step-by-step example
1. Import or create a collection named Inventory, and show it in a gallery, as the first
procedure in Show images and text in a gallery describes.
2. Set the Text property of the lower label in the gallery to this function:
Right(ThisItem.ProductName, 3)
The label shows the last three characters of each product name.
Average, Max, Min, StdevP, Sum, and
VarP functions in Power Apps
Article • 02/23/2023 • 2 minutes to read
Description
The Average function calculates the average, or arithmetic mean, of its arguments.
Fields of the record currently being processed are available within the formula. Use the
ThisRecord operator or simply reference fields by name as you would any other value.
The As operator can also be used to name the record being processed which can help
make your formula easier to understand and make nested records accessible. For more
information, see the examples below and working with record scope.
These functions operate on numeric values only. Other types of values, such as strings or
records, are ignored. Use the Value function to convert a string into a number.
The Average, Max, Min, and Sum functions can be delegated when used with a data
source that supports delegation for these functions. However, StdevP and VarP can't be
delegated for any data sources. If delegation is not supported, only the first portion of
the data will be retrieved and then the function applied locally. The result may not
represent the complete story. A delegation warning will appear at authoring time to
remind you of this limitation and to suggest switching to delegable alternatives where
possible. For more information, see the delegation overview.
Syntax
Average( NumericalFormula1, [ NumericalFormula2, ... ] )
Examples
Step by step
Let's say that you had a data source named Sales that contained a CostPerUnit column
and a UnitsSold column, and you set the Text property of a label to this function:
The label would show total sales by multiplying the values in those columns for each
record and then adding the results from all records together:
As a different example, let's say that you had sliders that were named Slider1, Slider2,
and Slider3 and a label with its Text property set to this formula:
Sum(Slider1.Value, Slider2.Value, Slider3.Value): The label would show the sum of all
values to which the sliders were set.
Description
The Day function returns the day component of a Date/Time value, ranging from 1 to
31.
The Month function returns the month component of a Date/Time value, ranging from
1 to 12.
The Year function returns the year component of a Date/Time value, starting with 1900.
The Hour function returns the hour component of a Date/Time value, ranging from 0
(12:00 AM) to 23 (11:00 PM).
The Minute function returns the minute component of a Date/Time value, ranging from
0 to 59.
The Second function returns the second component of a Date/Time value, ranging from
0 to 59.
The Weekday function returns the weekday of a Date/Time value. By default, the result
ranges from 1 (Sunday) to 7 (Saturday). You can specify a different range with an
Microsoft Excel Weekday function code or a StartOfWeek enumeration value:
Syntax
Day( DateTime )
Month( DateTime )
Year( DateTime )
Hour( DateTime )
Minute( DateTime )
Second( DateTime )
Examples
For the following example, the current time is 3:59:37 PM on Thursday, April 9, 2015.
Description
The Mod function returns the remainder after a number is divided by a divisor.
Syntax
Mod( Number, Divisor )
Description
The Day function returns the day component of a Date/Time value, ranging from 1 to
31.
The Month function returns the month component of a Date/Time value, ranging from
1 to 12.
The Year function returns the year component of a Date/Time value, starting with 1900.
The Hour function returns the hour component of a Date/Time value, ranging from 0
(12:00 AM) to 23 (11:00 PM).
The Minute function returns the minute component of a Date/Time value, ranging from
0 to 59.
The Second function returns the second component of a Date/Time value, ranging from
0 to 59.
The Weekday function returns the weekday of a Date/Time value. By default, the result
ranges from 1 (Sunday) to 7 (Saturday). You can specify a different range with an
Microsoft Excel Weekday function code or a StartOfWeek enumeration value:
Syntax
Day( DateTime )
Month( DateTime )
Year( DateTime )
Hour( DateTime )
Minute( DateTime )
Second( DateTime )
Examples
For the following example, the current time is 3:59:37 PM on Thursday, April 9, 2015.
Overview
Most apps contain multiple screens. Use the Back and Navigate function to change
which screen is displayed. For example, set the OnSelect property of a button to a
formula that includes a Navigate function if you want to show a different screen when a
user selects that button. In that formula, you can specify a visual transition, such as Fade,
to control how one screen changes to another.
Back and Navigate change only which screen is displayed. Screens that aren't currently
displayed continue to operate behind the scenes. You can build formulas that refer to
properties of controls on other screens. For example, a user can change the value of a
slider on one screen, navigate to a different screen that uses that value in a formula, and
determine how it affects what happens in the new screen. The user can then navigate
back to the original screen and confirm that the slider has kept its value.
Context variables are also preserved when a user navigates between screens. You can
use Navigate to set one or more context variables for the screen that the formula will
display, which is the only way to set a context variable from outside the screen. You can
use this approach to pass parameters to a screen. If you've used another programming
tool, this approach is similar to passing parameters to procedures.
Use the App object's StartScreen property to control the first screen to be displayed.
Navigate
In the first argument, specify the name of the screen to display.
In the second argument, specify how the old screen changes to the new screen:
You can use Navigate to create or update context variables of the new screen. As an
optional third argument, pass a record that contains the context-variable name as a
column name and the new value for the context variable. This record is the same as the
record that you use with the UpdateContext function.
Set the OnHidden property of the old screen, the OnVisible property of the new screen,
or both to make additional changes during the transition. The App.ActiveScreen
property will be updated to reflect the change.
Navigate normally returns true but will return false if an error is encountered.
Context variables for navigation are explained in the article navigate between screens.
Back
The Back function returns to the screen that was most recently displayed.
For each Navigate call, the app tracks the screen that appeared and the transition. You
can use successive Back calls to return all the way to the screen that appeared when the
user started the app.
When the Back function runs, the inverse transition is used by default. For example, if a
screen appeared through the CoverRight transition, Back uses UnCover (which is to the
left) to return. Fade and None are their own inverses. Pass an optional argument to Back
to force a specific transition.
Back normally returns true but returns false if the user hasn't navigated to another
screen since starting the app.
Syntax
Back( [ Transition ] )
Transition - Optional. The visual transition to use between the current screen and
the previous screen. Refer to the list of valid values for this argument earlier in this
article. By default, the transition through which a screen returns is the inverse of
the transition through which it appeared.
Examples
Formula Description Result
Navigate( Details ) Displays the Details The Details screen appears quickly.
screen with no
transition or change in
value for a context
variable.
Navigate( Details, Displays the Details The current screen fades away to show
ScreenTransition.Fade ) screen with a Fade the Details screen.
transition. No value of a
context variable is
changed.
Formula Description Result
Navigate( Details, Displays the Details The current screen fades away to show
ScreenTransition.Fade, screen with a Fade the Details screen, and the context
{ ID: 12 } ) transition, and updates variable ID on that screen is set to 12.
the value of the ID
context variable to 12.
Navigate( Details, Displays the Details The current screen fades away to show
ScreenTransition.Fade, screen with a Fade the Details screen. The context variable
{ ID: 12 , Shade: Color.Red } transition. Updates the ID on the Details screen is set to 12, and
) value of the ID context the context variable Shade is set to
variable to 12, and Color.Red. If you set the Fill property of
updates the value of the a control on the Details screen to Shade,
Shade context variable that control would display as red.
to Color.Red.
Back() Displays the previous Displays the previous screen through the
screen with the default inverse transition of the transition
return transition. through which the current screen
appeared.
Back( Displays the previous Displays the previous screen through the
ScreenTransition.Cover ) screen with the Cover Cover transition, regardless of the
transition. transition through which the current
screen appeared.
Step-by-step
1. Create a blank app.
4. On Screen2, add a button, and set its OnSelect property to this formula:
Power Apps
Screen1 appears with a white background through a transition that covers to the
left.
6. On Screen1, add a button, and set its OnSelect property to this formula:
Power Apps
Back()
The second screen appears with a gray background through a transition that
uncovers to the right (the inverse of Cover).
8. Select the button on each screen repeatedly to bounce back and forth.
See also
Using context variables
EditForm, NewForm, SubmitForm,
ResetForm, and ViewForm functions in
Power Apps
Article • 02/23/2023 • 5 minutes to read
View, edit, or create an item, save the contents, and reset the controls in an Edit form
control.
Overview
These functions change the state of the Edit form control. The form control can be in
one of these modes:
Mode Description
FormMode.Edit The form is populated with an existing record and the user can modify the
values of the fields. Once complete, the user can save the changes to the
record.
FormMode.New The form is populated with default values and the user can modify the values
of the fields. Once complete, the user can add the record to the data source.
FormMode.View The form is populated with an existing record but the user cannot modify the
values of the fields.
Description
These functions are often invoked from the OnSelect formula of a Button or Image
control so that the user can save edits, abandon edits, or create a record. You can use
controls and these functions together to create a complete solution.
SubmitForm
Use the SubmitForm function in the OnSelect property of a Button control to save any
changes in a Form control to the data source.
Before submitting any changes, this function checks for validation issues with any field
that's marked as required or that has one or more constraints on its value. This behavior
matches that of the Validate function.
SubmitForm also checks the Valid property of the Form, which is an aggregation of all
the Valid properties of the Card controls that the Form control contains. If a problem
occurs, the data isn't submitted, and the Error and ErrorKind properties of the Form
control are set accordingly.
If successful, the Form's OnSuccess behavior runs, and the Error and ErrorKind
properties are cleared. If the form was in FormMode.New mode, it is returned to
FormMode.Edit mode.
If unsuccessful, the Form's OnFailure behavior runs, and the Error and ErrorKind
properties are set accordingly. The mode of the form is unchanged.
EditForm
The EditForm function changes the Form control's mode to FormMode.Edit. In this
mode, the contents of the Form control's Item property are used to populate the form.
If the SubmitForm function runs when the form is in this mode, a record is changed, not
created. FormMode.Edit is the default for the Form control.
NewForm
The NewForm function changes the Form control's mode to FormMode.New. In this
mode, the contents of the Form control's Item property are ignored, and the default
values of the Form's DataSource property populate the form. If the SubmitForm
function runs when the form is in this mode, a record is created, not changed.
ResetForm
The ResetForm function resets the contents of a form to their initial values, before the
user made any changes. If the form is in FormMode.New mode, the form is reset to
FormMode.Edit mode. The OnReset behavior of the form control also runs. You can also
reset individual controls with the Reset function but only from within the form.
ViewForm
The ViewForm function changes the Form control's mode to FormMode.View. In this
mode, the contents of the Form control's Item property are used to populate the form.
The SubmitForm and ResetForm functions have no effect when in this mode.
DisplayMode Property
The current mode can be read through the Mode property. The mode also determines
the value of the DisplayMode property, which can be used by data cards and controls
within the form control. Often, the data card's DisplayMode property will be set to
Parent.DisplayMode (referencing the form) as will the control's DisplayMode property
(referencing the data card):
FormMode.Edit DisplayMode.Edit Data cards and controls are editable, ready to accept
changes to a record.
FormMode.New DisplayMode.Edit Data cards and controls are editable, ready to accept a
new record.
FormMode.View DisplayMode.View Data cards and controls are not editable and optimized
for viewing.
Syntax
SubmitForm( FormName )
EditForm( FormName )
NewForm( FormName )
ResetForm( FormName )
FormName - Required. Form control to reset to initial values. Also switches the
form from FormMode.New mode to FormMode.Edit mode.
ViewForm( FormName )
1. Add a Button control, set its Text property to show Save, and set its OnSelect
property to this formula:
SubmitForm( EditForm )
2. Set the OnFailure property of a Form control to blank and its OnSuccess property
to this formula:
Back()
3. Name a Label control ErrorText, and set its Text property to this formula:
EditForm.Error
When the user selects the Save button, any changes in the Form control are
submitted to the underlying data source.
If the submission succeeds, any changes are saved or, if the Form control is in
New mode, a record is created. ErrorText is blank and the previous screen
reappears.
If the submission fails, ErrorText shows a user-friendly error message, and the
current screen remains visible so that the user can correct the problem and
try again.
4. Add a Button control, set its Text property to show Cancel, and set its OnSelect
property to this formula:
When the user selects the Cancel button, the values in the Form control are reset
to what they were before the user started to edit it, the previous screen reappears,
and the Form control is returned to Edit mode if it was in New mode.
5. Add a Button control, set its Text property to show New, and set its OnSelect
property to this formula:
When the user selects the New button, the Form control switches to New mode,
the default values for the Form control's data source populate that control, and the
screen that contains the Form control appears. When the SubmitForm function
runs, a record is created instead of updated.
And, Or, and Not functions in Power
Apps
Article • 02/23/2023 • 2 minutes to read
Boolean logic functions, commonly used to manipulate the results of comparisons and
tests.
Description
The And function returns true if all of its arguments are true.
The Not function returns true if its argument is false; it returns false if its argument is
true.
These functions work the same way as they do in Excel. You can also use operators to
perform these same operations, using either Visual Basic or JavaScript syntax:
Or( x, y ) x Or y x || y
Not( x ) Not x !x
These functions work with logical values. You can't pass them a number or a string
directly; instead, you must make a comparison or a test. For example, this logical
formula x > 1 evaluates to the Boolean value true if x is greater than 1. If x is less than 1,
the formula evaluates to false.
Syntax
And( LogicalFormula1, LogicalFormula2 [, LogicalFormula3, ... ] )
Not( LogicalFormula )
Examples
The examples in this section use these global variables:
a = false
b = true
x = 10
y = 100
s = "Hello World"
To create these global variables in an app, insert a Button control, and set its OnSelect
property to this formula:
Power Apps
Select the button (by clicking it while you hold down the Alt key), and then set the Text
property of a Label control to a formula in the first column of the next table.
And( a, b ) Tests the values of a and b. One of the arguments is false, so the false
function returns false.
a And b Same as the previous example, using Visual Basic notation. false
Or( a, b ) Tests the values of a and b. One of the arguments is true, so the true
function returns true.
Not( a ) Tests the value of a. The argument is false, so the function returns true
the opposite result.
Not a Same as the previous example, using Visual Basic notation. true
Len( s ) < 20 Tests whether the length of s is less than 20 and whether it isn't a true
And Not IsBlank( s ) blank value. The length is less than 20, and the value isn't blank.
Therefore, the result is true.
Formula Description Result
Or( Len( s ) < 10, Tests whether the length of s is less than 10, whether x is less than true
x < 100, y < 100 ) 100, and whether y is less than 100. The first and third arguments
are false, but the second one is true. Therefore, the function
returns true.
Not IsBlank( s ) Tests whether s is blank, which returns false. Not returns the true
opposite of this result, which is true.
Notify function in Power Apps
Article • 02/23/2023 • 2 minutes to read
Description
The Notify function displays a banner message to the user at the top of the screen. The
notification will remain until the user dismisses it or the timeout expires which defaults
to 10 seconds.
An appropriate color and icon are used depending on the type of the message. The type
is specified by the second argument to the function:
7 Note
Messages are shown both when authoring your app and when end users are using your
app.
Notify can be paired with the IfError function to detect and report errors with a custom
error message.
Power Apps can also send push notifications using an entirely different mechanism from
Notify. For more information see Send a notification in Power Apps.
Note: This function was previously named ShowError when it could only display error
messages.
Syntax
Notify( Message [, NotificationType [ , Timeout ] ] )
Examples
Step by step
1. Add a Button control to your screen.
Power Apps
Each time the button is clicked, the message Hello, World is displayed to the user
as informational. It will dismiss automatically in 10 seconds (default timeout) if the
user does not dismiss it or press the button again.
4. Change the type of message to indicate an error. Add a second argument to our
formula:
Power Apps
Notify( "Hello, World", NotificationType.Error )
Now each time the button is clicked, the message Hello, World is displayed to the
user as an error. It will dismiss automatically in 10 seconds (default timeout) if the
user does not dismiss it or press the button again.
6. Change the type of message to indicate a warning. Change the second argument
in our formula:
Power Apps
Now each time the button is clicked, the message Hello, World is displayed to the
user as a warning. It will dismiss automatically in 4 seconds (4,000 milliseconds) if
the user does not dismiss it or press the button again.
8. Change the type of message to indicate success. Change the second argument in
our formula:
Power Apps
Now each time the button is clicked, the message Hello, World is displayed to the
user as success. With a 0 timeout, the notification will only be dismissed by the
user or by pressing the button again.
Now, Today, IsToday, UTCNow,
UTCToday, IsUTCToday functions in
Power Apps
Article • 02/23/2023 • 4 minutes to read
Returns the current date and time, and tests whether a date/time value is today.
Description
The Now function returns the current date and time as a date/time value.
The Today function returns the current date as a date/time value. The time portion is
midnight. Today has the same value throughout a day, from midnight today to midnight
tomorrow.
The IsToday function tests whether a date/time value is between midnight today and
midnight tomorrow. This function returns a Boolean (true or false) value.
Now, Today, and IsToday functions work with the local time of the current user.
UTCNow, UTCToday, and IsUTCToday functions are the same as their non-UTC
countrparts but work with time zone independent values and use Coordinated Universal
Time (UTC).
7 Note
More information: Work with formula table columns in Dataverse for Teams
See Date, Time, and DateTime in the data types documentation and working with dates
and times for more information.
Volatile Functions
Now, Today, UTCNow, and UTCToday are volatile functions. These functions return a
different value for each evaluation.
When used in a data flow formula, a volatile function will only return a different value if
the formula in which it appears is reevaluated. If nothing else changes in the formula
then it will have the same value throughout the execution of your app.
For example, a label control with Label1.Text = Now() will not change while your app is
active. Only closing and reopening the app will result in a new value.
The function will be reevaluated if it is part of a formula in which something else has
changed. For example, if we change our example to involve a slider control with
Label1.Text = DateAdd( Now(), Slider1.Value, Minutes ) then the current time is
retrieved each time the Slider control's value changes and the label's text property is
reevaluated.
When used in a behavior formula, volatile functions will be evaluated each time the
behavior formula is evaluated. See below for an example.
Syntax
Now()
Today()
IsToday( DateTime )
UTCNow()
UTCToday()
IsUTCToday( TimeZoneIndependentTime )
Text( Now(), Retrieves the current date and time in the user's time "07/11/2021
"mm/dd/yyyy hh:mm:ss" ) zone, and displays it as a string. 20:58:00"
Text( Today(), Retrieves the current date only, leaving the time "07/12/2021
"mm/dd/yyyy hh:mm:ss" ) portion as midnight, and displays it as a string. 00:00:00"
IsToday( Now() ) Tests whether the current date and time is between true
midnight today and midnight tomorrow.
IsToday( Today() ) Tests whether the current date is between midnight true
today and midnight tomorrow.
Text( DateAdd( Now(), 12 Retrieves the current date and time, adds 12 days to "07/23/2021
), "mm/dd/yyyy the result, and displays it as a string. 20:58:00"
hh:mm:ss" )
Text( DateAdd( Today(), 12 Retrieves the current date, adds 12 days to the result, "07/23/2021
), "mm/dd/yyyy and displays it as a string. 00:00:00"
hh:mm:ss" )
IsToday( DateAdd( Now(), Tests whether the current date and time, plus 12 false
12 ) ) days, is between midnight today and midnight
tomorrow.
IsToday( DateAdd( Tests whether the current date, plus 12 days, is false
Today(), 12 ) ) between midnight today and midnight tomorrow.
Hour( UTCNow() ) Retrieves the current date and time in UTC and 4
extracts the hour only, which is 8 hours ahead of
local time.
Day( UTCToday() ) Retrives the current date only in UTC and extracts the 12
day, which is 1 day ahead of local time.
IsUTCToday( UTCNow() ) Tests whether the current date and time is between true
midnight today and midnight tomorrow, all in UTC
time.
IsUTCToday( UTCToday() ) Tests whether the current date is between midnight true
today and midnight tomorrow, all in UTC time.
The timer will run for one second, automatically start over, and continue that
pattern.
Whenever the timer starts over (after each second), this formula sets the
CurrentTime global variable to the current value of the Now function.
3. Add a Label control, and set its Text property to this formula:
Use the Text function to format the date and time however you want, or set this
property to just CurrentTime to show hours and minutes but not seconds.
4. Preview the app by pressing F5, and then start the timer by clicking or tapping it.
The label continually shows the current time, down to the second.
5. Set the timer's AutoStart property to true and its Visible property to false.
6. Set the screen's OnStart property so that the CurrentTime variable has a valid
value, as in this example:
Set(CurrentTime, Now())
The label appears as soon as the app starts (before the timer runs for a full
second).
Operators and Identifiers in Power Apps
Article • 03/01/2023 • 12 minutes to read
Some of these operators are dependent on the language of the author. For more
information about language support in canvas apps, see Global apps.
"..." Text string "Hello, World" Text strings are enclosed in double
quotes
. Property Slider1.Value
Extracts a property from a table,
Selector Color.Red
control, signal, or enumeration. For
Acceleration.X backward compatibility, ! may also be
used.
.
Decimal 1.23 Separator between whole and fractional
[language separator parts of a number. The character
dependent] depends on the language.
* 2*3 Multiplication
& String "hello" & " " & Makes multiple strings appear
concatenation "world" continuous
operator
&& or And Logical Price < 100 && Logical conjunction, equivalent to the
operators Slider1.Value = 20
And function
or Price < 100 And
Slider1.Value = 20
! or Not !(Price < 100) or Not Logical negation, equivalent to the Not
(Price < 100) function
,
List separator If( X < 10, "Low", Separates:
[language "Good" )
arguments in function calls
dependent] { X: 12, Y: 32 }
fields in a record
[ 1, 2, 3 ] records in a table
;
Formula Collect(T, A); Separate invocations of functions in
[language chaining Navigate(S1, "") behavior properties. The chaining
dependent] operator depends on the language.
7 Note
The @ operator can also be used to validate the type of the record object against a
data source. For example, Collect(coll,Account@{'Account Number: 1111')
The gallery shows all products except Callisto because the name of that product is
the only one that doesn't contain the letter you specified.
The gallery shows only Europa because only its name contains the letter that you
specified in the case that you specified.
ThisItem Gallery control
The default name for the current record in a Gallery or form
Edit form control
control.
Display form control
ThisRecord ForAll, Filter, With, The default name for the current record in ForAll and other
Sum and other record scope functions.
record scope
functions
As name Gallery control
Defines a name for the current record, replacing default
ForAll, Filter, With, ThisItem or ThisRecord. Use As to make formulas easier to
Sum and other understand and resolve ambiguity when nesting.
record scope
functions
ThisItem operator
For example, in the following Gallery control, the Items property is set to the Employees
data source (such as the Employees table included with the Northwind Traders sample):
Power Apps
Employees
The first item in the gallery is a template that is replicated for each employee. In the
template, the formula for the picture uses ThisItem to refer to the current item:
Power Apps
ThisItem.Picture
Power Apps
ThisRecord operator
ThisRecord is used in functions that have a record scope. For example, we can use the
Filter function with our gallery's Items property to only show first names that being with
M:
Power Apps
ThisRecord is optional and implied by using the fields directly, for example, in this case,
we could have written:
Power Apps
Although optional, using ThisRecord can make formulas easier to understand and may
be required in ambiguous situations where a field name may also be a relationship
name. ThisRecord is optional while ThisItem is always required.
Use ThisRecord to reference the whole record with Patch, Collect, and other record
scope functions. For example, the following formula sets the status for all inactive
employees to active:
Power Apps
ForAll( InactiveEmployees,
As operator
Use the As operator to name a record in a gallery or record scope function, overriding
the default ThisItem or ThisRecord. Naming the record can make your formulas easier
to understand and may be required in nested situations to access records in other
scopes.
For example, you can modify the Items property of our gallery to use As to identify that
we are working with an Employee:
Power Apps
Employees As Employee
The formulas for the picture and name are adjusted to use this name for the current
record:
Power Apps
Employee.Picture
Power Apps
Employee.'First Name' & " " & Employee.'Last Name'
As can also be used with record scope functions to replace the default name
ThisRecord. We can apply this to our previous example to clarify the record we're
working with:
Power Apps
When nesting galleries and record scope functions, ThisItem and ThisRecord always
refers to the inner most scope, leaving records in outer scopes unavailable. Use As to
make all record scopes available by giving each a unique name.
For example, this formula produces a chessboard pattern as a text string by nesting two
ForAll functions:
Power Apps
Concat(
Concat(
),
Value
) & Char(10)
),
Value
A similar example is possible with nested Gallery controls instead of ForAll functions.
Let's start with the vertical gallery for the Rank. This gallery control will have an Items
formula of:
Power Apps
Sequence(8) as Rank
Within this gallery, we'll place a horizontal gallery for the File, that will be replicated for
each Rank, with an Items property of:
Power Apps
Sequence(8) as File
And finally, within this gallery, we'll add a Label control that will be replicated for each
File and each Rank. We'll size it to fill the entire space and use the Fill property to
provide the color with this formula:
Power Apps
Method Description
By Any control can be referenced by name from anywhere within the app.
control
name For example, Label1.Fill refers to the fill property of the control who's name is Label1.
Self It's often convenient to reference another property of the same control when writing a
operator formula. Instead of using an absolute reference by name, it's easier and more portable
to use a relative reference to oneself. The Self operator provides that easy access to
the current control.
For example, Self.Fill refers to the fill color of the current control.
Parent Some controls host other controls, such as the Screen and Gallery controls. The
operator hosting control of the controls within it's called the parent. Like the Self operator, the
Parent operator provides an easy relative reference to the container control.
For example, Parent.Fill refers to the fill property of the control that is the container for
the current control.
Self and Parent are operators and not properties on the controls themselves. Referring
to Parent.Parent, Self.Parent or Parent.Self is not supported.
Identifier names
The names of variables, data sources, columns, and other objects can contain any
Unicode .
Use single quotes around a name that contains a space or other special character.
Use two single quotes together to represent one single quote in the name. Names that
don't contain special characters don't require single quotes.
Here are some example column names you might encounter in a table, and how they're
represented in a formula:
SimpleName SimpleName
NameWith123Numbers NameWith123Numbers
Display name - A name that is user-friendly and intended to be seen by end users.
This name may not be unique, may change over time, may contain spaces and any
Unicode character, and may be localized into different languages. Corresponding
to the example above, the display name may be Custom Field with space in
between the words.
Since display names are easier to understand, Canvas apps will suggest them as choices
and not suggest logical names. Although logical names aren't suggested, they can still
be used if typed indirectly.
For example, imagine you've added a Custom Field to a table in Dataverse. A logical
name will be assigned for you by the system, which you can modify only when creating
the field. The result would look similar to:
When authoring a reference to a field of Accounts, the suggestion will be made to use
'Custom Field' since this is the display name. Single quotes must be used because this
name has a space in it:
After selecting the suggestion, 'Custom Field' is shown in the formula bar and the data is
retrieved:
Although it isn't suggested, we could also use the logical name for this field. This will
result in the same data being retrieved. Single quotes are not required since this name
doesn't contain spaces or special characters:
Behind the scenes, a mapping is maintained between the display names seen in
formulas and the underlying logical names. Since logical names must be used to interact
with the data source, this mapping is used to convert from the current display name to
the logical name automatically and that is what is seen in the network traffic. This
mapping is also used to convert back to logical names to switch into new display names,
for example, if a display name changes or a maker in a different language edits the app.
7 Note
Logical names are not translated when moving an app between environments. For
Dataverse system table and field names, this should not be a problem as logical
names are consistent across environments. But any custom fields, such as
cra3a_customfield in this example above, may have a different environment prefix
(cra3a in this case). Display names are preferred as they can be matched against
display names in the new environment.
Name disambiguation
Since display names aren't unique, the same display name may appear more than once
in the same table. When this happens, the logical name will be added to the end of the
display name in parenthesis for one of more of the conflicting names. Building on the
example above, if there was a second field with the same display name of Custom Field
with a logical name of cra3a_customfieldalt then the suggestions would show:
Name disambiguation strings are added in other situations where name conflicts occur,
such as the names of table, choices, and other Dataverse items.
Disambiguation operator
Some functions create record scopes for accessing the fields of table while processing
each record, such as Filter, AddColumns, and Sum. Field names added with the record
scope override the same names from elsewhere in the app. When this happens, you can
still access values from outside the record scope with the @ disambiguation operator:
To access values from nested record scopes, use the @ operator with the name of
the table being operated upon using this pattern:
Table[@FieldName]
To access global values, such as data sources, collections, and context variables,
use the pattern [@ObjectName] (without a table designation).
Boolean logic functions, commonly used to manipulate the results of comparisons and
tests.
Description
The And function returns true if all of its arguments are true.
The Not function returns true if its argument is false; it returns false if its argument is
true.
These functions work the same way as they do in Excel. You can also use operators to
perform these same operations, using either Visual Basic or JavaScript syntax:
Or( x, y ) x Or y x || y
Not( x ) Not x !x
These functions work with logical values. You can't pass them a number or a string
directly; instead, you must make a comparison or a test. For example, this logical
formula x > 1 evaluates to the Boolean value true if x is greater than 1. If x is less than 1,
the formula evaluates to false.
Syntax
And( LogicalFormula1, LogicalFormula2 [, LogicalFormula3, ... ] )
Not( LogicalFormula )
Examples
The examples in this section use these global variables:
a = false
b = true
x = 10
y = 100
s = "Hello World"
To create these global variables in an app, insert a Button control, and set its OnSelect
property to this formula:
Power Apps
Select the button (by clicking it while you hold down the Alt key), and then set the Text
property of a Label control to a formula in the first column of the next table.
And( a, b ) Tests the values of a and b. One of the arguments is false, so the false
function returns false.
a And b Same as the previous example, using Visual Basic notation. false
Or( a, b ) Tests the values of a and b. One of the arguments is true, so the true
function returns true.
Not( a ) Tests the value of a. The argument is false, so the function returns true
the opposite result.
Not a Same as the previous example, using Visual Basic notation. true
Len( s ) < 20 Tests whether the length of s is less than 20 and whether it isn't a true
And Not IsBlank( s ) blank value. The length is less than 20, and the value isn't blank.
Therefore, the result is true.
Formula Description Result
Or( Len( s ) < 10, Tests whether the length of s is less than 10, whether x is less than true
x < 100, y < 100 ) 100, and whether y is less than 100. The first and third arguments
are false, but the second one is true. Therefore, the function
returns true.
Not IsBlank( s ) Tests whether s is blank, which returns false. Not returns the true
opposite of this result, which is true.
Launch and Param functions in Power
Apps
Article • 03/04/2023 • 8 minutes to read
Launch
Launches a webpage or a canvas app. The function supports:
Address (required), the URL of the webpage or App ID of the canvas app.
Parameters (optional), named values to pass to the webpage or canvas app. In a
canvas app, parameters can be read with the Param function.
Target (optional), the browser tab in which to launch the webpage or canvas app.
Address
Webpages are launched via a URL address. For example:
Power Apps
Launch( "https://bing.com" )
You can launch canvas apps with Web link or App ID. To find these values for an app:
1. Go to Power Apps .
You can also select ... (More Commands) and then select Details from the drop-
down menu.
5. Copy Web link or App ID.
The Web link can be used in any web page and will launch the canvas app. It can also be
used with the Launch function.
The App ID can be used with the Launch function, but must be prefixed with
/providers/Microsoft.PowerApps/apps/ . For example:
Power Apps
Launch( "/providers/Microsoft.PowerApps/apps/f342faaf-5f82-4ace-a64b-
7c1b01499231" )
Native apps on a device can't be launched directly. There may be indirect options
available on some platforms, such as a native app installing a custom URL scheme or
registering with the web browser to offer an option for specific web sites.
Parameters
Launch can pass parameters to the webpage or canvas app. Parameters can be provided
in two ways:
Power Apps
Power Apps
This form can be easier to work with as it makes the association between name
and value clearer. It's the only form that supports the optional LaunchTarget
argument.
The address and parameters are URL encoded before being passed to replace certain
non-alphanumeric characters with % and a hexadecimal number as if the EncodeUrl
function has been used on each.
When launching a webpage, a query string of parameters can be included at the end
of the URL address. Any additional parameters provided to Launch will be added to the
end of the query string. Query strings don't work when launching a canvas app.
Target
Use the LaunchTarget argument to specify the target browser window in which to open
the webpage or app. Use one of the following LaunchTarget enum values or provide a
custom window name.
LaunchTarget enum Description
name Instead of an enum value, use your own text string to name the window or
tab. Self is an internal only name that is only used by the Launch function.
It has no impact on nor will it match the title of the window that your
users see. If a window or tab with the given name already exists, its
contents will be replaced. Otherwise, a new window or tab will be created.
name can't begin with the underscore character "_".
New is the default enum when running in a web browser with Replace and name as
available options. In a mobile player, New is the default for webpages with name as an
available option; while the current canvas app will always be replaced by another canvas
app.
7 Note
Using a LaunchTarget with any value other than New in embedded scenarios
(for example, Power BI or SharePoint) is not supported and may result in
unexpected behavior. In the future, this behavior may change, or may cause
an error.
Param
The Param function retrieves a parameter passed to the app when it was launched. If the
named parameter wasn't passed, Param returns blank.
When launching a canvas app from another canvas app, use the Parameter
arguments to the Launch function. Parameter names and values will be
automatically URL encoded.
When launching a canvas app from a web page, add parameters to the query
string of the canvas app web link. This involves adding
¶metername=parametervalue assuming the query string has already been
started for the tenantId . For example, adding &First%20Name=Vicki&category=3
would pass two parameters: First Name with a value of "Vicki" and category with
a value of "3" (value type is text). The parameter name and value must be URL
encoded if they contain spaces or special characters, similar to using the
EncodeURL function.
Param names are case-sensitive.
Param names and values will be automatically URL decoded for use in your app.
Even if the parameter contains a number, the type returned by Param will always
be a text string. Conversion to other types will automatically occur or use explicit
conversions such as the Value function to convert explicitly to a number.
Syntax
Launch( Address [, ParameterName1, ParameterValue1, ... ] )
Param( ParameterName )
Reserved parameters
The following keywords are reserved (regardless of case) for internal use, and shouldn't
be used as a custom parameter in the Param() function:
amp%3Bauthmode
amp%3Benableonbehalfof
amp%3Bhidenavbar
amp%3Blocale
appmetadataversion
authmode
channeltype
cordovapath
correlationid
debug
delegatelaunchurl
delegatelaunchurl
disablepreviewredirect
embedderorigin
enableonbehalfof
groupid
hideappsplash
hidenavbar
hint
hostclienttype
hostmode
iframecontainerid
isfullscreen
ispreviewmode
loader
loaderType
locale
location
packagekind
packageproperties
playerresourcespath
playersessionid
powerappslanguage
screencolor
sdkversion
site
skipappmetadata
skipiframecreation
skiplaunchappcache
source
standaloneconsent
teamid
teamtype
tenantId
theme
uselocalpackagehostresources
userteamrole
Examples
Simple Launch
From a canvas app to a web page:
Formula Description
Launch( "http://bing.com/search",
Opens the webpage http://bing.com/search?
"q", "Power Apps", "count", 1 ) q=Power%20Apps&count=1 . A new window or tab is
opened.
Launch( "http://bing.com/search",
The same as the previous examples using the equivalent
{ q: "Power Apps", count: 1 } ) record notation. A new window or tab is opened.
Launch( "http://bing.com/search",
The same as the previous examples, replacing the current
{ q: "Power Apps", count: 1 },
window or tab with the result if running in a web browser.
LaunchTarget.Replace )
Launch( "http://bing.com/search",
The same as the previous example, creating or replacing
{ q: "Power Apps", count: 1 },
the contents of the window or tab named Search Results.
"Search Results" )
Update the app ID, screen name, and record number as appropriate.
Power Apps
Launch( "/providers/Microsoft.PowerApps/apps/YOUR-APP-ID",
Update the app ID, tenant ID, screen name, and record number as appropriate.
HTML
<html>
<body>
<a
href="https://apps.powerapps.com/play/YOUR-APP-ID?tenantId=YOUR-
TENANT-ID&Navigate=Second%20Screen&Record=34"
>
</a>
</body>
</html>
Simple Param
Simple launch examples above to launch canvas app from web page or from another
canvas app show simple examples for Param function:
Param( "Navigate" ) The Navigate parameter was provided when the app was "Second
launched and is returned. Screen"
Param( "Record" ) The Record parameter was provided when the app was "34"
launched. Even though it was passed in as a number to the
Launch function, the result from Param will be a text string that
can be implicitly or explicitly converted to other types.
Param( "User" ) The User parameter wasn't provided. A blank value is returned blank
that can be tested with the IsBlank function.
Example - Launch
1. Go to Power Apps .
6. From the properties pane on the right-side, select Color as white and set Border
thickness at 1.
7. Select the Text property from right-side and enter text as Surface tablets in news.
your choice.
10. Save and publish the app.
12. Select label Surface tablets in news to launch news search with keywords Microsoft
Surface tablets.
Tip
For scalability, you can replace the manually entered keywords in Launch function
with variables.
Example - Param
1. Go to Power Apps .
7. Enter formula as Param("browser") . You can also use a different parameter of your
choice.
8. Save and publish the app.
11. Paste the app web link in the browser and append &browser=Microsoft%20Edge at
the end.
12. When your app launches, the label shows the parameter value passed.
13. Close the app player and edit the app.
7 Note
Replace the TechSpecs control name in the If function with the name of a
screen control in your own app if you're not using the Product Showcase app
template.
19. Paste the app web link in the browser and append &screen=techspecs at the end.
See also
Canvas app formula reference
Operators and Identifiers in Power Apps
Article • 03/01/2023 • 12 minutes to read
Some of these operators are dependent on the language of the author. For more
information about language support in canvas apps, see Global apps.
"..." Text string "Hello, World" Text strings are enclosed in double
quotes
. Property Slider1.Value
Extracts a property from a table,
Selector Color.Red
control, signal, or enumeration. For
Acceleration.X backward compatibility, ! may also be
used.
.
Decimal 1.23 Separator between whole and fractional
[language separator parts of a number. The character
dependent] depends on the language.
* 2*3 Multiplication
& String "hello" & " " & Makes multiple strings appear
concatenation "world" continuous
operator
&& or And Logical Price < 100 && Logical conjunction, equivalent to the
operators Slider1.Value = 20
And function
or Price < 100 And
Slider1.Value = 20
! or Not !(Price < 100) or Not Logical negation, equivalent to the Not
(Price < 100) function
,
List separator If( X < 10, "Low", Separates:
[language "Good" )
arguments in function calls
dependent] { X: 12, Y: 32 }
fields in a record
[ 1, 2, 3 ] records in a table
;
Formula Collect(T, A); Separate invocations of functions in
[language chaining Navigate(S1, "") behavior properties. The chaining
dependent] operator depends on the language.
7 Note
The @ operator can also be used to validate the type of the record object against a
data source. For example, Collect(coll,Account@{'Account Number: 1111')
The gallery shows all products except Callisto because the name of that product is
the only one that doesn't contain the letter you specified.
The gallery shows only Europa because only its name contains the letter that you
specified in the case that you specified.
ThisItem Gallery control
The default name for the current record in a Gallery or form
Edit form control
control.
Display form control
ThisRecord ForAll, Filter, With, The default name for the current record in ForAll and other
Sum and other record scope functions.
record scope
functions
As name Gallery control
Defines a name for the current record, replacing default
ForAll, Filter, With, ThisItem or ThisRecord. Use As to make formulas easier to
Sum and other understand and resolve ambiguity when nesting.
record scope
functions
ThisItem operator
For example, in the following Gallery control, the Items property is set to the Employees
data source (such as the Employees table included with the Northwind Traders sample):
Power Apps
Employees
The first item in the gallery is a template that is replicated for each employee. In the
template, the formula for the picture uses ThisItem to refer to the current item:
Power Apps
ThisItem.Picture
Power Apps
ThisRecord operator
ThisRecord is used in functions that have a record scope. For example, we can use the
Filter function with our gallery's Items property to only show first names that being with
M:
Power Apps
ThisRecord is optional and implied by using the fields directly, for example, in this case,
we could have written:
Power Apps
Although optional, using ThisRecord can make formulas easier to understand and may
be required in ambiguous situations where a field name may also be a relationship
name. ThisRecord is optional while ThisItem is always required.
Use ThisRecord to reference the whole record with Patch, Collect, and other record
scope functions. For example, the following formula sets the status for all inactive
employees to active:
Power Apps
ForAll( InactiveEmployees,
As operator
Use the As operator to name a record in a gallery or record scope function, overriding
the default ThisItem or ThisRecord. Naming the record can make your formulas easier
to understand and may be required in nested situations to access records in other
scopes.
For example, you can modify the Items property of our gallery to use As to identify that
we are working with an Employee:
Power Apps
Employees As Employee
The formulas for the picture and name are adjusted to use this name for the current
record:
Power Apps
Employee.Picture
Power Apps
Employee.'First Name' & " " & Employee.'Last Name'
As can also be used with record scope functions to replace the default name
ThisRecord. We can apply this to our previous example to clarify the record we're
working with:
Power Apps
When nesting galleries and record scope functions, ThisItem and ThisRecord always
refers to the inner most scope, leaving records in outer scopes unavailable. Use As to
make all record scopes available by giving each a unique name.
For example, this formula produces a chessboard pattern as a text string by nesting two
ForAll functions:
Power Apps
Concat(
Concat(
),
Value
) & Char(10)
),
Value
A similar example is possible with nested Gallery controls instead of ForAll functions.
Let's start with the vertical gallery for the Rank. This gallery control will have an Items
formula of:
Power Apps
Sequence(8) as Rank
Within this gallery, we'll place a horizontal gallery for the File, that will be replicated for
each Rank, with an Items property of:
Power Apps
Sequence(8) as File
And finally, within this gallery, we'll add a Label control that will be replicated for each
File and each Rank. We'll size it to fill the entire space and use the Fill property to
provide the color with this formula:
Power Apps
Method Description
By Any control can be referenced by name from anywhere within the app.
control
name For example, Label1.Fill refers to the fill property of the control who's name is Label1.
Self It's often convenient to reference another property of the same control when writing a
operator formula. Instead of using an absolute reference by name, it's easier and more portable
to use a relative reference to oneself. The Self operator provides that easy access to
the current control.
For example, Self.Fill refers to the fill color of the current control.
Parent Some controls host other controls, such as the Screen and Gallery controls. The
operator hosting control of the controls within it's called the parent. Like the Self operator, the
Parent operator provides an easy relative reference to the container control.
For example, Parent.Fill refers to the fill property of the control that is the container for
the current control.
Self and Parent are operators and not properties on the controls themselves. Referring
to Parent.Parent, Self.Parent or Parent.Self is not supported.
Identifier names
The names of variables, data sources, columns, and other objects can contain any
Unicode .
Use single quotes around a name that contains a space or other special character.
Use two single quotes together to represent one single quote in the name. Names that
don't contain special characters don't require single quotes.
Here are some example column names you might encounter in a table, and how they're
represented in a formula:
SimpleName SimpleName
NameWith123Numbers NameWith123Numbers
Display name - A name that is user-friendly and intended to be seen by end users.
This name may not be unique, may change over time, may contain spaces and any
Unicode character, and may be localized into different languages. Corresponding
to the example above, the display name may be Custom Field with space in
between the words.
Since display names are easier to understand, Canvas apps will suggest them as choices
and not suggest logical names. Although logical names aren't suggested, they can still
be used if typed indirectly.
For example, imagine you've added a Custom Field to a table in Dataverse. A logical
name will be assigned for you by the system, which you can modify only when creating
the field. The result would look similar to:
When authoring a reference to a field of Accounts, the suggestion will be made to use
'Custom Field' since this is the display name. Single quotes must be used because this
name has a space in it:
After selecting the suggestion, 'Custom Field' is shown in the formula bar and the data is
retrieved:
Although it isn't suggested, we could also use the logical name for this field. This will
result in the same data being retrieved. Single quotes are not required since this name
doesn't contain spaces or special characters:
Behind the scenes, a mapping is maintained between the display names seen in
formulas and the underlying logical names. Since logical names must be used to interact
with the data source, this mapping is used to convert from the current display name to
the logical name automatically and that is what is seen in the network traffic. This
mapping is also used to convert back to logical names to switch into new display names,
for example, if a display name changes or a maker in a different language edits the app.
7 Note
Logical names are not translated when moving an app between environments. For
Dataverse system table and field names, this should not be a problem as logical
names are consistent across environments. But any custom fields, such as
cra3a_customfield in this example above, may have a different environment prefix
(cra3a in this case). Display names are preferred as they can be matched against
display names in the new environment.
Name disambiguation
Since display names aren't unique, the same display name may appear more than once
in the same table. When this happens, the logical name will be added to the end of the
display name in parenthesis for one of more of the conflicting names. Building on the
example above, if there was a second field with the same display name of Custom Field
with a logical name of cra3a_customfieldalt then the suggestions would show:
Name disambiguation strings are added in other situations where name conflicts occur,
such as the names of table, choices, and other Dataverse items.
Disambiguation operator
Some functions create record scopes for accessing the fields of table while processing
each record, such as Filter, AddColumns, and Sum. Field names added with the record
scope override the same names from elsewhere in the app. When this happens, you can
still access values from outside the record scope with the @ disambiguation operator:
To access values from nested record scopes, use the @ operator with the name of
the table being operated upon using this pattern:
Table[@FieldName]
To access global values, such as data sources, collections, and context variables,
use the pattern [@ObjectName] (without a table designation).
) Important
Description
The ParseJSON function will parse a valid JSON string and return an untyped object representing the
JSON structure.
The ParseJSON function may return errors if the text isn't valid JSON according to the JavaScript
Object Notation (JSON) format described in ECMA-404 and IETF RFC 8259 .
Syntax
ParseJSON( JSONString )
} Color values can With( { uo: ParseJSON( "{ ""r"": 255, ""g"":
be created from 128, ""b"": 0, ""a"": 0.5 }" ) }, RGBA( Value(
RGBA integers uo.r ), Value( uo.g ), Value( uo.b ), Value(
or hexadecimal uo.a ) ) )
strings.
Choice { "status": 1 }
Choices are Switch( Value( ParseJSON( "{ ""status"": 1
{ "status": "Closed" } presented as }" ).status ), 0, Status.Open, 1, Status.Closed
localized )
strings, backed
by a number.
The JSON()
function
serializes a
choice to its
backing
number. There's
no direct
conversion from
number or
string to a
choice, but the
Switch() or If()
functions can
be used on the
text or number
value.
Table [ { "id": 1, "name": "one" }, { "id": JSON can ForAll( Table( ParseJSON( "[ { ""id"": 1,
2, "name": "two" } ]
contain arrays, ""name"": ""one"" }, { ""id"": 2, ""name"":
[1, 2, 3] which can be ""two"" } ]" ) ), { id:
converted into Value(ThisRecord.Value.id), name:
tables. These Text(ThisRecord.Value.name) } )
values can be
arrays of
records, or
arrays of values
that are
effectively
single column
tables.
ParseJSON()
arrays can only
be converted
into a single
column table of
untyped
objects, and
can be used as
such or
converted to
typed tables of
records using
ForAll().
Text { "stringField": "this is text" } Text is an Text( ParseJSON( "{ ""stringField"": ""this is
explicit type in text"" }").stringField )
JSON and can
be directly
converted.
Data type JSON examples Description Example conversion
Examples
JSON
Power Apps
Power Apps
In case a field name consists of an invalid identifier name, you can put the field names in single
quotes.
Given the following JSON string in a variable named JsonString
JSON
Power Apps
Blanks
Given the following JSON string in a variable named JsonString
JSON
1. Attempting to access non-existing fields returns Blank(). The following formula returns true :
Power Apps
2. JSON null values are considered Blank(). The following formula returns true :
Power Apps
Simple Arrays
Given the following JSON string in a variable named JsonString
JSON
{ "array": [1, 2, 3] }
1. Accessing the second number in the array field's single-column table of untyped object and
converting to a number using Value() returns 2 :
Power Apps
2. Converting the single-column table of untyped object in the array field, to a single column
table of numbers { Value: 1 }, { Value: 2 }, { Value: 3 } :
Power Apps
Arrays of Records
Given the following JSON string in a variable named JsonString
JSON
{ "array": [
] }
1. Converting to a typed table of records directly with ForAll() can be done by using ThisRecord.
[fieldname] to access untyped object fields and convert them to known types:
Power Apps
Array to Table
1. Converting untyped object to a table by using the Table() function results in a single-column
table of untyped objects. The object needs to then be accessed using Value (single) column
and be converted to types as explained previously.
JSON
{ "array": [1, 2, 3] }
Table() returns a single-column table of untyped objects with a single-column Value for number in
the array...
Power Apps
```
```JSON
{ "array": [
] }
Table() returns a single-column table of untyped objects that represents each json object in the
array.
Power Apps
Modifies or creates one or more records in a data source, or merges records outside of
a data source.
Use the Patch function to modify records in complex situations, such as when you do
updates that require no user interaction or use forms that span multiple screens.
To update records in a data source more easily for simple changes, use the Edit form
control instead. When you add an Edit form control, you provide users with a form to fill
in and then save the changes to a data source. For more information, see Understand
data forms.
Overview
Use the Patch function to modify one or more records of a data source. The values of
specific fields are modified without affecting other properties. For example, this formula
changes the phone number for a customer named Contoso:
555-1234" } )
Use Patch with the Defaults function to create records. Use this behavior to build a
single screen for both creating and editing records. For example, this formula creates a
record for a customer named Contoso:
Even if you're not working with a data source, you can use Patch to merge two or more
records. For example, this formula merges two records into one that identifies both the
phone number and the location for Contoso:
"Midtown" } )
Description
Modify or create a record in a data source
To use this function with a data source, specify the data source, and then specify a base
record:
To modify a record, the base record needs to have come from a data source. The
base record may have come through a gallery's Items property, been placed in a
context variable, or come through some other path. But, you can trace the base
record back to the data source. This is important as the record will include
additional information to help find the record again for modification.
To create a record, use the Defaults function to create a base record with default
values.
Then specify one or more change records, each of which contains new property values
that override property values in the base record. Change records are processed in order
from the beginning of the argument list to the end, with later property values overriding
earlier ones.
The return value of Patch is the record that you modified or created. If you created a
record, the return value may include properties that the data source generated
automatically. However, the return value doesn't provide a value for fields of a related
table.
Power Apps
When you update a data source, one or more issues may arise. Use IfError and IsError
with the return value from Patch to detect and respond to errors, as Error Handling
describes. You can also use the Errors function to identify and examine issues, as
Working with Data Sources describes.
Related functions include the Update function to replace an entire record, and the
Collect function to create a record. Use the UpdateIf function to modify specific
properties of multiple records based on a condition.
Instead of passing a single base record, a table of base records can be provided in the
second argument. Change records are provided in a table as well, corresponding one-
for-one with the base records. The number of records in each change table must be the
same as the number of records in the base table.
When using Patch in this manner, the return value is also a table with each record
corresponding one-for-one with the base and change records.
Patch returns the merged record and doesn't modify its arguments or records in any
data sources.
Syntax
DataSource – Required. The data source that contains the record that you want to
modify or will contain the record that you want to create.
BaseRecord – Required. The record to modify or create. If the record came from a
data source, the record is found and modified. If the result of Defaults is used, a
record is created.
ChangeRecord(s) – Required. One or more records that contain properties to
modify in the BaseRecord. Change records are processed in order from the
beginning of the argument list to the end, with later property values overriding
earlier ones.
DataSource – Required. The data source that contains the records that you want to
modify or will contain the records that you want to create.
BaseRecordTable – Required. A table of records to modify or create. If the record
came from a data source, the record is found and modified. If the result of
Defaults is used, a record is created.
ChangeRecordTable(s) – Required. One or more tables of records that contain
properties to modify for each record of the BaseRecordTable. Change records are
processed in order from the beginning of the argument list to the end, with later
property values overriding earlier ones.
Merge records
Record(s) - Required. At least two records that you want to merge. Records are
processed in order from the beginning of the argument list to the end, with later
property values overriding earlier ones.
Examples
In these examples, you'll modify or create a record in a data source, named IceCream,
that contains the data in this table and automatically generates the values in the ID
column:
Patch( IceCream,
Modifies a record in the IceCream data { ID: 1,
LookUp( IceCream, source: Flavor: "Chocolate",
Flavor = "Chocolate" ), Quantity: 400 }
After the previous formulas have been evaluated, the data source ends with these
values:
In the example below, consider the first lookup in the If statement. (OrderID =
A[@OrderID]) is expected to compare the OrderId in the lookup scope with the OrderId
of collection A in the ForAll scope. In this case, you likely want A[@OrderId] to be
resolved as a local parameter. But it is ambiguous.
Power Apps currently interprets both the left-hand side OrderId and right-hand side
A[@OrderId] as a field in the lookup scope. Therefore, lookup will always find the first
row in [dbo].[Orders1] because the condition is always true (that is, any row's OrderId
is equal to itself.)
Power Apps
ClearCollect(
A,
Filter(
'[dbo].[Orders1]',
OrderId = 8888888
);
ForAll(
A,
If(
LookUp(
'[dbo].[Orders1]',
OrderId = A[@OrderId],
"OK"
) = "OK",
Patch(
'[dbo].[Orders1]',
LookUp(
'[dbo].[Orders1]',
OrderId = A[@OrderId]
),
OrderName: "val1"
),
Patch(
'[dbo].[Orders1]',
Defaults('[dbo].[Orders1]'),
OrderName: "val2"
Using As or ThisRecord
Whenever possible use the As operator or the ThisRecord to disambiguate the left-hand
side. As is recommended for the above scenario.
When your formula uses multiple scopes with ForAll , Filter , and Lookup on the same
data source or table, it is possible that the scope parameters may collide with a same
field elsewhere. Therefore, it is recommended to use the As operator or ThisRecord to
resolve the field name and avoid ambiguity.
For example, you can use the As operator to disambiguate in the example below.
Power Apps
ClearCollect(
A,
Filter(
'[dbo].[Orders1]',
OrderId = 8888888
);
ForAll(
A,
If(
LookUp(
'[dbo].[Orders1]' As B,
B.OrderId = A[@OrderId],
"OK"
) = "OK",
Patch(
'[dbo].[Orders1]',
LookUp(
'[dbo].[Orders1]' As C,
C.OrderId = A[@OrderId]
),
OrderName: "val1"
),
Patch(
'[dbo].[Orders1]',
Defaults('[dbo].[Orders1]'),
OrderName: "val2"
Power Apps
ClearCollect(
A,
Filter(
'[dbo].[Orders1]',
OrderId = 8888888
);
ForAll(
A,
If(
LookUp(
'[dbo].[Orders1]',
ThisRecord.OrderId = A[@OrderId],
"OK"
) = "OK",
Patch(
'[dbo].[Orders1]',
LookUp(
'[dbo].[Orders1]',
ThisRecord.OrderId = A[@OrderId]
),
OrderName: "val1"
),
Patch(
'[dbo].[Orders1]',
Defaults('[dbo].[Orders1]'),
OrderName: "val2"
To learn more about the usage of As operator and ThisRecord see Operators article.
PDF function in Power Apps
(experimental)
Article • 11/02/2022 • 3 minutes to read
Export contents from the current screen to an object for use in multiple scenarios.
) Important
Description
The PDF function allows you to select a screen or portions of a screen for export to a
PDF object (blob).
Different configuration options enable different outcomes for the resulting generated
PDF.
) Important
PDF generation happens on the device where the app is running. Different
devices such as desktop computers and mobile devices will have different
capacities when you're generating a PDF.
Generating a PDF with an exceptionally large file size can result in the app
crashing. This depends on the capacity of the device that you're running the
app on. Be aware of the size and number of images and how much data you
want to include in the generated PDF, specifically for apps intended for use on
a mobile device.
7 Note
You can only generate a PDF from content existing on the screen where you
have invoked the PDF function. For example, if you have added the PDF
function on screen two, then only the content in screen two can be included
in the generated PDF.
Syntax
PDF (Screen or control name [,{Size, DPI, Margin, Orientation, ExpandContainers}])
Screen or control name – Required. The screen or control containing the content to
use to generate the PDF. Supported controls: Vertical Gallery, Vertical Layout
Container, Horizontal Layout Container, Container, Screen.
Size – Optional. Controls the dimensions of the generated PDF. The default value
depends on the app user's locale; Letter for US and Canada and A4 for other
locales.
Margin – Optional. A string specifying the size of the space reserved between the
content and the outer edge of the generated PDF. Each margin of the generated
PDF (top, right, bottom, left) can support a different value. Supported units of
measurement for this value include in, cm, mm, pt, and px. The default value is 0.5
inch (12.7 mm) for all margins.
Orientation – Optional. Controls whether the generated PDF has a portrait (vertical)
or landscape (horizontal) orientation. The default value is portrait (vertical).
Examples
PDF(Screen1) Generates a PDF object with the A PDF object is created from the
default settings. visible contents of Screen1.
PDF(Container1, Generates a PDF object with the An A3-sized PDF object is created
{Size: A3}) paper size set to A3. from the visible contents of
Container1.
PDF(Screen1, {DPI: Generates a PDF object with the A PDF with the specified DPI,
72, Margin: resolution (DPI) set to 72, the margin, and orientation is created in
"25mm", margin set to 25 millimeters, and the default size (dependent on
Orientation: the orientation set to landscape locale) from the visible content on
"Landscape"}) (horizontal). Screen1.
Known limitations
Certain controls aren't currently supported. These include charts, Power BI tile,
Map, and some configurations of third-party PCF controls.
Non-Latin script types and font weights and styles such as bold and italic may not
appear in the generated PDF for some fonts.
Description
Primary functions
The Cos function returns the cosine of its argument, an angle specified in radians.
The Cot function returns the cotangent of its argument, an angle specified in radians.
The Sin function returns the sine of its argument, an angle specified in radians.
The Tan function returns the tangent of its argument, an angle specified in radians.
Inverse functions
The Acos function returns the arccosine, or inverse cosine, of its argument. The
arccosine is the angle whose cosine is the argument. The returned angle is given in
radians in the range 0 (zero) to π.
The Acot function returns the principal value of the arccotangent, or inverse cotangent,
of its argument. The returned angle is given in radians in the range 0 (zero) to π.
The Asin function returns the arcsine, or inverse sine, of its argument. The arcsine is the
angle whose sine is the argument. The returned angle is given in radians in the range
-π/2 to π/2.
The Atan function returns the arctangent, or inverse tangent, of its argument. The
arctangent is the angle whose tangent is the argument. The returned angle is given in
radians in the range -π/2 to π/2.
The Atan2 function returns the arctangent, or inverse tangent, of the specified x and y
coordinates as arguments. The arctangent is the angle from the x-axis to a line that
contains the origin (0, 0) and a point with coordinates (x, y). The angle is given in radians
between -π and π, excluding -π. A positive result represents a counterclockwise angle
from the x-axis; a negative result represents a clockwise angle. Atan2( a, b ) equals
Atan( b/a ), except that a can equal 0 (zero) with the Atan2 function.
Helper functions
The Degrees function converts radians to degrees. π radians equals 180 degrees.
Notes
If you pass a single number to these functions, the return value is a single result. If you
pass a single-column table that contains numbers, the return value is a single-column
table of results with a Value column, one result for each record in the argument's table.
If you have a multi-column table, you can shape it into a single-column table, as
working with tables describes.
If an argument would result in an undefined value, the result is blank. This can happen,
for example, when using inverse functions with arguments that are out of range.
Syntax
Primary Functions
Cos( Radians )
Cot( Radians )
Sin( Radians )
Tan( Radians )
Cos( SingleColumnTable )
Cot( SingleColumnTable )
Sin( SingleColumnTable )
Tan( SingleColumnTable )
Inverse Functions
Acos( Number )
Acot( Number )
Asin( Number )
Atan( Number )
Acos( SingleColumnTable )
Acot( SingleColumnTable )
Asin( SingleColumnTable )
Atan( SingleColumnTable )
Atan2( X, Y )
Helper Functions
Degrees( Radians )
Pi()
Radians( Degrees )
Examples
Single number
Atan2( 5, 3 ) Returns the arctangent of the angle from the x-axis of the line 0.540419...
that contains the origin (0,0) and the coordinate (5,3), which is
approximately 31 degrees.
Atan2( 4, 4 ) Returns the arctangent of the angle from the x-axis of the line 0.785398...
that contains the origin (0,0) and the coordinate (4,4), which is
exactly π/4 radians or 45 degrees.
Single-column table
The examples in this section use a data source that's named ValueTable and that
contains the following data. The last record in the table is π/2 radians or 90 degrees.
Value
0.5
-2
1.570796...
Sin( ValueTable ) Returns the sine of each number A single-column table with a Value
in the table. column containing the following
values: 0.479425, -0.909297..., 1
Description
The EncodeUrl function encodes a URL string, replacing certain non-alphanumeric
characters with % and a hexadecimal number.
The PlainText function removes HTML and XML tags, converting certain tags such as
these to an appropriate symbol:
"
The return value from these functions is the encoded or decoded string. This function
doesn't remove all HTML and XML tags.
Syntax
EncodeUrl( String )
PlainText( String )
String - Required. String from which HTML and XML tags will be stripped.
Examples
If you show an RSS feed in a text gallery and then set the Text property of a label in that
gallery to ThisItem.description, the label might show raw HTML or XML code as in this
example:
HTML
<p>
localization.
</p>
If you set the Text property of the label to PlainText(ThisItem.description), the text
appears as in this example:
Calculates absolute values, logarithms, square roots, and the results of raising e or any
number to specified powers.
Description
The Abs function returns the non-negative value of its argument. If a number is
negative, Abs returns the positive equivalent.
The Exp function returns e raised to the power of its argument. The transcendental
number e begins 2.7182818...
The Power function returns a number raised to a power. It's equivalent to using the ^
operator.
The Log function returns the logarithm of its first argument in the base specified by its
second argument (or 10 if not specified).
The Sqrt function returns the number that, when multiplied by itself, equals its
argument.
If you pass a single number, the return value is a single result based on the function
called. If you pass a single-column table that contains numbers, the return value is a
single-column table of results in a Value column, one result for each record in the
argument's table. If you have a multi-column table, you can shape it into a single-
column table, as working with tables describes.
If an argument would result in an undefined valued, the result is blank. Which can
happen with square roots and logarithms of negative numbers.
Syntax
Abs( Number )
Exp( Number )
Ln( Number )
Sqrt( Number )
Number - Required. Number to operate on.
Abs( SingleColumnTable )
Exp( SingleColumnTable )
Ln( SingleColumnTable )
Sqrt( SingleColumnTable )
Examples
Single number
Ln( 100 ) Returns the natural logarithm (base e) of the number 100. 4.605170...
Single-column table
The examples in this section use a data source that's named ValueTable and that
contains this data:
Value
-4
Sqrt( ValueTable ) Returns the square root A single-column table with a Value column
of each number in the containing the following values: 3, Blank(),
table 1.414213...
Step-by-step example
1. Add a Text input control, and name it Source.
2. Add a Label control, and set its Text property to this formula:
Description
The print function allows you to select any screen and fit it to a page in order to send it
to a printer for printing or allows you to save it as a PDF file.
The different configurations of the screen enable different printing outcomes. For fixed
screens, they fit the size of the page, for use of the screen templates/special sized
screens, we will fit the content to the size of the print.
7 Note
You can only print the screen you have added a button and defined Print function
on OnSelect property of the button. For example, if you have added a button on
screen 2 and when you select the button, only the content in the screen 2 gets
printed.
Syntax
Print()
Examples
1. Go to Power Apps .
9. Select the button that you added. When you select the button, a default print
browser pops up and allows you to choose from the available options to print or
save it as a PDF file.
From the above example, where you insert a button on the screen and when you print
the screen, you notice that the button is also gets printed. To remove the button from
the screen while printing, on the button’s Visible property add the formula Not
Screen1.Printing . Preview the app and select the button. Observe that the button does
not show in the content in the browser preview print dialog.
Observe that the screen is sized differently from other screens with the print
button on the top-right corner.
Add content to this screen.
Observe that the content is sized to the print. This enables more custom control
over the experience.
Known limitations
The Print function currently doesn't work on mobile devices and on SharePoint
forms.
The Print function currently doesn't work on custom pages or embedded
scenarios.
The default browser printers are the ones that will be available to print to.
In some browser print dialogs, a setting called Background graphics should be
enabled to see all the images and colors in the print.
See also
Canvas app formula reference
Lower, Upper, and Proper functions in
Power Apps
Article • 03/17/2023 • 2 minutes to read
Converts letters in a string of text to all lowercase, all uppercase, or proper case.
Description
The Lower, Upper, and Proper functions convert the case of letters in strings.
If you pass a single string, the return value is the converted version of that string. If you
pass a single-column table that contains strings, the return value is a single-column
table of converted strings. If you have a multi-column table, you can shape it into a
single-column table, as working with tables describes.
Syntax
Lower( String )
Upper( String )
Proper( String )
Lower( SingleColumnTable )
Upper( SingleColumnTable )
Proper( SingleColumnTable )
Examples
Single string
The examples in this section use a text-input control, named Author, as their data
source. The control contains the string "E. E. CummINGS".
Proper( Author.Text ) Converts the first letter of each word to uppercase if it's "E. E.
lowercase, and converts any other uppercase letters to Cummings"
lowercase.
Single-column table
The examples in this section convert strings from the Address column of the People
data source, which contains this data:
Name Address
Each formula returns a single-column table that contains the converted strings.
Proper(Source.Text)
3. Press F5, and then type WE ARE THE BEST! into the Source box.
Description
Primary functions
The Cos function returns the cosine of its argument, an angle specified in radians.
The Cot function returns the cotangent of its argument, an angle specified in radians.
The Sin function returns the sine of its argument, an angle specified in radians.
The Tan function returns the tangent of its argument, an angle specified in radians.
Inverse functions
The Acos function returns the arccosine, or inverse cosine, of its argument. The
arccosine is the angle whose cosine is the argument. The returned angle is given in
radians in the range 0 (zero) to π.
The Acot function returns the principal value of the arccotangent, or inverse cotangent,
of its argument. The returned angle is given in radians in the range 0 (zero) to π.
The Asin function returns the arcsine, or inverse sine, of its argument. The arcsine is the
angle whose sine is the argument. The returned angle is given in radians in the range
-π/2 to π/2.
The Atan function returns the arctangent, or inverse tangent, of its argument. The
arctangent is the angle whose tangent is the argument. The returned angle is given in
radians in the range -π/2 to π/2.
The Atan2 function returns the arctangent, or inverse tangent, of the specified x and y
coordinates as arguments. The arctangent is the angle from the x-axis to a line that
contains the origin (0, 0) and a point with coordinates (x, y). The angle is given in radians
between -π and π, excluding -π. A positive result represents a counterclockwise angle
from the x-axis; a negative result represents a clockwise angle. Atan2( a, b ) equals
Atan( b/a ), except that a can equal 0 (zero) with the Atan2 function.
Helper functions
The Degrees function converts radians to degrees. π radians equals 180 degrees.
Notes
If you pass a single number to these functions, the return value is a single result. If you
pass a single-column table that contains numbers, the return value is a single-column
table of results with a Value column, one result for each record in the argument's table.
If you have a multi-column table, you can shape it into a single-column table, as
working with tables describes.
If an argument would result in an undefined value, the result is blank. This can happen,
for example, when using inverse functions with arguments that are out of range.
Syntax
Primary Functions
Cos( Radians )
Cot( Radians )
Sin( Radians )
Tan( Radians )
Cos( SingleColumnTable )
Cot( SingleColumnTable )
Sin( SingleColumnTable )
Tan( SingleColumnTable )
Inverse Functions
Acos( Number )
Acot( Number )
Asin( Number )
Atan( Number )
Acos( SingleColumnTable )
Acot( SingleColumnTable )
Asin( SingleColumnTable )
Atan( SingleColumnTable )
Atan2( X, Y )
Helper Functions
Degrees( Radians )
Pi()
Radians( Degrees )
Examples
Single number
Atan2( 5, 3 ) Returns the arctangent of the angle from the x-axis of the line 0.540419...
that contains the origin (0,0) and the coordinate (5,3), which is
approximately 31 degrees.
Atan2( 4, 4 ) Returns the arctangent of the angle from the x-axis of the line 0.785398...
that contains the origin (0,0) and the coordinate (4,4), which is
exactly π/4 radians or 45 degrees.
Single-column table
The examples in this section use a data source that's named ValueTable and that
contains the following data. The last record in the table is π/2 radians or 90 degrees.
Value
0.5
-2
1.570796...
Sin( ValueTable ) Returns the sine of each number A single-column table with a Value
in the table. column containing the following
values: 0.479425, -0.909297..., 1
Description
The Rand function returns a pseudo-random number that's greater than or equal to 0
and less than 1. For example, Rand() might return 0.43147 and could return 0 but not 1.
Volatile Functions
Rand and RandBetween are volatile function. Each time the function is evaluated it
returns a different value.
When used in a data flow formula, a volatile function will only return a different value if
the formula in which it appears is reevaluated. If nothing else changes in the formula
then it will have the same value throughout the execution of your app.
For example, a label control with Label1.Text = Rand() won't change while your app is
active. Only closing and reopening the app will result in a new value.
The function will be reevaluated if it's part of a formula in which something else has
changed. For example, if we change our example to involve a slider control with
Label1.Text = Slider1.Value + Rand() then a new random number is generated each time
the Slider control's value changes and the label's text property is reevaluated. See below
for this example.
When used in a behavior formula, Rand and RandBetween will be evaluated each time
the behavior formula is evaluated. See below for an example.
Syntax
Rand()
RandBetween( Bottom, Top )
Bottom - Required. The smallest integer that the function can return.
Top - Required. The largest integer that the function can return. Must be equal to
or greater than Bottom.
Examples
Basic usage
Rand() Returns a pseudo-random number that's greater than Varies with each
or equal to 0 and less than 1. evaluation, for
example
0.874252.
Rand() * 100 Building on the previous example, uses multiplication Varies with each
to extend the range to greater than or equal to 0 and evaluation, for
less than 100. example
78.42521.
Int( Rand() * 100 ) Building on the previous example, uses the Int Varies with each
function to remove the decimal portion, resulting in evaluation, for
an integer greater than or equal to 0 and less than example 84.
100
RandBetween( 0, 99 ) Building on the previous example, performs the same Varies with each
operation using the RandBetween function evaluation, for
example 21.
2. Add a Label control, and set its Text property to this formula:
Slider1.Value + Rand()
The label shows 50 (the default value for the slider) plus a random decimal:
3. While holding down the Alt key, change the value of the slider.
Every time you change the value of the slider, the decimal portion of the label
shows a different random number:
This formula creates a single-column table that's used to iterate 100 times,
resulting in 100 random numbers.
2. Add a Data table, set its Items property to RandomNumbers, and show the Value
field.
3. While holding down the Alt key, select the button by clicking or tapping it.
The data table shows 100 hundred random numbers between 1 and 20:
Description
The Rand function returns a pseudo-random number that's greater than or equal to 0
and less than 1. For example, Rand() might return 0.43147 and could return 0 but not 1.
Volatile Functions
Rand and RandBetween are volatile function. Each time the function is evaluated it
returns a different value.
When used in a data flow formula, a volatile function will only return a different value if
the formula in which it appears is reevaluated. If nothing else changes in the formula
then it will have the same value throughout the execution of your app.
For example, a label control with Label1.Text = Rand() won't change while your app is
active. Only closing and reopening the app will result in a new value.
The function will be reevaluated if it's part of a formula in which something else has
changed. For example, if we change our example to involve a slider control with
Label1.Text = Slider1.Value + Rand() then a new random number is generated each time
the Slider control's value changes and the label's text property is reevaluated. See below
for this example.
When used in a behavior formula, Rand and RandBetween will be evaluated each time
the behavior formula is evaluated. See below for an example.
Syntax
Rand()
RandBetween( Bottom, Top )
Bottom - Required. The smallest integer that the function can return.
Top - Required. The largest integer that the function can return. Must be equal to
or greater than Bottom.
Examples
Basic usage
Rand() Returns a pseudo-random number that's greater than Varies with each
or equal to 0 and less than 1. evaluation, for
example
0.874252.
Rand() * 100 Building on the previous example, uses multiplication Varies with each
to extend the range to greater than or equal to 0 and evaluation, for
less than 100. example
78.42521.
Int( Rand() * 100 ) Building on the previous example, uses the Int Varies with each
function to remove the decimal portion, resulting in evaluation, for
an integer greater than or equal to 0 and less than example 84.
100
RandBetween( 0, 99 ) Building on the previous example, performs the same Varies with each
operation using the RandBetween function evaluation, for
example 21.
2. Add a Label control, and set its Text property to this formula:
Slider1.Value + Rand()
The label shows 50 (the default value for the slider) plus a random decimal:
3. While holding down the Alt key, change the value of the slider.
Every time you change the value of the slider, the decimal portion of the label
shows a different random number:
This formula creates a single-column table that's used to iterate 100 times,
resulting in 100 random numbers.
2. Add a Data table, set its Items property to RandomNumbers, and show the Value
field.
3. While holding down the Alt key, select the button by clicking or tapping it.
The data table shows 100 hundred random numbers between 1 and 20:
Description
Use the ReadNFC function to read an NFC tag that is close to your device. When
invoked, the screen displays instructions for scanning an NFC tag, and only returns after
the tag has been scanned or it times out.
RTD Text The tag's Record Type Definition (RTD). Only Text and URI are supported at
this time.
TNF Number The tag's Type Name Format (TNF). Only TNFs of Well Known(1) are
supported at this time.
Text Text The text payload of the NFC tag if RTD is TEXT, blank otherwise.
URI Hyperlink The URI payload of the NFC tag if RTD is URI, blank otherwise.
If the NDEF record isn't supported (for example, the TNF isn't of type Well Known), then
it won't be returned as part of the NDEFRecords table.
Always check the payload values for blank using the IsBlank function before using it.
You don't need to check the RTD and TNF values yourself as they must be the correct
values for Text and URI to have a non-blank value.
7 Note
ReadNFC is only supported when running the app on a native mobile app,
such as the iOS and Android apps. Even with a supported player, a device
may not support NFC. If your application has Formula-level error
management turned on, the function will return an error. Otherwise, an error
message will be shown to the user and the function will return a blank record.
Ensure your device has the NFC setting enabled to use this capability.
Syntax
ReadNFC()
Examples
Formula Description Result
ReadNFC().Identifier Returns the identifier of the NFC tag if one exists. 04A1C301314003
Step-by-step example
1. Create a blank canvas app with Phone format.
2. Add a Button control.
3. Double-click the button control to change the button text to Read NFC Tag (or
modify the Text property).
4. Set the OnSelect property of the button control to this formula that will add an
item to our collection:
Power Apps
With(ReadNFC(),
This formula reads an NFC tag using the ReadNFC() function, and displays type
information about the result. Then it collects the read NFC tags to populate the
tagRecords collection to be used for the gallery in the next steps.
6. When prompted, select the tagRecords collection as the data source for this
gallery. This action will set the Items property of the Gallery control.
7. Reposition the gallery control so that it doesn't overlap the button, and change the
layout type to Title and subtitle.
8. Change the Title formula in the gallery control to ThisItem.Value and change the
Subtitle formula in the gallery control to ThisItem.ID.
You can also delete the NextArrow from the gallery control since it's not used.
10. Since the function ReadNFC() can't be used in Power Apps Studio or in a web
browser, open your app on a mobile device.
Tip
The app might take a few moments to appear on your mobile device. If you
don't see the app listed, try refreshing your app list.
11. Select Read NFC Tag and scan a tag. Repeat the process to add multiple tags to
your collection.
RecordInfo function in Power Apps
Article • 02/23/2023 • 2 minutes to read
Use RecordInfo to obtain information about a particular record of a data source. The
data source must be tabular and compatible with the Remove and Patch functions.
At this time, only Microsoft Dataverse is supported. Records from all other data sources
will result in a formula error.
RecordInfo.DeletePermission Does the current user have permission to remove this record from
the data source?
RecordInfo.EditPermission Does the current user have permission to modify this record in
the data source?
RecordInfo.ReadPermission Does the current user have permission to read this record from
the data source?
Return Description
value
false The user does not have permission. If the record is blank then RecordInfo will also
return false.
RecordInfo takes into account permissions at the data source level too. For example, if
the user has permission at the record level to modify a record, but the user does not
have permissions at the table level, then it will return false for ModifyPermission. Use
the DataSourceInfo function to obtain information about the data source as a whole.
Syntax
RecordInfo( Record, Information )
Checks the edit permission for the first record in the Accounts data source, which could
be in Dataverse, SharePoint, SQL Server, or another tabular data source. If the user has
permission to edit this record and modify the Accounts data source in general, then
RecordInfo will return true.
Power Apps
Captures a record using the With function and then passes this value to the RecordInfo
function. The result will be the same as the last example.
Power Apps
Captures the first 10 records from the Accounts data source into the MyAccounts
collection. Since the records originated from a data source, they can be used with the
RecordInfo function. The result will be the same as the last example.
Power Apps
Collect( MyCollection, [ 1, 2, 3 ] );
Creates the MyCollection collection and tests the first record to determine if it can be
removed. Since the record's origin is a collection and not a data source, RecordInfo will
return an error.
Refresh function in Power Apps
Article • 02/23/2023 • 2 minutes to read
Description
The Refresh function retrieves a fresh copy of a data source. You'll see changes that
other users made.
Refresh has no return value, and you can use it only in behavior formulas.
Syntax
Refresh( DataSource )
Example
In this example, you'll refresh the data source named IceCream, which starts with this
data:
A user on another device changes the Quantity in the Strawberry record to 400. You
won't see this change until this formula executes:
Refresh( IceCream )
After that formula executes, galleries that are bound to the IceCream data source will
show the updated value for Strawberry:
Relate and Unrelate functions in Power
Apps
Article • 02/23/2023 • 9 minutes to read
Description
The Relate function links two records through a one-to-many or many-to-many
relationship in Microsoft Dataverse. The Unrelate function reverses the process and
removes the link.
For one-to-many relationships, the Many table has a foreign-key field that points to a
record of the One table. Relate sets this field to point to a specific record of the One
table, while Unrelate sets this field to blank. If the field is already set when Relate is
called, the existing link is lost in favor of the new link. You can also set this field by using
the Patch function or an Edit form control; you need not use the Relate function.
For many-to-many relationships, the system that links the records maintains a hidden
join table. You can't access this join table directly; it can be read only through a one-to-
many projection and set through the Relate and Unrelate functions. Neither related
table has a foreign key.
The data for the table that you specify in the first argument will be refreshed to reflect
the change, but the data for the table that you specify in the second argument won't.
That data must be manually refreshed with the Refresh function to show the result of
the operation.
These functions never create or delete a record. They only relate or unrelate two records
that already exist.
7 Note
These functions are part of a preview feature, and their behavior is available only
when the Relational data, option sets, and other new features for CDS feature is
enabled. This is an app-level setting that's enabled by default for new apps. To find
this feature switch, select Settings, and then select Upcoming features. Your
feedback is very valuable to us - please let us know what you think in the Power
Apps community forums .
Syntax
Relate( Table1RelatedTable, Table2Record )
Examples
Consider a Products table with the following relationships as seen in the Power Apps
portal's table viewer:
At no time did we create or remove or a record, only the relationship between records
was modified.
Products and Contacts are related through a Many-to-Many relationship. To relate the
first record of the Contacts table with the first record of the Products table:
or:
The walk through that follows does exactly these operations on these tables using an
app with Gallery and Combo box controls for selecting the records involved.
These examples depend on the sample data being installed in your environment. Either
create a trial environment including sample data or add sample data to an existing
environment.
One-to-many
Relate function
You'll first create a simple app to view and reassign the reservations that are associated
with a product.
5. Ensure that the control that you just added is named Gallery1, and then move and
resize it to fill the left-hand side of the screen.
6. On the Properties tab, set Gallery1's Items property to Products and its Layout to
Image and title.
7. In Gallery1, ensure that the Label control is named Title1, and then set its Text
property to ThisItem.Name.
8. Select the screen to avoid inserting the next item into Gallery1. Add a second blank
vertical Gallery control, and ensure that it's named Gallery2.
Gallery2 will show the reservations for whatever product the user selects in
Gallery1.
9. Move and resize Gallery2 to fill the upper-right quadrant of the screen.
10. (optional) Add the blue Label control above Gallery2, as the next graphic shows.
13. In Gallery2, add a Combo box control, ensure that it's named ComboBox1, and
then move and resize it to avoid blocking the other controls in Gallery2.
15. Scroll down in the Properties tab and set ComboBox1's Allow multiple selection
property to Off.
16. In the formula bar, set ComboBox1's DefaultSelectedItems property to
ThisItem.'Product Reservation'.
Power Apps
When the user selects this icon, the current reservation changes to the product
that the user selected in ComboBox1.
18. Press F5 to test the app in Preview mode.
With this app, the user can move a reservation from one product to another. For a
reservation on one product, the user can select a different product in ComboBox1 and
then select NextArrow2 to change that reservation.
Unrelate function
At this point, you can move the relationship from one record to another, but you can't
remove the relationship altogether. You can use the Unrelate function to disconnect a
reservation record from any product.
2. In the Data pane, select Add data source > Microsoft Dataverse > Reservations >
Connect.
3. In Gallery2, set the OnSelect formula for NextArrow2 to this formula:
Power Apps
);
Refresh( Reservations )
5. Paste a duplicate of Gallery2 to the same screen by pressing Ctrl-V, and then move
it to the lower-right quadrant of the screen.
6. (optional) If you added a label above Gallery2, repeat the previous two steps for
that label.
7. Ensure that the duplicate of Gallery2 is named Gallery2_1, and then set its Items
property to this formula:
Power Apps
A delegation warning appears, but it won't matter with the small amount of data in
this example.
With these changes, users can clear the selection in ComboBox1 for a contact if that
person hasn't reserved a product. Contacts who haven't reserved a product appear in
Gallery2_1 where users can assign each contact to a product.
Many-to-many
1. From this page , select Data in the left navigation bar, and then select Tables.
2. Change the table filter to include all tables.
1. In a blank app for tablets, create Gallery1 as the first procedure in this topic
describes.
2. Add another blank vertical Gallery control, ensure that it's named Gallery2, and
then move it into the upper-right corner of the screen.
Later in this topic, you'll add a Combo box control under Gallery2.
5. In Gallery2, ensure that the Label control is named Title2, and then set its Text
property to ThisItem.'Full Name'.
No text will appear in that control until you finish this procedure and assign a
contact to a product.
6. Delete NextArrow2, insert a Cancel icon, and ensure that it's named icon1.
Power Apps
9. In the Data pane, select Add data source > Microsoft Dataverse > Contacts >
Connect.
10. Under Gallery2, add a Combo box control, ensure that it's named ComboBox1,
and then set its Items property to Contacts.
11. On the Properties tab, set Allow multiple selection to Off.
12. Insert an Add icon, and set its OnSelect property to this formula:
Power Apps
With this app, users can now freely relate and unrelate a set of contacts to each product.
To add a contact to a product, select the contact in the combo box at the bottom
of the screen, and then select the Add icon.
To remove a contact from a product, select the Cancel icon for that contact.
The duplicate will be named Screen1_1 and form the basis for looking at the
relationships from the contacts side.
3. To create the reverse view, change these formulas on the controls of Screen1_1:
4. Insert an Arrows up down icon and set its OnSelect property to Navigate(
Screen1, None ). Do the same thing on Screen1 with the formula Navigate(
Screen1_1, None ).
With this new screen, users can add a contact to a product and then flip to a view of
contacts and see the associated product. The relationships are symmetric and shared
between the two screens.
Remove and RemoveIf functions in
Power Apps
Article • 03/08/2023 • 6 minutes to read
Description
Remove function
Use the Remove function to remove a specific record or records from a data source.
For collections, the entire record must match. You can use the RemoveFlags.All
argument to remove all copies of a record; otherwise, only one copy of the record is
removed.
RemoveIf function
Use the RemoveIf function to remove a record or records based on a condition or a set
of conditions. Each condition can be any formula that results in a true or false and can
reference columns of the data source by name. Each condition is evaluated individually
for each record, and the record is removed if all conditions evaluate to true.
Remove and RemoveIf return the modified data source as a table. You can use both
functions only in behavior formulas.
You can also use the Clear function to remove all of the records in a collection.
Delegation
When used with a data source, these functions can't be delegated. Only the first portion
of the data source will be retrieved and then the function applied. The result may not
represent the complete story. A warning may appear at authoring time to remind you of
this limitation and to suggest switching to delegable alternatives where possible. For
more information, see the delegation overview.
Syntax
Remove( DataSource, Record1 [, Record2, ... ] [, RemoveFlags.All ] )
DataSource – Required. The data source that contains the record or records that
you want to remove.
Record(s) – Required. The record or records to remove.
RemoveFlags.All – Optional. In a collection, the same record may appear more
than once. You can add the RemoveFlags.All argument to remove all copies of the
record.
DataSource – Required. The data source that contains the records that you want to
remove.
Table – Required. A table of records to remove.
RemoveFlags.All – Optional. In a collection, the same record may appear more
than once. You can add the RemoveFlags.All argument to remove all copies of the
record.
DataSource – Required. The data source that contains the record or records that
you want to remove.
Condition(s) – Required. A formula that evaluates to true for the record or records
to remove. You can use column names from the DataSource in the formula. If you
specify multiple Conditions, all must evaluate to true for the record or records to
be removed.
ClearCollect( IceCream,
Remove( IceCream,
Removes the Chocolate record
LookUp( IceCream, Flavor="Chocolate" )) from the data source.
The IceCream
data source has
been modified.
Remove( IceCream,
Removes two records from the
LookUp( IceCream, Flavor="Chocolate" ), data source.
LookUp( IceCream, Flavor="Strawberry" ) The IceCream
) data source has
been modified.
The IceCream
data source has
been modified.
8. Set the OnSelect property for this button control to the following formula:
Power Apps
The gallery control makes the currently selected record available using Selected
property. Remove function refers to this selected record to remove it.
9. Preview the app using the Play button on the top right, or press F5 on keyboard:
Tip
You can also use alternate behavior with Alt key instead of using the app
preview with Play button or F5.
Power Apps
ClearCollect( SampleContacts,
Sample collection is created that you can use in the following example.
To ensure next step inserts item into gallery's template and not outside the gallery,
ensure you follow this step before moving to the next step.
6. Select Add icon from left pane.
7 Note
Add icon inserts a + icon on the left side of the gallery, replicated for each
item in the gallery.
7. In the top item, move the icon to the right side of the screen.
8. Select the Icon property for icon and set it to the following formula to update the
icon image as trash icon:
Power Apps
Icon.Trash
7 Note
The Icon. prefix is only shown when you're actively editing the formula.
9. Set the OnSelect property to the following formula:
Power Apps
7 Note
You must use global disambiguation operator [@...] in this example with
sample data that uses the Contacts table to avoid conflict with a One-to-Many
relationship. If you use data sources such as a list or a SQL Server table, using
global disambgulation operator is not required.
10. Preview the app using the Play button on the top right, or press F5 on keyboard.
11. Select the trash icon next to a record, for example Maria's:
Description
Remove function
Use the Remove function to remove a specific record or records from a data source.
For collections, the entire record must match. You can use the RemoveFlags.All
argument to remove all copies of a record; otherwise, only one copy of the record is
removed.
RemoveIf function
Use the RemoveIf function to remove a record or records based on a condition or a set
of conditions. Each condition can be any formula that results in a true or false and can
reference columns of the data source by name. Each condition is evaluated individually
for each record, and the record is removed if all conditions evaluate to true.
Remove and RemoveIf return the modified data source as a table. You can use both
functions only in behavior formulas.
You can also use the Clear function to remove all of the records in a collection.
Delegation
When used with a data source, these functions can't be delegated. Only the first portion
of the data source will be retrieved and then the function applied. The result may not
represent the complete story. A warning may appear at authoring time to remind you of
this limitation and to suggest switching to delegable alternatives where possible. For
more information, see the delegation overview.
Syntax
Remove( DataSource, Record1 [, Record2, ... ] [, RemoveFlags.All ] )
DataSource – Required. The data source that contains the record or records that
you want to remove.
Record(s) – Required. The record or records to remove.
RemoveFlags.All – Optional. In a collection, the same record may appear more
than once. You can add the RemoveFlags.All argument to remove all copies of the
record.
DataSource – Required. The data source that contains the records that you want to
remove.
Table – Required. A table of records to remove.
RemoveFlags.All – Optional. In a collection, the same record may appear more
than once. You can add the RemoveFlags.All argument to remove all copies of the
record.
DataSource – Required. The data source that contains the record or records that
you want to remove.
Condition(s) – Required. A formula that evaluates to true for the record or records
to remove. You can use column names from the DataSource in the formula. If you
specify multiple Conditions, all must evaluate to true for the record or records to
be removed.
ClearCollect( IceCream,
Remove( IceCream,
Removes the Chocolate record
LookUp( IceCream, Flavor="Chocolate" )) from the data source.
The IceCream
data source has
been modified.
Remove( IceCream,
Removes two records from the
LookUp( IceCream, Flavor="Chocolate" ), data source.
LookUp( IceCream, Flavor="Strawberry" ) The IceCream
) data source has
been modified.
The IceCream
data source has
been modified.
8. Set the OnSelect property for this button control to the following formula:
Power Apps
The gallery control makes the currently selected record available using Selected
property. Remove function refers to this selected record to remove it.
9. Preview the app using the Play button on the top right, or press F5 on keyboard:
Tip
You can also use alternate behavior with Alt key instead of using the app
preview with Play button or F5.
Power Apps
ClearCollect( SampleContacts,
Sample collection is created that you can use in the following example.
To ensure next step inserts item into gallery's template and not outside the gallery,
ensure you follow this step before moving to the next step.
6. Select Add icon from left pane.
7 Note
Add icon inserts a + icon on the left side of the gallery, replicated for each
item in the gallery.
7. In the top item, move the icon to the right side of the screen.
8. Select the Icon property for icon and set it to the following formula to update the
icon image as trash icon:
Power Apps
Icon.Trash
7 Note
The Icon. prefix is only shown when you're actively editing the formula.
9. Set the OnSelect property to the following formula:
Power Apps
7 Note
You must use global disambiguation operator [@...] in this example with
sample data that uses the Contacts table to avoid conflict with a One-to-Many
relationship. If you use data sources such as a list or a SQL Server table, using
global disambgulation operator is not required.
10. Preview the app using the Play button on the top right, or press F5 on keyboard.
11. Select the trash icon next to a record, for example Maria's:
Overview
These functions shape a table by adjusting its columns:
Reduce a table that contains multiple columns down to a single column for use
with single-column functions, such as Lower or Abs.
Add a calculated column to a table (for example, a Total Price column that shows
the results of multiplying Quantity by Unit Price).
Rename a column to something more meaningful, for display to users or for use in
formulas.
A table is a value in Power Apps, just like a string or a number. You can specify a table as
an argument in a formula, and functions can return a table as a result.
7 Note
The functions that this topic describes don't modify the original table. Instead, they
take that table as an argument and return a new table with a transform applied. See
working with tables for more details.
You can't modify the columns of a data source by using these functions. You must
modify the data at its source. You can add columns to a collection with the Collect
function. See working with data sources for more details.
Description
The AddColumns function adds a column to a table, and a formula defines the values in
that column. Existing columns remain unmodified.
The DropColumns function excludes columns from a table. All other columns remain
unmodified. DropColumns excludes columns, and ShowColumns includes columns.
The ShowColumns function includes columns of a table and drops all other columns.
You can use ShowColumns to create a single-column table from a multi-column table.
ShowColumns includes columns, and DropColumns excludes columns.
For all these functions, the result is a new table with the transform applied. The original
table isn't modified. You can't modify an existing table with a formula. SharePoint,
Microsoft Dataverse, SQL Server, and other data sources provide tools for modifying the
columns of lists, tables, and tables, which are often referred to as the schema. The
functions in this topic only transform an input table, without modifying the original, into
an output table for further use.
The arguments to these functions support delegation. For example, a Filter function
used as an argument to pull in related records searches through all listings, even if the
'[dbo].[AllListings]' data source contains a million rows:
Power Apps
AddColumns( RealEstateAgents,
"Listings",
However, the output of these functions is subject to the non-delegation record limit. In
this example, only 500 records are returned even if the RealEstateAgents data source
has 501 or more records.
If you use AddColumns in this manner, Filter must make separate calls to the data
source for each of those first records in RealEstateAgents, which causes a lot of network
chatter. If [dbo](.[AllListings] is small enough and doesn't change often, you could call
the Collect function in OnStart to cache the data source in your app when it starts. As
an alternative, you could restructure your app so that you pull in the related records
only when the user asks for them.
Syntax
AddColumns( Table, ColumnName1, Formula1 [, ColumnName2, Formula2, ... ] )
None of these examples modify the IceCreamSales data source. Each function
transforms the value of the data source as a table and returns that value as the result.
DropColumns(
Performs the following table transforms in
RenameColumns(
order, starting from the inside of the formula:
AddColumns(
IceCreamSales, 1. Adds a Revenue column based on the
"Revenue",
per-record calculation of UnitPrice *
UnitPrice * QuantitySold ),
Quantity.
"UnitPrice", "Price" ),
2. Renames UnitPrice to Price.
"Quantity" ) 3. Excludes the Quantity column.
Step by step
Let's try some of the examples from earlier in this topic.
1. Create a collection by adding a Button control and setting its OnSelect property to
this formula:
Power Apps
ClearCollect( IceCreamSales,
Table(
2. Run the formula by selecting the button while holding down the Alt key.
3. Add a second Button control, set its OnSelect property to this formula, and then
run it:
Power Apps
ClearCollect( FirstExample,
4. On the File menu, select Collections, and then select IceCreamSales to show that
collection.
As this graphic shows, the second formula didn't modify this collection. The
AddColumns function used IceCreamSales as a read-only argument; the function
didn't modify the table to which that argument refers.
5. Select FirstExample.
As this graphic shows, the second formula returned a new table with the added
column. The ClearCollect function captured the new table in the FirstExample
collection, adding something to the original table as it flowed through the function
without modifying the source:
Map columns in a component
See Map columns.
Replace and Substitute functions in
Power Apps
Article • 03/17/2023 • 3 minutes to read
Description
The Replace function identifies the text to replace by starting position and length.
The Substitute function identifies the text to replace by matching a string. If more than
one match is found, you can replace all of them or specify one to replace.
If you pass a single string, the return value is the modified string. If you pass a single-
column table that contains strings, the return value is a single-column table with a Value
column of modified strings. If you have a multi-column table, you can shape it into a
single-column table, as working with tables describes.
Syntax
Replace( String, StartingPosition, NumberOfCharacters, NewString )
Examples
Formula Description Result
Substitute( "Quarter 1, 2018", "1", "2", 1 ) Substitutes only the first "Quarter 2, 2018"
instance of "1" with "2" because
the fourth argument
(InstanceNumber) is provided
with a 1.
Formula Description Result
Substitute( "Quarter 1, 2011", "1", "2", 3 ) Substitutes only the third "Quarter 1, 2012"
instance of "1" with "2" because
the fourth argument
(InstanceNumber) is provided
with a 3.
Substitute( "Quarter 1, 2011", "1", "2" ) Substitutes all instances of "1" "Quarter 2, 2022"
with "2" because the fourth
argument (InstanceNumber)
isn't provided.
Replace(
Replaces the ninth character in A single-column
[ "Quarter 1, 2018",
each record of the single- table with a Value
"Quarter 2, 2011",
column table with "3". column containing
"Quarter 4, 2019" ],
the following
9, 1, "3" ) values:
[ "Quarter 3, 2018",
"Quarter 3, 2011",
"Quarter 3, 2019" ]
Substitute(
Because the fourth argument A single-column
[ "Qtr 1, 2018",
(InstanceNumber) is provided table with a Value
"Quarter 1, 2011",
with a value of 1, substitutes column containing
"Q1, 2019" ],
only the first instance of "1" in the following
"1", "3", 1 ) each record of the single- values:
column table with "3". [ "Qtr 3, 2018",
"Quarter 3, 2011",
"Q3, 2019" ]
Substitute(
Because the fourth argument A single-column
[ "Qtr 1, 2018",
(InstanceNumber) isn't table with a Value
"Quarter 1, 2011",
provided, substitutes all column containing
"Q1, 2019" ],
instances of "1" in each record the following
"1", "3" ) of the single-column table with values:
"3". [ "Qtr 3, 2038",
"Quarter 3, 2033",
"Q3, 2039" ]
Reset function in Power Apps
Article • 02/23/2023 • 2 minutes to read
Description
The Reset function resets a control to its Default property value. Any user changes are
discarded.
You cannot reset controls that are within a Gallery or Edit form control from outside
those controls. You can reset controls from formulas on controls within the same gallery
or form. You can also reset all the controls within a form with the ResetForm function.
Using the Reset function is an alternative to toggling the Reset property of input
controls and is generally preferred. The Reset property may be a better choice if many
controls need to be reset together from multiple formulas. Toggling the Reset property
can be done from a Button control with the formula Reset = Button.Pressed or from a
variable with Reset = MyVar and toggling MyVar with the formula Button.OnSelect =
Set( MyVar, true ); Set( MyVar, false ).
Input controls are also reset when their Default property changes.
Reset has no return value, and you can use it only in behavior formulas.
Syntax
Reset( Control )
Example
1. Insert a Text input control on a screen. By default, its name will be TextInput1 and
its Default property will be set to "Text input".
2. Type a new value in the text box.
3. Insert a Button control on the screen.
4. Set the button's OnSelect property to Reset( TextInput1 ).
5. Select the button. This can be done even when authoring by selecting toward the
ends of the control.
6. The contents of the text box will return to the value of the Default property.
EditForm, NewForm, SubmitForm,
ResetForm, and ViewForm functions in
Power Apps
Article • 02/23/2023 • 5 minutes to read
View, edit, or create an item, save the contents, and reset the controls in an Edit form
control.
Overview
These functions change the state of the Edit form control. The form control can be in
one of these modes:
Mode Description
FormMode.Edit The form is populated with an existing record and the user can modify the
values of the fields. Once complete, the user can save the changes to the
record.
FormMode.New The form is populated with default values and the user can modify the values
of the fields. Once complete, the user can add the record to the data source.
FormMode.View The form is populated with an existing record but the user cannot modify the
values of the fields.
Description
These functions are often invoked from the OnSelect formula of a Button or Image
control so that the user can save edits, abandon edits, or create a record. You can use
controls and these functions together to create a complete solution.
SubmitForm
Use the SubmitForm function in the OnSelect property of a Button control to save any
changes in a Form control to the data source.
Before submitting any changes, this function checks for validation issues with any field
that's marked as required or that has one or more constraints on its value. This behavior
matches that of the Validate function.
SubmitForm also checks the Valid property of the Form, which is an aggregation of all
the Valid properties of the Card controls that the Form control contains. If a problem
occurs, the data isn't submitted, and the Error and ErrorKind properties of the Form
control are set accordingly.
If successful, the Form's OnSuccess behavior runs, and the Error and ErrorKind
properties are cleared. If the form was in FormMode.New mode, it is returned to
FormMode.Edit mode.
If unsuccessful, the Form's OnFailure behavior runs, and the Error and ErrorKind
properties are set accordingly. The mode of the form is unchanged.
EditForm
The EditForm function changes the Form control's mode to FormMode.Edit. In this
mode, the contents of the Form control's Item property are used to populate the form.
If the SubmitForm function runs when the form is in this mode, a record is changed, not
created. FormMode.Edit is the default for the Form control.
NewForm
The NewForm function changes the Form control's mode to FormMode.New. In this
mode, the contents of the Form control's Item property are ignored, and the default
values of the Form's DataSource property populate the form. If the SubmitForm
function runs when the form is in this mode, a record is created, not changed.
ResetForm
The ResetForm function resets the contents of a form to their initial values, before the
user made any changes. If the form is in FormMode.New mode, the form is reset to
FormMode.Edit mode. The OnReset behavior of the form control also runs. You can also
reset individual controls with the Reset function but only from within the form.
ViewForm
The ViewForm function changes the Form control's mode to FormMode.View. In this
mode, the contents of the Form control's Item property are used to populate the form.
The SubmitForm and ResetForm functions have no effect when in this mode.
DisplayMode Property
The current mode can be read through the Mode property. The mode also determines
the value of the DisplayMode property, which can be used by data cards and controls
within the form control. Often, the data card's DisplayMode property will be set to
Parent.DisplayMode (referencing the form) as will the control's DisplayMode property
(referencing the data card):
FormMode.Edit DisplayMode.Edit Data cards and controls are editable, ready to accept
changes to a record.
FormMode.New DisplayMode.Edit Data cards and controls are editable, ready to accept a
new record.
FormMode.View DisplayMode.View Data cards and controls are not editable and optimized
for viewing.
Syntax
SubmitForm( FormName )
EditForm( FormName )
NewForm( FormName )
ResetForm( FormName )
FormName - Required. Form control to reset to initial values. Also switches the
form from FormMode.New mode to FormMode.Edit mode.
ViewForm( FormName )
1. Add a Button control, set its Text property to show Save, and set its OnSelect
property to this formula:
SubmitForm( EditForm )
2. Set the OnFailure property of a Form control to blank and its OnSuccess property
to this formula:
Back()
3. Name a Label control ErrorText, and set its Text property to this formula:
EditForm.Error
When the user selects the Save button, any changes in the Form control are
submitted to the underlying data source.
If the submission succeeds, any changes are saved or, if the Form control is in
New mode, a record is created. ErrorText is blank and the previous screen
reappears.
If the submission fails, ErrorText shows a user-friendly error message, and the
current screen remains visible so that the user can correct the problem and
try again.
4. Add a Button control, set its Text property to show Cancel, and set its OnSelect
property to this formula:
When the user selects the Cancel button, the values in the Form control are reset
to what they were before the user started to edit it, the previous screen reappears,
and the Form control is returned to Edit mode if it was in New mode.
5. Add a Button control, set its Text property to show New, and set its OnSelect
property to this formula:
When the user selects the New button, the Form control switches to New mode,
the default values for the Form control's data source populate that control, and the
screen that contains the Form control appears. When the SubmitForm function
runs, a record is created instead of updated.
Revert function in Power Apps
Article • 02/23/2023 • 2 minutes to read
Description
The Revert function refreshes an entire data source or a single record in that data
source. You'll see changes that other users made.
For the records reverted, Revert also clears any errors from the table that the Errors
function returned.
If the Errors function reports a conflict after a Patch or other data operation, Revert the
record to start with the conflicting version and reapply the change.
Revert has no return value. You can use it only in a behavior formula.
Syntax
Revert( DataSource [, Record ] )
Example
In this example, you'll revert the data source named IceCream, which starts with the
data in this table:
A user on another device changes the Quantity property of the Strawberry record to
400. At about the same time, you change the same property of the same record to 500,
not knowing about the other change.
You use the Patch function to update the record:
{ ID: 1, Flavor: blank "The record you are trying to modify has ErrorKind.Conflict
"Strawberry", been modified by another user. Please
Quantity: 300 } revert the record and try again."
Based on the Error column, you have a Reload button for which the OnSelect property
to set to this formula:
After you select the Reload button, the Errors table is empty, and the new value for
Strawberry has been loaded:
You reapply your change on top of the previous change, and your change succeed
because the conflict has been resolved.
RequestHide function in Power Apps
Article • 02/23/2023 • 2 minutes to read
7 Note
Description
Use the RequestHide function to hide the SharePoint form. By default, RequestHide() is
used for the OnSuccess property of a SharePoint form being customized.
This function is not required for the SharePointIntegration control's OnCancel event as
SharePoint by default hides the form when a user selects Cancel, and the function only
reacts to a SharePoint form.
Syntax
RequestHide ( )
No parameters.
Examples
Formula Description
Use built-in color values, define custom colors, and use the alpha channel.
Description
By using the Color enumeration, you can easily access the colors that are defined by
HTML's Cascading Style Sheets (CSS). For example, Color.Red returns pure red. You can
find a list of these colors at the end of this topic.
The ColorValue function returns a color based on a color string in a CSS. The string can
take any of these forms:
CSS color name: "RoxyBrown" and "OliveDrab" are examples. These names don't
include spaces. The list of supported colors appears later in this topic.
6-digit hex value: As an example "#ffd700" is the same as "Gold". The string is in
the format "#rrggbb" where rr is the red portion in two hexadecimal digits, gg is
the green, and bb is the blue.
8-digit hex value: As an example, "#ff7f5080" is the same as "Coral" with a 50%
alpha channel. The string is in the format "#rrggbbaa" where rr, gg, and bb are
identical to the 6-digit form. The alpha channel is represented by aa: 00 represents
fully transparent, and ff represents fully opaque.
The RGBA function returns a color based on red, green, and blue components. The
function also includes an alpha channel for mixing colors of controls that are layered in
front of one another. An alpha channel varies from 0 or 0% (which is fully transparent
and invisible) to 1 or 100% (which is fully opaque and completely blocks out any layers
behind a control).
The ColorFade function returns a brighter or darker version of a color. The amount of
fade varies from -1 (which fully darkens a color to black) to 0 (which doesn't affect the
color) to 1 (which fully brightens a color to white).
Alpha channel
In a canvas app, you can layer controls in front of one another and specify the
transparency of a control to any controls that are behind it. As a result, colors will blend
through the layers. For example, this diagram shows how the three primary colors mix
with an alpha setting of 50%:
You can also blend images in file formats that support alpha channels. For example, you
can't blend .jpeg files, but you can blend .png files. The next graphic shows the same
red, green, and blue colors from the previous example, but the red color appears as a
squiggle (instead of a circle) in a .png file with a 50% alpha channel:
If you specify a Color enumeration value or you build a ColorValue formula with a color
name or a 6-digit hexadecimal value, the alpha setting is 100%, which is fully opaque.
Syntax
Color.ColorName
ColorName - Required. A Cascading Style Sheet (CSS) color name. The list of
possible enumeration values appears at the end of this topic.
ColorValue( CSSColor )
CSSColor - Required. A Cascading Style Sheet (CSS) color definition. You can
specify either a name, such as OliveDrab, or a hex value, such as #6b8e23 or
#7fffd420. Hex values can take the form of either #rrggbb or #rrggbbaa.
ColorValue( Untyped )
Red, Green, Blue - Required. Color-component values, which range from 0 (no
saturation) to 255 (full saturation).
Alpha - Required. Alpha component, which ranges from 0 (fully transparent) to 1
(fully opaque). You can also use a percentage, 0% to 100%.
Color - Required. A color value such as Color.Red or the output from ColorValue or
RGBA.
FadeAmount - Required. A number between -1 and 1. -1 fully darkens a color to
black, 0 doesn't affect the color, and 1 fully brightens a color to white. You can also
use a percentage from -100% to 100%.
Built-in colors
Color enumeration ColorValue RGBA Color
Swatch
ColorValue(
"Transparent" )
Description
The Left, Mid, and Right functions return a portion of a string.
If you specify a single string as an argument, the function returns the portion that you
requested of the string. If you specify a single-column table that contains strings, the
function returns a single-column table with a Value column containing the portions that
you requested of those strings. If you specify a multi-column table, you can shape it into
a single-column table, as working with tables describes.
If the starting position is negative or beyond the end of the string, Mid returns blank.
You can check the length of a string by using the Len function. If you request more
characters than the string contains, the function returns as many characters as possible.
Syntax
Left( String, NumberOfCharacters )
Examples
Single string
The examples in this section use a text-input control as their data source. The control is
named Author and contains the string "E. E. Cummings".
Left( Author.Text, Extracts up to five characters from the start of the string. "E. E."
5)
Mid( Author.Text, Extracts up to four characters, starting with the seventh "Cumm"
7, 4 ) character, from the string.
Mid( Author.Text, Extracts all characters, starting with the seventh character, "Cummings"
7) from the string.
Right( Extracts up to five characters from the end of the string. "mings"
Author.Text, 5 )
Single-column table
Each example in this section extracts strings from the Address column of this data
source, named People, and returns a single-column table that contains the results:
Name Address
Step-by-step example
1. Import or create a collection named Inventory, and show it in a gallery, as the first
procedure in Show images and text in a gallery describes.
2. Set the Text property of the lower label in the gallery to this function:
Right(ThisItem.ProductName, 3)
The label shows the last three characters of each product name.
Int, Round, RoundDown, RoundUp, and
Trunc functions in Power Apps
Article • 02/23/2023 • 2 minutes to read
Rounds a number.
Round rounds up if the next digit is 5 or higher. Otherwise, this function rounds
down.
RoundDown always rounds down to the previous lower number, towards zero.
RoundUp always rounds up to the next higher number, away from zero.
Greater than The number is rounded to the right of the decimal Round( 12.37, 1 ) returns
0 separator. 12.4.
Less than 0 The number is rounded to the left of the decimal Round( 12.37, -1 )
separator. returns 10.
The difference between Int and Trunc is in the handling of negative numbers. For
example, for an argument of -4.3 , Int will return the integer further away from zero, -5 ,
while Trunc will return the integer closer to zero, -4 . Int returns values that are unique
amongst the five rounding functions, while Trunc returns the same values as
RoundDown.
Use Trunc to extract the decimal portion of a number by subtracting it from the original,
for example X - Trunc(X) .
Decimal places cannot be specified with Trunc as it can with Microsoft Excel. Use
RoundDown instead when this is needed.
Single-column tables
These functions support single-column tables. If you pass a single number, the return
value is the rounded version of that number. If you pass a single-column table that
contains numbers, the return value is a single-column table of rounded numbers. The
DecimalPlaces parameter can be a single value or a single-column table. If the single-
column table has less values that the Number, zero is used for the remaining values. Use
ShowColumns and other table shaping functions to extract a single-column table from
a larger table.
Syntax
Round(Number, DecimalPlaces)
RoundDown(Number, DecimalPlaces)
RoundUp(Number, DecimalPlaces)
Int(Number)
Trunc(Number)
Examples
Rounding to a whole number.
7.9 8 8 7 7 7
-7.9 -8 -8 -7 -8 -7
7.5 8 8 7 7 7
-7.5 -8 -8 -7 -8 -7
7.1 7 8 7 7 7
-7.1 -7 -8 -7 -8 -7
Rounding to two decimal places to the right of the decimal separator (0.01).
Rounding to two decimal places to the left of the decimal separator (100).
[ 123.456,
[ 123,
[ 123.46,
[ 123,
[ 123.46,
987.593,
987,
987.59,
987.5,
988,
Rounds a number.
Round rounds up if the next digit is 5 or higher. Otherwise, this function rounds
down.
RoundDown always rounds down to the previous lower number, towards zero.
RoundUp always rounds up to the next higher number, away from zero.
Greater than The number is rounded to the right of the decimal Round( 12.37, 1 ) returns
0 separator. 12.4.
Less than 0 The number is rounded to the left of the decimal Round( 12.37, -1 )
separator. returns 10.
The difference between Int and Trunc is in the handling of negative numbers. For
example, for an argument of -4.3 , Int will return the integer further away from zero, -5 ,
while Trunc will return the integer closer to zero, -4 . Int returns values that are unique
amongst the five rounding functions, while Trunc returns the same values as
RoundDown.
Use Trunc to extract the decimal portion of a number by subtracting it from the original,
for example X - Trunc(X) .
Decimal places cannot be specified with Trunc as it can with Microsoft Excel. Use
RoundDown instead when this is needed.
Single-column tables
These functions support single-column tables. If you pass a single number, the return
value is the rounded version of that number. If you pass a single-column table that
contains numbers, the return value is a single-column table of rounded numbers. The
DecimalPlaces parameter can be a single value or a single-column table. If the single-
column table has less values that the Number, zero is used for the remaining values. Use
ShowColumns and other table shaping functions to extract a single-column table from
a larger table.
Syntax
Round(Number, DecimalPlaces)
RoundDown(Number, DecimalPlaces)
RoundUp(Number, DecimalPlaces)
Int(Number)
Trunc(Number)
Examples
Rounding to a whole number.
7.9 8 8 7 7 7
-7.9 -8 -8 -7 -8 -7
7.5 8 8 7 7 7
-7.5 -8 -8 -7 -8 -7
7.1 7 8 7 7 7
-7.1 -7 -8 -7 -8 -7
Rounding to two decimal places to the right of the decimal separator (0.01).
Rounding to two decimal places to the left of the decimal separator (100).
[ 123.456,
[ 123,
[ 123.46,
[ 123,
[ 123.46,
987.593,
987,
987.59,
987.5,
988,
Rounds a number.
Round rounds up if the next digit is 5 or higher. Otherwise, this function rounds
down.
RoundDown always rounds down to the previous lower number, towards zero.
RoundUp always rounds up to the next higher number, away from zero.
Greater than The number is rounded to the right of the decimal Round( 12.37, 1 ) returns
0 separator. 12.4.
Less than 0 The number is rounded to the left of the decimal Round( 12.37, -1 )
separator. returns 10.
The difference between Int and Trunc is in the handling of negative numbers. For
example, for an argument of -4.3 , Int will return the integer further away from zero, -5 ,
while Trunc will return the integer closer to zero, -4 . Int returns values that are unique
amongst the five rounding functions, while Trunc returns the same values as
RoundDown.
Use Trunc to extract the decimal portion of a number by subtracting it from the original,
for example X - Trunc(X) .
Decimal places cannot be specified with Trunc as it can with Microsoft Excel. Use
RoundDown instead when this is needed.
Single-column tables
These functions support single-column tables. If you pass a single number, the return
value is the rounded version of that number. If you pass a single-column table that
contains numbers, the return value is a single-column table of rounded numbers. The
DecimalPlaces parameter can be a single value or a single-column table. If the single-
column table has less values that the Number, zero is used for the remaining values. Use
ShowColumns and other table shaping functions to extract a single-column table from
a larger table.
Syntax
Round(Number, DecimalPlaces)
RoundDown(Number, DecimalPlaces)
RoundUp(Number, DecimalPlaces)
Int(Number)
Trunc(Number)
Examples
Rounding to a whole number.
7.9 8 8 7 7 7
-7.9 -8 -8 -7 -8 -7
7.5 8 8 7 7 7
-7.5 -8 -8 -7 -8 -7
7.1 7 8 7 7 7
-7.1 -7 -8 -7 -8 -7
Rounding to two decimal places to the right of the decimal separator (0.01).
Rounding to two decimal places to the left of the decimal separator (100).
[ 123.456,
[ 123,
[ 123.46,
[ 123,
[ 123.46,
987.593,
987,
987.59,
987.5,
988,
7 Note
These functions can now be used when playing an app in a web browser as an
experimental feature. This feature is disabled by default. To enable, navigate to
Settings > Upcoming features > Experimental > Enabled SaveData, LoadData,
ClearData on web player." and turn the switch on. To submit feedback regarding
this experimental feature, go to Power Apps community forum .
Description
The SaveData function stores a collection for later use under a name.
The LoadData function reloads a collection by name that was previously saved with
SaveData. You can't use this function to load a collection from another source.
The ClearData function clears the storage under a specific name or clears all storage
associated with the app if no name is provided.
7 Note
The name shared between SaveData, LoadData, and ClearData is a key, not a
file name. It need not be complex as names are unique to each app and there
is no danger of name conflict. The name must not contain any of these
characters: *".?:\<>|/ .
SaveData is limited to 1 MB of data for Power Apps running in Teams and in a
web browser. There is no fixed limit for Power Apps running in a mobile player
but there are practical limits discussed below.
Don't use SaveData to store sensitive data in the web since it'll be stored in
plain text.
You can also use these functions to add simple offline capabilities to your app.
To test your app, run it in Power Apps Mobile on an iPhone or Android device.
These functions are limited by the amount of available app memory as they operate on
an in-memory collection. Available memory can vary depending on factors such as:
Test your app with expected scenarios on the type of devices you expect the app to run
when storing large data. Expect to have between 30 MB and 70 MB of available memory
generally.
These functions depend on the collection being implicitly defined with Collect or
ClearCollect. You don't need to call Collect or ClearCollect to load data into the
collection for defining it. It's a common case when using LoadData after a previous
SaveData. All that is needed is the presence of these functions in a formula to implicitly
define the structure of the collection. For more information, see creating and removing
variables.
The loaded data will be appended to the collection. Use the Clear function before
calling LoadData if you want to start with an empty collection.
Data security
Consider carefully the isolation and encryption of data stored with SaveData and decide
if it's appropriate for your needs, especially if devices are shared by multiple users.
Data stored with SaveData is isolated from other Power Apps by the Power Apps
players. Data is stored based on the app's App ID, automatically isolating the SaveData
name space between Power Apps.
The operating system and browser is responsible for isolating data between Power Apps
and other apps on a device and with websites. For example, the operating system is
responsible for isolating data stored in Microsoft Outlook from data stored in Power
Apps, and also isolating that data from websites such as Bing.com or PowerApps.com.
The operating system's built in app sandbox facilities are used for SaveData storage
which is usually not accessible to or hidden from the user.
When using the same app, the operating system and browser is also responsible for
isolating the data between different operating system level users. For example, if two
different users share a computer and use two different Windows login credentials, the
operating system is responsible for isolating data between the two Windows users.
Data may or may not be isolated between different Power Apps users if the operating
system user is the same. Not every Power Apps player treats this the same way. For
example, while logged in as the same Windows user, in the Power Apps player, the user
signs out of Power Apps and signs in as a different Power Apps user. Data stored in an
app before the change of Power Apps user, may be accessible to the second Power
Apps user within the same app. The data may also be removed and the first Power Apps
user may no longer be able to access it. The behavior varies between Power Apps
players.
The operating system may also encrypt the data or you can use a mobile device
management tool such as Microsoft Intune . Data stored when playing an app in a web
browser is not encrypted.
Syntax
SaveData( Collection, Name )
ClearData( [Name] )
Name - Optional. Name of the storage previously saved with SaveData. If Name is
not provided, all storage associated with the app is cleared.
Examples
Formula Description Result
SaveData( Save the LocalCache collection to the user's device Data is saved to the app
LocalCache, under the name "MyCache", suitable for LoadData host under the name
"MyCache" ) to retrieve later. "MyCache".
LoadData( Loads the LocalCache collection from the user's Data is loaded from the
LocalCache, device under the name "MyCache", previously app host under the name
"MyCache" ) stored with a call to SaveData. "MyCache".
ClearData( Clears the storage under the name "MyCache". Any Data is removed from the
"MyCache" ) data stored under this name will no longer be app host under the name
available through LoadData. "MyCache".
ClearData() Clear all storage associated with this app. Data All data is removed from
stored by other apps is not affected. the app host.
7 Note
This example uses a camera control to capture images. Since SaveData is limited to
1 MB of data when running in Teams or a web browser, this example will not work
with more than a few images. Also, depending on the camera, it may not work with
even one image. Use a device to work through this full example, or remove the
camera control and picture part of this example to run in Teams or in a web
browser.
1. Create a blank canvas app with a tablet layout. For more details, read creating an
app from a template and select Tablet layout under Blank app.
2. Add a Text input control and a Camera control and arrange them roughly as
shown:
3. Add a Button control.
4. Double-click the button control to change the button text to Add Item (or modify
the Text property).
5. Set the OnSelect property of the button control to this formula that will add an
item to our collection:
Power Apps
7. Double-click the button control to change the button text to Save Data (or modify
the Text property).
8. Set the OnSelect property of the button control to this formula in order to save
our collection to the local device:
Power Apps
It's tempting to test the button as it doesn't affect anything. But you'll only see an
error as you're authoring in a web browser. Save the app first and open on a
device before you follow the next steps to test this formula:
10. Double-click the button control to change the button text to Load Data (or modify
the Text property).
11. Set the OnSelect property of the button control to this formula in order to load
our collection from the local device:
Power Apps
12. Add a Gallery control with a Vertical layout that includes a picture and text areas:
13. When prompted, select the MyItems collection as the data source for this gallery.
This will set the Items property of the Gallery control:
The image control in the gallery template should default its Image property to
ThisItem.Picture and the label controls should both default their Text properties to
ThisItem.Item. Check these formulas if after adding items in the following steps
you don't see anything in the gallery.
15. Save your app. If it's the first time it has been saved, there's no need to publish it. If
it's not the first time, publish the app after you save.
16. Open your app on a device such as a phone or tablet. SaveData and LoadData
can't be used in Studio or in a web browser. Refresh your app list if you don't see
your app immediately, it can take a few seconds for the app to appear on your
device. Signing out and back in to your account can help too.
Once your app has been downloaded, you can disconnect from the network and
run the app offline.
17. Enter the name and take a picture of an item.
18. Select the Add Item button. Repeat adding items a couple of times to load up your
collection.
19. Select the Save Data button. This will save the data in your collection to your local
device.
20. Close the app. Your collection in memory will be lost including all item names and
pictures, but they'll still be there in the device's storage.
21. Launch the app again. The collection in memory will again show as empty in the
gallery.
22. Select the Load Data button. The collection will be repopulated from the stored
data on your device and your items will be back in the gallery. The collection was
empty before this button calls the LoadData function; there was no need to call
Collect or ClearCollect before loading the data from storage.
23. Select the Load Data button again. The stored data will be appended to the end of
the collection and a scroll bar will appear on the gallery. If you would like to
replace rather than append, use the Clear function first to clear out the collection
before calling the LoadData function.
Watch this video to learn how to use Filter, Search and LookUp functions:
https://www.microsoft.com/en-us/videoplayer/embed/RWLj3m?postJsllMsg=true
Description
The Filter function finds records in a table that satisfy a formula. Use Filter to find a set
of records that match one or more criteria and to discard those that don't.
The LookUp function finds the first record in a table that satisfies a formula. Use LookUp
to find a single record that matches one or more criteria.
For both, the formula is evaluated for each record of the table. Records that result in
true are included in the result. Besides the normal formula operators, you can use the in
and exactin operators for substring matches.
Fields of the record currently being processed are available within the formula. Use the
ThisRecord operator or simply reference fields by name as you would any other value.
The As operator can also be used to name the record being processed which can help
make your formula easier to understand and make nested records accessible. For more
information, see the examples below and working with record scope.
The Search function finds records in a table that contain a string in one of their columns.
The string may occur anywhere within the column; for example, searching for "rob" or
"bert" would find a match in a column that contains "Robert". Searching is case-
insensitive. Unlike Filter and LookUp, the Search function uses a single string to match
instead of a formula.
Filter and Search return a table that contains the same columns as the original table and
the records that match the criteria. LookUp returns only the first record found, after
applying a formula to reduce the record to a single value. If no records are found, Filter
and Search return an empty table, and LookUp returns blank.
Tables are a value in Power Apps, just like a string or number. They can be passed to and
returned from functions. Filter, Search, and LookUp don't modify a table. Instead, they
take a table as an argument and return a table, a record, or a single value from it. See
working with tables for more details.
Delegation
When possible, Power Apps will delegate filter and sort operations to the data source
and page through the results on demand. For example, when you start an app that
shows a Gallery control filled with data, only the first set of records will be initially
brought to the device. As the user scrolls, additional data is brought down from the data
source. The result is a faster start time for the app and access to very large data sets.
However, delegation may not always be possible. Data sources vary on what functions
and operators they support with delegation. If complete delegation of a formula isn't
possible, the authoring environment will flag the portion that can't be delegated with a
warning. When possible, consider changing the formula to avoid functions and
operators that can't be delegated. The delegation list details which data sources and
operations can be delegated.
If delegation is not possible, Power Apps will pull down only a small set of records to
work on locally. Filter and sort functions will operate on a reduced set of records. What
is available in the Gallery may not be the complete story, which could be confusing to
users.
Syntax
Filter(Table*, Formula1 [, *Formula2*, ... ] )
7 Note
For SharePoint and Excel data sources that contain column names with spaces,
specify each space as "_x0020_". For example, specify "Column Name" as
"Column_x0020_Name".
Table - Required. Table to search. In the UI, the syntax is shown as source above the
function box.
Formula - Required.
The formula by which each record of the table is evaluated.
The function returns the first record that results in true. You can reference columns
within the table. In the UI, the syntax is shown as condition above the function box.
ReductionFormula - Optional. This formula is evaluated over the record that was
found, and then reduces the record to a single value. You can reference columns
within the table. If you don't use this parameter, the function returns the full record
from the table. In the UI, the syntax is shown as result above the function box.
Examples
The following examples use the IceCream data source:
Search(IceCream, Because the search term is empty, all records are returned.
"", "Flavor")
LookUp(IceCream, Searches for a record with Quantity greater than 150, of 250
Quantity > 150, which there are multiple. For the first record that's found,
Quantity + which is "Vanilla" Flavor, returns the sum of Quantity and
OnOrder) OnOrder columns.
LookUp(IceCream, Searches for a record with Flavor equal to "Vanilla", of which { Flavor:
Flavor = "Vanilla") there is one. Since no reduction formula was supplied, the "Vanilla",
entire record is returned. Quantity:
200,
OnOrder: 75
}
Step by step
4. On the Properties tab of the right-hand pane, open Data Source and then select
Accounts.
6. On the Insert tab, select Input and then select Combo box. Repeat the step to add
two more combo box controls.
7. For each combo box control, on the Properties tab of the right-hand pane, open
Data Source and then select Accounts. Select Edit next to Fields option and then
select the Primary text and SearchField values. The Primary text should be the
choices column you want to add to the combo box. Repeat the step for other two
combo box controls.
8. Now select Gallery control and set the Items property to the following formula:
Filter(Accounts,
'Industry' =
ComboBox3.Selected.Industry||IsBlank(ComboBox3.Selected.Industry),
IsBlank(ComboBox2.Selected.'Relationship Type'),
In many apps, you can type one or more characters into a search box to filter a list of
records in a large data set. As you type, the list shows only those records that match the
search criteria.
The examples in the rest of this topic show the results of searching a list, named
Customers, that contain this data:
To create this data source as a collection, create a Button control and set its OnSelect
property to this formula:
As in this example, you can show a list of records in a Gallery control at the bottom of a
screen. Near the top of the screen, you can add a Text input control, named
SearchInput, so that users can specify which records interest them.
As the user types characters in SearchInput, the results in the gallery are automatically
filtered. In this case, the gallery is configured to show records for which the name of the
customer (not the name of the company) starts with the sequence of characters in
SearchInput. If the user types co in the search box, the gallery shows these results:
To filter based on the Name column, set the Items property of the gallery control to one
of these formulas:
Filter(Customers, Filters the Customers data source for records in which the search
StartsWith(Name, string appears at the start of the Name column. The test is case
SearchInput.Text) insensitive. If the user types co in the search box, the gallery shows
) Colleen Jones and Cole Miller. The gallery doesn't show Mike
Collins because the Name column for that record doesn't start
with the search string.
Filter(Customers, Filters the Customers data source for records in which the search
SearchInput.Text string appears anywhere in the Name column. The test is case
in Name) insensitive. If the user types co in the search box, the gallery shows
Colleen Jones, Cole Miller, and Mike Collins because the search
string appears somewhere in the Name column of all of those
records.
Search(Customers, Similar to using the in operator, the Search function searches for a
SearchInput.Text, match anywhere within the Name column of each record. You
"Name") must enclose the column name in double quotation marks.
You can expand your search to include the Company column and the Name column:
Filter(Customers, Filters the Customers data source for records in which either the
StartsWith(Name, Name column or the Company column starts with the search
SearchInput.Text) || string (for example, co). The || operator is true if either
StartsWith(Company, StartsWith function is true.
SearchInput.Text) )
Filter(Customers, Filters the Customers data source for records in which either the
SearchInput.Text in Name column or the Company column contains the search
Name || SearchInput. string (for example, co) anywhere within it.
Text in Company)
Description
The Day function returns the day component of a Date/Time value, ranging from 1 to
31.
The Month function returns the month component of a Date/Time value, ranging from
1 to 12.
The Year function returns the year component of a Date/Time value, starting with 1900.
The Hour function returns the hour component of a Date/Time value, ranging from 0
(12:00 AM) to 23 (11:00 PM).
The Minute function returns the minute component of a Date/Time value, ranging from
0 to 59.
The Second function returns the second component of a Date/Time value, ranging from
0 to 59.
The Weekday function returns the weekday of a Date/Time value. By default, the result
ranges from 1 (Sunday) to 7 (Saturday). You can specify a different range with an
Microsoft Excel Weekday function code or a StartOfWeek enumeration value:
Syntax
Day( DateTime )
Month( DateTime )
Year( DateTime )
Hour( DateTime )
Minute( DateTime )
Second( DateTime )
Examples
For the following example, the current time is 3:59:37 PM on Thursday, April 9, 2015.
Description
The Select function simulates a select action on a control as if the user had clicked or
tapped the control. As a result, the OnSelect formula on the target control is evaluated.
Use Select to propagate a select action to a parent control. This type of propagation is
the default behavior in, for example, galleries. By default, the OnSelect property of any
control in a Gallery control is set to Select( Parent ). That way, you can set the value of
the OnSelect property of the gallery control itself, and that formula will be evaluated
regardless of where in the gallery a user might click or tap.
If you want one or more controls in the gallery to perform different actions from the
gallery itself, set the OnSelect property for those controls to something other than the
default value. You can leave the default values for the OnSelect properties of most
controls in the gallery if you want them to perform the same action as the gallery itself.
Select queues the target OnSelect for later processing, which may happen after the
current formula has finished being evaluated. Select doesn't cause the target OnSelect
to evaluate immediately, nor does Select wait for OnSelect to finish being evaluated.
You can use Select only with controls that have an OnSelect property.
The select function can also be used with a gallery. For example, it can be used to
specify the row or column to select in a gallery and the control to select within that row
or column of the gallery. When you select a row or column, the gallery selection
changes and the OnSelect formula on the gallery control is evaluated. If a control within
the row or column is provided, the OnSelect formula for the child control will be
evaluated.
Syntax
Select( Control )
Examples
Button
Select(button1)
Gallery
Select(Gallery1, 1)
Gallery
Select(Gallery1, 1, ChildControl1)
Basic usage
1. Add a Button control, and rename it Button1 if it has a different name.
3. On the same screen, add a second Button control, and set its OnSelect property to
this formula:
Select( Button1 )
4. While holding down the Alt key, select the second button.
A notification appears across the top of your app. The OnSelect property of
Button1 generated this notification.
Gallery control
1. Add a vertical Gallery control that contains other controls.
3. While holding down the Alt key, click or tap the background of the gallery or any
control in the gallery.
All actions will show the Gallery Selected notification at the top of the app.
Use the gallery's OnSelect property to specify the default action to take when the
user clicks or taps an item in the gallery.
4. Set the OnSelect property of the image control to this formula:
5. While holding down the Alt key, click or tap the various elements of the gallery.
When you click or tap any control in the gallery except the image, Gallery Selected
appears as before. When you click or tap the image, Image Selected appears.
Use individual controls in the gallery to take actions that differ from the gallery's
default action.
6. On the same screen, add a Button control, and set its OnSelect property to this
formula:
Select( Gallery1,2,Image1 )
A Image Selected notification appears across the top of your app. The button click
simulated selecting the image in row 2 of the gallery.
Operators and Identifiers in Power Apps
Article • 03/01/2023 • 12 minutes to read
Some of these operators are dependent on the language of the author. For more
information about language support in canvas apps, see Global apps.
"..." Text string "Hello, World" Text strings are enclosed in double
quotes
. Property Slider1.Value
Extracts a property from a table,
Selector Color.Red
control, signal, or enumeration. For
Acceleration.X backward compatibility, ! may also be
used.
.
Decimal 1.23 Separator between whole and fractional
[language separator parts of a number. The character
dependent] depends on the language.
* 2*3 Multiplication
& String "hello" & " " & Makes multiple strings appear
concatenation "world" continuous
operator
&& or And Logical Price < 100 && Logical conjunction, equivalent to the
operators Slider1.Value = 20
And function
or Price < 100 And
Slider1.Value = 20
! or Not !(Price < 100) or Not Logical negation, equivalent to the Not
(Price < 100) function
,
List separator If( X < 10, "Low", Separates:
[language "Good" )
arguments in function calls
dependent] { X: 12, Y: 32 }
fields in a record
[ 1, 2, 3 ] records in a table
;
Formula Collect(T, A); Separate invocations of functions in
[language chaining Navigate(S1, "") behavior properties. The chaining
dependent] operator depends on the language.
7 Note
The @ operator can also be used to validate the type of the record object against a
data source. For example, Collect(coll,Account@{'Account Number: 1111')
The gallery shows all products except Callisto because the name of that product is
the only one that doesn't contain the letter you specified.
The gallery shows only Europa because only its name contains the letter that you
specified in the case that you specified.
ThisItem Gallery control
The default name for the current record in a Gallery or form
Edit form control
control.
Display form control
ThisRecord ForAll, Filter, With, The default name for the current record in ForAll and other
Sum and other record scope functions.
record scope
functions
As name Gallery control
Defines a name for the current record, replacing default
ForAll, Filter, With, ThisItem or ThisRecord. Use As to make formulas easier to
Sum and other understand and resolve ambiguity when nesting.
record scope
functions
ThisItem operator
For example, in the following Gallery control, the Items property is set to the Employees
data source (such as the Employees table included with the Northwind Traders sample):
Power Apps
Employees
The first item in the gallery is a template that is replicated for each employee. In the
template, the formula for the picture uses ThisItem to refer to the current item:
Power Apps
ThisItem.Picture
Power Apps
ThisRecord operator
ThisRecord is used in functions that have a record scope. For example, we can use the
Filter function with our gallery's Items property to only show first names that being with
M:
Power Apps
ThisRecord is optional and implied by using the fields directly, for example, in this case,
we could have written:
Power Apps
Although optional, using ThisRecord can make formulas easier to understand and may
be required in ambiguous situations where a field name may also be a relationship
name. ThisRecord is optional while ThisItem is always required.
Use ThisRecord to reference the whole record with Patch, Collect, and other record
scope functions. For example, the following formula sets the status for all inactive
employees to active:
Power Apps
ForAll( InactiveEmployees,
As operator
Use the As operator to name a record in a gallery or record scope function, overriding
the default ThisItem or ThisRecord. Naming the record can make your formulas easier
to understand and may be required in nested situations to access records in other
scopes.
For example, you can modify the Items property of our gallery to use As to identify that
we are working with an Employee:
Power Apps
Employees As Employee
The formulas for the picture and name are adjusted to use this name for the current
record:
Power Apps
Employee.Picture
Power Apps
Employee.'First Name' & " " & Employee.'Last Name'
As can also be used with record scope functions to replace the default name
ThisRecord. We can apply this to our previous example to clarify the record we're
working with:
Power Apps
When nesting galleries and record scope functions, ThisItem and ThisRecord always
refers to the inner most scope, leaving records in outer scopes unavailable. Use As to
make all record scopes available by giving each a unique name.
For example, this formula produces a chessboard pattern as a text string by nesting two
ForAll functions:
Power Apps
Concat(
Concat(
),
Value
) & Char(10)
),
Value
A similar example is possible with nested Gallery controls instead of ForAll functions.
Let's start with the vertical gallery for the Rank. This gallery control will have an Items
formula of:
Power Apps
Sequence(8) as Rank
Within this gallery, we'll place a horizontal gallery for the File, that will be replicated for
each Rank, with an Items property of:
Power Apps
Sequence(8) as File
And finally, within this gallery, we'll add a Label control that will be replicated for each
File and each Rank. We'll size it to fill the entire space and use the Fill property to
provide the color with this formula:
Power Apps
Method Description
By Any control can be referenced by name from anywhere within the app.
control
name For example, Label1.Fill refers to the fill property of the control who's name is Label1.
Self It's often convenient to reference another property of the same control when writing a
operator formula. Instead of using an absolute reference by name, it's easier and more portable
to use a relative reference to oneself. The Self operator provides that easy access to
the current control.
For example, Self.Fill refers to the fill color of the current control.
Parent Some controls host other controls, such as the Screen and Gallery controls. The
operator hosting control of the controls within it's called the parent. Like the Self operator, the
Parent operator provides an easy relative reference to the container control.
For example, Parent.Fill refers to the fill property of the control that is the container for
the current control.
Self and Parent are operators and not properties on the controls themselves. Referring
to Parent.Parent, Self.Parent or Parent.Self is not supported.
Identifier names
The names of variables, data sources, columns, and other objects can contain any
Unicode .
Use single quotes around a name that contains a space or other special character.
Use two single quotes together to represent one single quote in the name. Names that
don't contain special characters don't require single quotes.
Here are some example column names you might encounter in a table, and how they're
represented in a formula:
SimpleName SimpleName
NameWith123Numbers NameWith123Numbers
Display name - A name that is user-friendly and intended to be seen by end users.
This name may not be unique, may change over time, may contain spaces and any
Unicode character, and may be localized into different languages. Corresponding
to the example above, the display name may be Custom Field with space in
between the words.
Since display names are easier to understand, Canvas apps will suggest them as choices
and not suggest logical names. Although logical names aren't suggested, they can still
be used if typed indirectly.
For example, imagine you've added a Custom Field to a table in Dataverse. A logical
name will be assigned for you by the system, which you can modify only when creating
the field. The result would look similar to:
When authoring a reference to a field of Accounts, the suggestion will be made to use
'Custom Field' since this is the display name. Single quotes must be used because this
name has a space in it:
After selecting the suggestion, 'Custom Field' is shown in the formula bar and the data is
retrieved:
Although it isn't suggested, we could also use the logical name for this field. This will
result in the same data being retrieved. Single quotes are not required since this name
doesn't contain spaces or special characters:
Behind the scenes, a mapping is maintained between the display names seen in
formulas and the underlying logical names. Since logical names must be used to interact
with the data source, this mapping is used to convert from the current display name to
the logical name automatically and that is what is seen in the network traffic. This
mapping is also used to convert back to logical names to switch into new display names,
for example, if a display name changes or a maker in a different language edits the app.
7 Note
Logical names are not translated when moving an app between environments. For
Dataverse system table and field names, this should not be a problem as logical
names are consistent across environments. But any custom fields, such as
cra3a_customfield in this example above, may have a different environment prefix
(cra3a in this case). Display names are preferred as they can be matched against
display names in the new environment.
Name disambiguation
Since display names aren't unique, the same display name may appear more than once
in the same table. When this happens, the logical name will be added to the end of the
display name in parenthesis for one of more of the conflicting names. Building on the
example above, if there was a second field with the same display name of Custom Field
with a logical name of cra3a_customfieldalt then the suggestions would show:
Name disambiguation strings are added in other situations where name conflicts occur,
such as the names of table, choices, and other Dataverse items.
Disambiguation operator
Some functions create record scopes for accessing the fields of table while processing
each record, such as Filter, AddColumns, and Sum. Field names added with the record
scope override the same names from elsewhere in the app. When this happens, you can
still access values from outside the record scope with the @ disambiguation operator:
To access values from nested record scopes, use the @ operator with the name of
the table being operated upon using this pattern:
Table[@FieldName]
To access global values, such as data sources, collections, and context variables,
use the pattern [@ObjectName] (without a table designation).
Overview
Use the Set function to set the value of a global variable, which temporarily holds a
piece of information, such as the number of times the user has selected a button or the
result of a data operation.
Global variables are available throughout your app on all screens. These are the simplest
kind of variables and fill the needs of most situations. There are also context variables
which are scoped to a single screen and collections that allow row level modifications to
tables. For more information about these other options, review Understand variables.
Power Apps are based on formulas that automatically recalculate as the user interacts
with an app. Any formulas that depend on a variable will automatically update when it
changes. However, the variable won't be automatically updated if the value of the
formula used in the Set function changes. This requires the app maker to manually
update the variable, which can be error prone and harder for others to understand.
Before you use a variable, review Understand variables.
Description
Global variables are implicitly created by using the Set function. No explicit declaration
is required. If you remove all the Set functions for a global variable, that global variable
will cease to exist. To clear a variable, set its value to the result of the Blank function.
You can see your variables' values, definitions, and uses with the Variables view under
the File menu in Power Apps Studio.
As the examples later in this topic show, global variables can hold several kinds of
information, including these:
a single value
a record
a table
an object reference
any result from a formula
A global variable holds its value until the app is closed. Once closed, the global
variable's value will be lost and must be recreated when the app is loaded again.
Global variables cannot use the same name as an existing collection or control. It can
use the same name as a context variable. To disambiguate between the two, use the
disambiguation operator.
Set has no return value, and you can use it only within a behavior formula.
Syntax
Set( VariableName, Value )
Examples
Formula Description Result
Set( Counter, Counter + 1 ) Increments the value of the Counter has the value
Counter global variable 3.
from the previous example
to 3.
Description
The SetFocus function gives a control the input focus. The user's keystrokes are then
received by that control, allowing them to type into a text input control or use the Enter
key to select a button. The user can also use the Tab key, touch, mouse, or other gesture
to move the input focus themselves. Tab key behavior is governed by the TabIndex
property.
Use the SetFocus function to set the focus when (each with an example below):
a newly exposed or enabled input control, to guide the user in what comes next
and for faster data entry.
a form is validated, to focus and display the offending input control for quick
resolution.
a screen is displayed, to focus the first input control with the OnVisible property of
the Screen.
The control with focus may be visually different based on the FocusedBorderColor and
FocusedBorderThickness properties.
Limitations
SetFocus can only be used with:
Button control
Icon control
Image control
Label control
TextInput control
You cannot set the focus to controls that are within a Gallery control, Edit form control,
or Component. SetFocus can be used with a control in a scrollbale screen.
You cannot set the focus to controls that are within a Container control.
You can only set the focus to controls on the same screen as the formula containing the
SetFocus call.
Attempting to set the focus to a control that has its DisplayMode property set to
Disabled has no effect. Focus will remain where it was previously.
On Apple iOS, the soft keyboard will only be displayed automatically if SetFocus was
initiated by a direct user action. For example, invoking from a button's OnSelect
property will display the soft keyboard while invoking from a screen's OnVisible will not.
Syntax
SetFocus( Control )
Examples
powerappa-dot
SetFocus( BillingName )
The Tab key can also be used to move focus quickly from one field to another. To better
illustrate, the Tab key was not used in the animation.
automatically enable or disable this control based on the state of the check box
control.
13. Set the Default property of the check box to the formula true . This will default the
Billing address to use the same value as the Shipping address.
14. Set the OnCheck property of the check box to the formula Reset( BillingName );
Reset( BillingAddress ) . If the user chooses to sync Shipping and Billing
addresses, this will clear any user input in the Billing address fields allowing the
Default properties on each to pull the values from the corresponding Shipping
address fields.
15. Set the OnUncheck property of the check box to the formula SetFocus(
BillingName ) . If the user chooses to have a different billing address, this will move
the focus to the first control in the Billing address. The controls will have already
been enabled due to their DisplayMode properties.
7 Note
When validating a form, it can be helpful to not only display a message if there is a
problem but to also take the user to the field that is offending. It can be particularly
helpful if the field in question is scrolled off the screen and not visible.
In this animation, the validation button is repeatedly pressed until all the fields have
been filled in properly. Note that the mouse pointer doesn't move down from the top of
the screen. Instead the SetFocus function hsa moved the input focus to the control that
requires attention with this formula:
Power Apps
IsBlank( Street1 ),
IsBlank( Street2 ),
IsBlank( City ),
IsBlank( County ),
IsBlank( StateProvince ),
IsBlank( PostalCode ),
IsBlank( Phone ),
7 Note
Similar to exposing an input control, when displaying a data entry screen it is helpful to
focus the first input control for faster data entry.
In this animation, the data entry screen on the left is not using SetFocus. Upon display
no input control has focus, requiring the user to tab, touch, mouse, or use another
means to focus the Name field before a value can be typed into it.
On the right we have exactly the same app with the OnVisible property of the data entry
screen set to this formula:
Power Apps
SetFocus( Name )
This sets the focus to the Name field automatically. The user can begin typing and
tabbing between fields immediately with no prior action required.
The SetProperty function simulates interactions with input controls as if the user had
entered or set a value on the control. This function is only available if you are writing
tests in the Power Apps Test Studio. The following properties can be set using the
SetProperty function.
Syntax
SetProperty(Control Property, value)
Control Property – Required. The control property to set on behalf of the user.
Value – Required. The value of the property to set on behalf of the user.
Examples
Control Property Example expression
See Also
Test Studio Overview
Description
The Sequence function generates a single column table of sequential numbers, such as
1, 2, 3. The name of the column is Value. Sequence( 4 ) is equivalent to [1,2,3,4] .
Use Sequence with the ForAll function to iterate a specific number of times. For
example, the following formula adds 10 random numbers to the collection
MyRandomNumbers:
Power Apps
ForAll can also be used to transform the value into other data types and return a new
table. For example, the following formula returns a table of the next 10 days:
Power Apps
The number of records to generate is rounded down to the nearest whole number and
must be in the range 0 to 50,000. Generating a table with zero records results in an
empty table.
7 Note
Syntax
Sequence( Records [, Start [, Step ] ] )
Examples
Basic usage
Actual
numbers will
vary.
Character map
See the Char function reference for two Sequence functions working together to display
a character map in a two-dimensional layout.
Chessboard
See the As operator reference for two Sequence functions working together to create a
chessboard in a text string and in two nested galleries.
AddColumns, DropColumns,
RenameColumns, and ShowColumns
functions in Power Apps
Article • 02/23/2023 • 6 minutes to read
Overview
These functions shape a table by adjusting its columns:
Reduce a table that contains multiple columns down to a single column for use
with single-column functions, such as Lower or Abs.
Add a calculated column to a table (for example, a Total Price column that shows
the results of multiplying Quantity by Unit Price).
Rename a column to something more meaningful, for display to users or for use in
formulas.
A table is a value in Power Apps, just like a string or a number. You can specify a table as
an argument in a formula, and functions can return a table as a result.
7 Note
The functions that this topic describes don't modify the original table. Instead, they
take that table as an argument and return a new table with a transform applied. See
working with tables for more details.
You can't modify the columns of a data source by using these functions. You must
modify the data at its source. You can add columns to a collection with the Collect
function. See working with data sources for more details.
Description
The AddColumns function adds a column to a table, and a formula defines the values in
that column. Existing columns remain unmodified.
The DropColumns function excludes columns from a table. All other columns remain
unmodified. DropColumns excludes columns, and ShowColumns includes columns.
The ShowColumns function includes columns of a table and drops all other columns.
You can use ShowColumns to create a single-column table from a multi-column table.
ShowColumns includes columns, and DropColumns excludes columns.
For all these functions, the result is a new table with the transform applied. The original
table isn't modified. You can't modify an existing table with a formula. SharePoint,
Microsoft Dataverse, SQL Server, and other data sources provide tools for modifying the
columns of lists, tables, and tables, which are often referred to as the schema. The
functions in this topic only transform an input table, without modifying the original, into
an output table for further use.
The arguments to these functions support delegation. For example, a Filter function
used as an argument to pull in related records searches through all listings, even if the
'[dbo].[AllListings]' data source contains a million rows:
Power Apps
AddColumns( RealEstateAgents,
"Listings",
However, the output of these functions is subject to the non-delegation record limit. In
this example, only 500 records are returned even if the RealEstateAgents data source
has 501 or more records.
If you use AddColumns in this manner, Filter must make separate calls to the data
source for each of those first records in RealEstateAgents, which causes a lot of network
chatter. If [dbo](.[AllListings] is small enough and doesn't change often, you could call
the Collect function in OnStart to cache the data source in your app when it starts. As
an alternative, you could restructure your app so that you pull in the related records
only when the user asks for them.
Syntax
AddColumns( Table, ColumnName1, Formula1 [, ColumnName2, Formula2, ... ] )
None of these examples modify the IceCreamSales data source. Each function
transforms the value of the data source as a table and returns that value as the result.
DropColumns(
Performs the following table transforms in
RenameColumns(
order, starting from the inside of the formula:
AddColumns(
IceCreamSales, 1. Adds a Revenue column based on the
"Revenue",
per-record calculation of UnitPrice *
UnitPrice * QuantitySold ),
Quantity.
"UnitPrice", "Price" ),
2. Renames UnitPrice to Price.
"Quantity" ) 3. Excludes the Quantity column.
Step by step
Let's try some of the examples from earlier in this topic.
1. Create a collection by adding a Button control and setting its OnSelect property to
this formula:
Power Apps
ClearCollect( IceCreamSales,
Table(
2. Run the formula by selecting the button while holding down the Alt key.
3. Add a second Button control, set its OnSelect property to this formula, and then
run it:
Power Apps
ClearCollect( FirstExample,
4. On the File menu, select Collections, and then select IceCreamSales to show that
collection.
As this graphic shows, the second formula didn't modify this collection. The
AddColumns function used IceCreamSales as a read-only argument; the function
didn't modify the table to which that argument refers.
5. Select FirstExample.
As this graphic shows, the second formula returned a new table with the added
column. The ClearCollect function captured the new table in the FirstExample
collection, adding something to the original table as it flowed through the function
without modifying the source:
Map columns in a component
See Map columns.
Shuffle function in Power Apps
Article • 02/23/2023 • 2 minutes to read
Description
The Shuffle function reorders the records of a table.
Shuffle returns a table that has the same columns and number of rows as the argument.
Syntax
Shuffle( Table )
Example
If you stored details about playing cards in a collection named Deck, this formula would
return a copy of that collection that has been randomly shuffled.
Shuffle(Deck)
Acos, Acot, Asin, Atan, Atan2, Cos, Cot,
Degrees, Pi, Radians, Sin, and Tan
functions in Power Apps
Article • 03/17/2023 • 5 minutes to read
Description
Primary functions
The Cos function returns the cosine of its argument, an angle specified in radians.
The Cot function returns the cotangent of its argument, an angle specified in radians.
The Sin function returns the sine of its argument, an angle specified in radians.
The Tan function returns the tangent of its argument, an angle specified in radians.
Inverse functions
The Acos function returns the arccosine, or inverse cosine, of its argument. The
arccosine is the angle whose cosine is the argument. The returned angle is given in
radians in the range 0 (zero) to π.
The Acot function returns the principal value of the arccotangent, or inverse cotangent,
of its argument. The returned angle is given in radians in the range 0 (zero) to π.
The Asin function returns the arcsine, or inverse sine, of its argument. The arcsine is the
angle whose sine is the argument. The returned angle is given in radians in the range
-π/2 to π/2.
The Atan function returns the arctangent, or inverse tangent, of its argument. The
arctangent is the angle whose tangent is the argument. The returned angle is given in
radians in the range -π/2 to π/2.
The Atan2 function returns the arctangent, or inverse tangent, of the specified x and y
coordinates as arguments. The arctangent is the angle from the x-axis to a line that
contains the origin (0, 0) and a point with coordinates (x, y). The angle is given in radians
between -π and π, excluding -π. A positive result represents a counterclockwise angle
from the x-axis; a negative result represents a clockwise angle. Atan2( a, b ) equals
Atan( b/a ), except that a can equal 0 (zero) with the Atan2 function.
Helper functions
The Degrees function converts radians to degrees. π radians equals 180 degrees.
Notes
If you pass a single number to these functions, the return value is a single result. If you
pass a single-column table that contains numbers, the return value is a single-column
table of results with a Value column, one result for each record in the argument's table.
If you have a multi-column table, you can shape it into a single-column table, as
working with tables describes.
If an argument would result in an undefined value, the result is blank. This can happen,
for example, when using inverse functions with arguments that are out of range.
Syntax
Primary Functions
Cos( Radians )
Cot( Radians )
Sin( Radians )
Tan( Radians )
Cos( SingleColumnTable )
Cot( SingleColumnTable )
Sin( SingleColumnTable )
Tan( SingleColumnTable )
Inverse Functions
Acos( Number )
Acot( Number )
Asin( Number )
Atan( Number )
Acos( SingleColumnTable )
Acot( SingleColumnTable )
Asin( SingleColumnTable )
Atan( SingleColumnTable )
Atan2( X, Y )
Helper Functions
Degrees( Radians )
Pi()
Radians( Degrees )
Examples
Single number
Atan2( 5, 3 ) Returns the arctangent of the angle from the x-axis of the line 0.540419...
that contains the origin (0,0) and the coordinate (5,3), which is
approximately 31 degrees.
Atan2( 4, 4 ) Returns the arctangent of the angle from the x-axis of the line 0.785398...
that contains the origin (0,0) and the coordinate (4,4), which is
exactly π/4 radians or 45 degrees.
Single-column table
The examples in this section use a data source that's named ValueTable and that
contains the following data. The last record in the table is π/2 radians or 90 degrees.
Value
0.5
-2
1.570796...
Sin( ValueTable ) Returns the sine of each number A single-column table with a Value
in the table. column containing the following
values: 0.479425, -0.909297..., 1
Sorts a table.
Description
The Sort function sorts a table based on a formula.
The formula is evaluated for each record of the table, and the results are used to sort
the table. The formula must result in a number, a string, or a Boolean value; it can't
result in a table or a record.
Fields of the record currently being processed are available within the formula. Use the
ThisRecord operator or simply reference fields by name as you would any other value.
The As operator can also be used to name the record being processed which can help
make your formula easier to understand and make nested records accessible. For more
information, see the examples below and working with record scope.
To sort first by one column and then by another, you embed a Sort formula within
another. For example, you can use this formula to sort a Contacts table first by a
LastName column and then by a FirstName column: Sort( Sort( Contacts, LastName ),
FirstName )
The SortByColumns function can also be used to sort a table based on one or more
columns.
The parameter list for SortByColumns provides the names of the columns to sort by and
the sort direction per column. Sorting is performed in the order of the parameters
(sorted first by the first column, then the second, and so on). Column names are
specified as strings, requiring double quotes if directly included in the parameter list. For
example, SortByColumns( CustomerTable, "LastName" ).
You can combine SortByColumns with a Drop down or List box control to enable users
to select which column to sort by.
Tables are a value in Power Apps, just like a string or number. They can be passed to and
returned from functions. Sort and SortByColumn don't modify a table; instead they take
a table as an argument and return a new table that has been sorted. See working with
tables for more details.
Delegation
When possible, Power Apps will delegate filter and sort operations to the data source
and page through the results on demand. For example, when you start an app that
shows a Gallery control filled with data, only the first set of records will be initially
brought to the device. As the user scrolls, additional data is brought down from the data
source. The result is a faster start time for the app and access to very large data sets.
However, delegation may not always be possible. Data sources vary on what functions
and operators they support with delegation. If complete delegation of a formula isn't
possible, the authoring environment will flag the portion that can't be delegated with a
warning. When possible, consider changing the formula to avoid functions and
operators that can't be delegated. The delegation list details which data sources and
operations can be delegated.
If delegation is not possible, Power Apps will pull down only a small set of records to
work on locally. Filter and sort functions will operate on a reduced set of records. What
is available in the Gallery may not be the complete story, which could be confusing to
users.
Syntax
Sort( Table, Formula [, SortOrder ] )
7 Note
For SharePoint and Excel data sources that contain column names with
spaces, specify each space as "_x0020_". For example, specify "Column
Name" as "Column_x0020_Name".
7 Note
For SharePoint and Excel data sources that contain column names with
spaces, specify each space as "_x0020_". For example, specify "Column
Name" as "Column_x0020_Name".
Examples
For the following examples, we'll use the IceCream data source, which contains the data
in this table:
Sort( IceCream, Quantity, Sorts IceCream by its Quantity column. The Quantity
SortOrder.Descending )
column contains numbers, so the sort is done
numerically. The sort order has been specified as
SortByColumns( IceCream, descending.
"Quantity",
SortOrder.Descending )
Sort( IceCream, Quantity + Sorts IceCream by the sum of its Quantity and OnOrder
OnOrder ) columns for each record individually. The sum is a
number, so the table is sorted numerically. By default, the
sort order is ascending. Since we are sorting by a formula
and not by raw column values, there is no equivalent
using SortByColumns.
Sort( Sort( IceCream, Sorts IceCream first by its OnOrder column, and then by
OnOrder ), Quantity )
its Quantity column. Note that "Pistachio" rose above
"Vanilla" in the first sort based on OnOrder, and then
SortByColumns( IceCream, together they moved to their appropriate place based on
"OnOrder", Quantity.
SortOrder.Ascending,
"Quantity",
SortOrder.Ascending )
SortByColumns( IceCream, Sorts IceCream by it's Flavor column based on the single
"Flavor", column table containing "Pistachio" and "Strawberry".
[ "Pistachio", "Strawberry" ] Records which have a Flavor of "Pistachio" will appear
) first in the result, followed by records that contain
"Strawberry". For values in the Flavor column that are not
matched, such as "Vanilla", they will appear after the
items that were matched.
Step by step
To run these examples yourself, create the IceCream data source as a collection:
Sort
1. Add another button, and set its OnSelect property to this formula:
2. Press F5, select the new button, and then press Esc.
3. Select Collections on the File menu to display both collections, and then press Esc
to return to the default workspace.
4. Repeat the last three steps, but change the name of the collection that you want to
create, and replace the Sort formula with a different formula from the table of
examples earlier in this section that uses Sort.
SortByColumns
1. Add another button, and set its OnSelect property to this formula:
2. Press F5, select the new button, and then press Esc.
3. Select Collections on the File menu to display all three collections, and then press
Esc to return to the default workspace.
4. Repeat the last three steps, but change the name of the collection that you want to
create, and replace the SortByColumns formula with a different formula from the
table of examples earlier in this section that uses SortByColumns.
Sort and SortByColumns functions in
Power Apps
Article • 03/08/2023 • 7 minutes to read
Sorts a table.
Description
The Sort function sorts a table based on a formula.
The formula is evaluated for each record of the table, and the results are used to sort
the table. The formula must result in a number, a string, or a Boolean value; it can't
result in a table or a record.
Fields of the record currently being processed are available within the formula. Use the
ThisRecord operator or simply reference fields by name as you would any other value.
The As operator can also be used to name the record being processed which can help
make your formula easier to understand and make nested records accessible. For more
information, see the examples below and working with record scope.
To sort first by one column and then by another, you embed a Sort formula within
another. For example, you can use this formula to sort a Contacts table first by a
LastName column and then by a FirstName column: Sort( Sort( Contacts, LastName ),
FirstName )
The SortByColumns function can also be used to sort a table based on one or more
columns.
The parameter list for SortByColumns provides the names of the columns to sort by and
the sort direction per column. Sorting is performed in the order of the parameters
(sorted first by the first column, then the second, and so on). Column names are
specified as strings, requiring double quotes if directly included in the parameter list. For
example, SortByColumns( CustomerTable, "LastName" ).
You can combine SortByColumns with a Drop down or List box control to enable users
to select which column to sort by.
Tables are a value in Power Apps, just like a string or number. They can be passed to and
returned from functions. Sort and SortByColumn don't modify a table; instead they take
a table as an argument and return a new table that has been sorted. See working with
tables for more details.
Delegation
When possible, Power Apps will delegate filter and sort operations to the data source
and page through the results on demand. For example, when you start an app that
shows a Gallery control filled with data, only the first set of records will be initially
brought to the device. As the user scrolls, additional data is brought down from the data
source. The result is a faster start time for the app and access to very large data sets.
However, delegation may not always be possible. Data sources vary on what functions
and operators they support with delegation. If complete delegation of a formula isn't
possible, the authoring environment will flag the portion that can't be delegated with a
warning. When possible, consider changing the formula to avoid functions and
operators that can't be delegated. The delegation list details which data sources and
operations can be delegated.
If delegation is not possible, Power Apps will pull down only a small set of records to
work on locally. Filter and sort functions will operate on a reduced set of records. What
is available in the Gallery may not be the complete story, which could be confusing to
users.
Syntax
Sort( Table, Formula [, SortOrder ] )
7 Note
For SharePoint and Excel data sources that contain column names with
spaces, specify each space as "_x0020_". For example, specify "Column
Name" as "Column_x0020_Name".
7 Note
For SharePoint and Excel data sources that contain column names with
spaces, specify each space as "_x0020_". For example, specify "Column
Name" as "Column_x0020_Name".
Examples
For the following examples, we'll use the IceCream data source, which contains the data
in this table:
Sort( IceCream, Quantity, Sorts IceCream by its Quantity column. The Quantity
SortOrder.Descending )
column contains numbers, so the sort is done
numerically. The sort order has been specified as
SortByColumns( IceCream, descending.
"Quantity",
SortOrder.Descending )
Sort( IceCream, Quantity + Sorts IceCream by the sum of its Quantity and OnOrder
OnOrder ) columns for each record individually. The sum is a
number, so the table is sorted numerically. By default, the
sort order is ascending. Since we are sorting by a formula
and not by raw column values, there is no equivalent
using SortByColumns.
Sort( Sort( IceCream, Sorts IceCream first by its OnOrder column, and then by
OnOrder ), Quantity )
its Quantity column. Note that "Pistachio" rose above
"Vanilla" in the first sort based on OnOrder, and then
SortByColumns( IceCream, together they moved to their appropriate place based on
"OnOrder", Quantity.
SortOrder.Ascending,
"Quantity",
SortOrder.Ascending )
SortByColumns( IceCream, Sorts IceCream by it's Flavor column based on the single
"Flavor", column table containing "Pistachio" and "Strawberry".
[ "Pistachio", "Strawberry" ] Records which have a Flavor of "Pistachio" will appear
) first in the result, followed by records that contain
"Strawberry". For values in the Flavor column that are not
matched, such as "Vanilla", they will appear after the
items that were matched.
Step by step
To run these examples yourself, create the IceCream data source as a collection:
Sort
1. Add another button, and set its OnSelect property to this formula:
2. Press F5, select the new button, and then press Esc.
3. Select Collections on the File menu to display both collections, and then press Esc
to return to the default workspace.
4. Repeat the last three steps, but change the name of the collection that you want to
create, and replace the Sort formula with a different formula from the table of
examples earlier in this section that uses Sort.
SortByColumns
1. Add another button, and set its OnSelect property to this formula:
2. Press F5, select the new button, and then press Esc.
3. Select Collections on the File menu to display all three collections, and then press
Esc to return to the default workspace.
4. Repeat the last three steps, but change the name of the collection that you want to
create, and replace the SortByColumns formula with a different formula from the
table of examples earlier in this section that uses SortByColumns.
Split function in Power Apps
Article • 03/17/2023 • 3 minutes to read
Description
The Split function breaks a text string into a table of substrings. Use Split to break up
comma delimited lists, dates that use a slash between date parts, and in other situations
where a well defined delimiter is used.
A separator string is used to break the text string apart. The separator can be zero, one,
or more characters that are matched as a whole in the text string. Using a zero length or
blank string results in each character being broken out individually. The matched
separator characters are not returned in the result. If no separator match is found, then
the entire text string is returned as a single result.
Use the Concat function to recombine the string without the separators.
The examples show how Split can be used with the First and Last functions to extract a
single delimited substring. The Match function is often a more concise and powerful
choice for regular expressions.
Syntax
Split( Text, Separator )
Examples
Basic usage
Split( Splits the different fruits apart, based on the comma A single-column
"Apples, separator. The split is performed based on only the comma table with a Value
Oranges, and not the space after it, resulting in a space at the front of column containing
Bananas", " Oranges" and " Bananas". the following
"," ) values: "Apples",
" Oranges",
" Bananas"
TrimEnds( Same as the previous example, but in this case the space is A single-column
Split( removed by the TrimEnds function, operating on the single table with a Value
"Apples, column table that is produced by Split. We could have also column containing
Oranges, used the separator ", " which includes the space after the the following
Bananas", comma, but that wouldn't have worked properly if there's no values: "Apples",
"," ) ) space or there are two spaces. "Oranges",
"Bananas"
Split( Splits the date apart, using a forward slash as the separator. A single-column
"08/28/17", table with a Value
"/" ) column containing
the following
values: "08", "28",
"17"
Different delimiters
Split( Splits the words apart, using a comma as the A single-column table with a Value
"Hello, separator. The second result starts with a space column containing the following
World", since it is the character immediately following values: "Hello", " World"
"," ) the comma.
Split( Splits the string apart, using the character "o" A single-column table with a Value
"Hello, as the separator. column containing the following
World", values: "Hell", ", W", "rld"
"o" )
Split( Splits the string apart, using the single A single-column table with a Value
"Hello, character "l" as the separator. Since there were column containing the following
World", no characters between both the l's in Hello, a values: "He", Blank(), "o, Wor", "d"
"l" ) blank value was returned.
Split( Splits the string apart, using the double A single-column table with a Value
"Hello, character "ll" as the separator. column containing the following
World", values: "He", "o, World"
"ll" )
Formula Description Result
Split( Splits the string apart, using the percent sign as A single-column table with a Value
"Hello, the separator. Since this separator doesn't column containing the following
World", appear in the string, the entire string is value: "Hello, World"
"%" ) returned as one result.
Split( Splits the string apart, using an empty string as A single-column table with a Value
"Hello, the separator (zero characters). This will break column containing the following
World", the string on each character. values: "H", "e", "l", "l", "o", ",", " ",
"" ) "W", "o", "r", "l", "d"
Substring extraction
Calculates absolute values, logarithms, square roots, and the results of raising e or any
number to specified powers.
Description
The Abs function returns the non-negative value of its argument. If a number is
negative, Abs returns the positive equivalent.
The Exp function returns e raised to the power of its argument. The transcendental
number e begins 2.7182818...
The Power function returns a number raised to a power. It's equivalent to using the ^
operator.
The Log function returns the logarithm of its first argument in the base specified by its
second argument (or 10 if not specified).
The Sqrt function returns the number that, when multiplied by itself, equals its
argument.
If you pass a single number, the return value is a single result based on the function
called. If you pass a single-column table that contains numbers, the return value is a
single-column table of results in a Value column, one result for each record in the
argument's table. If you have a multi-column table, you can shape it into a single-
column table, as working with tables describes.
If an argument would result in an undefined valued, the result is blank. Which can
happen with square roots and logarithms of negative numbers.
Syntax
Abs( Number )
Exp( Number )
Ln( Number )
Sqrt( Number )
Number - Required. Number to operate on.
Abs( SingleColumnTable )
Exp( SingleColumnTable )
Ln( SingleColumnTable )
Sqrt( SingleColumnTable )
Examples
Single number
Ln( 100 ) Returns the natural logarithm (base e) of the number 100. 4.605170...
Single-column table
The examples in this section use a data source that's named ValueTable and that
contains this data:
Value
-4
Sqrt( ValueTable ) Returns the square root A single-column table with a Value column
of each number in the containing the following values: 3, Blank(),
table 1.414213...
Step-by-step example
1. Add a Text input control, and name it Source.
2. Add a Label control, and set its Text property to this formula:
Description
The EndsWith function tests whether one text string ends with another.
The StartsWith function tests whether one text string begins with another.
For both functions, the tests are case insensitive. The return value of both is a Boolean
true or false.
Use EndsWith and StartsWith with the Filter function to search the data within your
app. You can also use the in operator or the Search function to look anywhere within
text strings, not just at the beginning or end. Your choice of functions will depend on
the needs of your app and which function can be delegated for your particular data
source. If one of these functions can't be delegated, a delegation warning will appear at
authoring time to warn you of this limitation.
Syntax
EndsWith( Text, EndText )
Examples
Formula Description Result
Formula Description Result
EndsWith( Tests whether "Hello World" ends with "world". The test is case true
"Hello World", insensitive.
"world" )
EndsWith( Tests whether "Good bye" ends with "good". The EndText argument false
"Good bye", ("good") appears in the text but not at the end.
"good" )
EndsWith( Tests whether "Always say hello" ends with "hello". true
"Always say
hello", "hello" )
EndsWith( "Bye Tests whether "Bye bye" ends with an empty text string (Len returns true
bye", "" ) 0). Easing its use in Filter expressions, EndsWith is defined to return
true in this case.
StartsWith( Tests whether "Hello World" begins with "hello". The test is case true
"Hello World", insensitive.
"hello" )
StartsWith( Tests whether "Always say hello" begins with "hello". Although false
"Always say "hello" appears in the text, it doesn't appear at the beginning.
hello", "hello" )
StartsWith( "Bye Tests whether "Bye bye" starts with an empty text string (Len returns true
bye", "" ) 0). Easing its use in Filter expressions, StartsWith is defined to return
true in this case.
The examples in the rest of this topic show the results of searching a Customers list that
contains this data:
To create this data source as a collection, create a Button control and set its OnSelect
property to this formula:
As in this example, you can show a list of records in a Gallery control at the bottom of a
screen. Near the top of the screen, you can add a Text input control, named
SearchInput, so that users can specify which records interest them.
As the user types characters in SearchInput, the results in the gallery are automatically
filtered. In this case, the gallery is configured to show records for which the name of the
customer (not the name of the company) starts with the sequence of characters in
SearchInput.If the user types co in the search box, the gallery shows these results:
To filter based on the Name column, set the Items property of the gallery control to one
of these formulas:
Filter( Filters the Customers data source for records in which the search
Customers, string appears at the start of the Name column. The test is case
StartsWith( insensitive. If the user types co in the search box, the gallery shows
Name, Colleen Jones and Cole Miller. The gallery doesn't show Mike
SearchInput.Text Collins because the Name column for that record doesn't start with
)) the search string.
Filter( Filters the Customers data source for records in which the search
Customers, string appears anywhere in the Name column. The test is case
SearchInput.Text insensitive. If the user types co in the search box, the gallery shows
in Name ) Colleen Jones, Cole Miller, and Mike Collins because the search
string appears somewhere in the Name column of all of those
records.
Search( Similar to using the in operator, the Search function searches for a
Customers, match anywhere within the Name column of each record. Note that
SearchInput.Text, you must enclose the column name in double quotation marks.
"Name" )
You can expand your search to include the Company column as well as the Name
column:
Filter( Filters the Customers data source for records in which either the
Customers, Name column or the Company column starts with the search string
StartsWith( (for example, co). The || operator is true if either StartsWith function
Name, is true.
SearchInput.Text
) || StartsWith(
Company,
SearchInput.Text
))
Filter( Filters the Customers data source for records in which either the
Customers, Name column or the Company column contains the search string
SearchInput.Text (for example, co) anywhere within it.
in Name ||
SearchInput.Text
in Company )
Search( Similar to using the in operator, the Search function searches the
Customers, Customers data source for records in which either the Name column
SearchInput.Text, or the Company column contains the search string (for example, co)
"Name", anywhere within it. The Search function is easier to read and write
"Company" ) than Filter if you want to specify multiple columns and multiple in
operators. Note that you must enclose the names of the columns in
double quotation marks.
Average, Max, Min, StdevP, Sum, and
VarP functions in Power Apps
Article • 02/23/2023 • 2 minutes to read
Description
The Average function calculates the average, or arithmetic mean, of its arguments.
Fields of the record currently being processed are available within the formula. Use the
ThisRecord operator or simply reference fields by name as you would any other value.
The As operator can also be used to name the record being processed which can help
make your formula easier to understand and make nested records accessible. For more
information, see the examples below and working with record scope.
These functions operate on numeric values only. Other types of values, such as strings or
records, are ignored. Use the Value function to convert a string into a number.
The Average, Max, Min, and Sum functions can be delegated when used with a data
source that supports delegation for these functions. However, StdevP and VarP can't be
delegated for any data sources. If delegation is not supported, only the first portion of
the data will be retrieved and then the function applied locally. The result may not
represent the complete story. A delegation warning will appear at authoring time to
remind you of this limitation and to suggest switching to delegable alternatives where
possible. For more information, see the delegation overview.
Syntax
Average( NumericalFormula1, [ NumericalFormula2, ... ] )
Examples
Step by step
Let's say that you had a data source named Sales that contained a CostPerUnit column
and a UnitsSold column, and you set the Text property of a label to this function:
The label would show total sales by multiplying the values in those columns for each
record and then adding the results from all records together:
As a different example, let's say that you had sliders that were named Slider1, Slider2,
and Slider3 and a label with its Text property set to this formula:
Sum(Slider1.Value, Slider2.Value, Slider3.Value): The label would show the sum of all
values to which the sliders were set.
Description
The Replace function identifies the text to replace by starting position and length.
The Substitute function identifies the text to replace by matching a string. If more than
one match is found, you can replace all of them or specify one to replace.
If you pass a single string, the return value is the modified string. If you pass a single-
column table that contains strings, the return value is a single-column table with a Value
column of modified strings. If you have a multi-column table, you can shape it into a
single-column table, as working with tables describes.
Syntax
Replace( String, StartingPosition, NumberOfCharacters, NewString )
Examples
Formula Description Result
Substitute( "Quarter 1, 2018", "1", "2", 1 ) Substitutes only the first "Quarter 2, 2018"
instance of "1" with "2" because
the fourth argument
(InstanceNumber) is provided
with a 1.
Formula Description Result
Substitute( "Quarter 1, 2011", "1", "2", 3 ) Substitutes only the third "Quarter 1, 2012"
instance of "1" with "2" because
the fourth argument
(InstanceNumber) is provided
with a 3.
Substitute( "Quarter 1, 2011", "1", "2" ) Substitutes all instances of "1" "Quarter 2, 2022"
with "2" because the fourth
argument (InstanceNumber)
isn't provided.
Replace(
Replaces the ninth character in A single-column
[ "Quarter 1, 2018",
each record of the single- table with a Value
"Quarter 2, 2011",
column table with "3". column containing
"Quarter 4, 2019" ],
the following
9, 1, "3" ) values:
[ "Quarter 3, 2018",
"Quarter 3, 2011",
"Quarter 3, 2019" ]
Substitute(
Because the fourth argument A single-column
[ "Qtr 1, 2018",
(InstanceNumber) is provided table with a Value
"Quarter 1, 2011",
with a value of 1, substitutes column containing
"Q1, 2019" ],
only the first instance of "1" in the following
"1", "3", 1 ) each record of the single- values:
column table with "3". [ "Qtr 3, 2018",
"Quarter 3, 2011",
"Q3, 2019" ]
Substitute(
Because the fourth argument A single-column
[ "Qtr 1, 2018",
(InstanceNumber) isn't table with a Value
"Quarter 1, 2011",
provided, substitutes all column containing
"Q1, 2019" ],
instances of "1" in each record the following
"1", "3" ) of the single-column table with values:
"3". [ "Qtr 3, 2038",
"Quarter 3, 2033",
"Q3, 2039" ]
EditForm, NewForm, SubmitForm,
ResetForm, and ViewForm functions in
Power Apps
Article • 02/23/2023 • 5 minutes to read
View, edit, or create an item, save the contents, and reset the controls in an Edit form
control.
Overview
These functions change the state of the Edit form control. The form control can be in
one of these modes:
Mode Description
FormMode.Edit The form is populated with an existing record and the user can modify the
values of the fields. Once complete, the user can save the changes to the
record.
FormMode.New The form is populated with default values and the user can modify the values
of the fields. Once complete, the user can add the record to the data source.
FormMode.View The form is populated with an existing record but the user cannot modify the
values of the fields.
Description
These functions are often invoked from the OnSelect formula of a Button or Image
control so that the user can save edits, abandon edits, or create a record. You can use
controls and these functions together to create a complete solution.
SubmitForm
Use the SubmitForm function in the OnSelect property of a Button control to save any
changes in a Form control to the data source.
Before submitting any changes, this function checks for validation issues with any field
that's marked as required or that has one or more constraints on its value. This behavior
matches that of the Validate function.
SubmitForm also checks the Valid property of the Form, which is an aggregation of all
the Valid properties of the Card controls that the Form control contains. If a problem
occurs, the data isn't submitted, and the Error and ErrorKind properties of the Form
control are set accordingly.
If successful, the Form's OnSuccess behavior runs, and the Error and ErrorKind
properties are cleared. If the form was in FormMode.New mode, it is returned to
FormMode.Edit mode.
If unsuccessful, the Form's OnFailure behavior runs, and the Error and ErrorKind
properties are set accordingly. The mode of the form is unchanged.
EditForm
The EditForm function changes the Form control's mode to FormMode.Edit. In this
mode, the contents of the Form control's Item property are used to populate the form.
If the SubmitForm function runs when the form is in this mode, a record is changed, not
created. FormMode.Edit is the default for the Form control.
NewForm
The NewForm function changes the Form control's mode to FormMode.New. In this
mode, the contents of the Form control's Item property are ignored, and the default
values of the Form's DataSource property populate the form. If the SubmitForm
function runs when the form is in this mode, a record is created, not changed.
ResetForm
The ResetForm function resets the contents of a form to their initial values, before the
user made any changes. If the form is in FormMode.New mode, the form is reset to
FormMode.Edit mode. The OnReset behavior of the form control also runs. You can also
reset individual controls with the Reset function but only from within the form.
ViewForm
The ViewForm function changes the Form control's mode to FormMode.View. In this
mode, the contents of the Form control's Item property are used to populate the form.
The SubmitForm and ResetForm functions have no effect when in this mode.
DisplayMode Property
The current mode can be read through the Mode property. The mode also determines
the value of the DisplayMode property, which can be used by data cards and controls
within the form control. Often, the data card's DisplayMode property will be set to
Parent.DisplayMode (referencing the form) as will the control's DisplayMode property
(referencing the data card):
FormMode.Edit DisplayMode.Edit Data cards and controls are editable, ready to accept
changes to a record.
FormMode.New DisplayMode.Edit Data cards and controls are editable, ready to accept a
new record.
FormMode.View DisplayMode.View Data cards and controls are not editable and optimized
for viewing.
Syntax
SubmitForm( FormName )
EditForm( FormName )
NewForm( FormName )
ResetForm( FormName )
FormName - Required. Form control to reset to initial values. Also switches the
form from FormMode.New mode to FormMode.Edit mode.
ViewForm( FormName )
1. Add a Button control, set its Text property to show Save, and set its OnSelect
property to this formula:
SubmitForm( EditForm )
2. Set the OnFailure property of a Form control to blank and its OnSuccess property
to this formula:
Back()
3. Name a Label control ErrorText, and set its Text property to this formula:
EditForm.Error
When the user selects the Save button, any changes in the Form control are
submitted to the underlying data source.
If the submission succeeds, any changes are saved or, if the Form control is in
New mode, a record is created. ErrorText is blank and the previous screen
reappears.
If the submission fails, ErrorText shows a user-friendly error message, and the
current screen remains visible so that the user can correct the problem and
try again.
4. Add a Button control, set its Text property to show Cancel, and set its OnSelect
property to this formula:
When the user selects the Cancel button, the values in the Form control are reset
to what they were before the user started to edit it, the previous screen reappears,
and the Form control is returned to Edit mode if it was in New mode.
5. Add a Button control, set its Text property to show New, and set its OnSelect
property to this formula:
When the user selects the New button, the Form control switches to New mode,
the default values for the Form control's data source populate that control, and the
screen that contains the Form control appears. When the SubmitForm function
runs, a record is created instead of updated.
Average, Max, Min, StdevP, Sum, and
VarP functions in Power Apps
Article • 02/23/2023 • 2 minutes to read
Description
The Average function calculates the average, or arithmetic mean, of its arguments.
Fields of the record currently being processed are available within the formula. Use the
ThisRecord operator or simply reference fields by name as you would any other value.
The As operator can also be used to name the record being processed which can help
make your formula easier to understand and make nested records accessible. For more
information, see the examples below and working with record scope.
These functions operate on numeric values only. Other types of values, such as strings or
records, are ignored. Use the Value function to convert a string into a number.
The Average, Max, Min, and Sum functions can be delegated when used with a data
source that supports delegation for these functions. However, StdevP and VarP can't be
delegated for any data sources. If delegation is not supported, only the first portion of
the data will be retrieved and then the function applied locally. The result may not
represent the complete story. A delegation warning will appear at authoring time to
remind you of this limitation and to suggest switching to delegable alternatives where
possible. For more information, see the delegation overview.
Syntax
Average( NumericalFormula1, [ NumericalFormula2, ... ] )
Examples
Step by step
Let's say that you had a data source named Sales that contained a CostPerUnit column
and a UnitsSold column, and you set the Text property of a label to this function:
The label would show total sales by multiplying the values in those columns for each
record and then adding the results from all records together:
As a different example, let's say that you had sliders that were named Slider1, Slider2,
and Slider3 and a label with its Text property set to this formula:
Sum(Slider1.Value, Slider2.Value, Slider3.Value): The label would show the sum of all
values to which the sliders were set.
Determines whether any condition in a set is true (If) or the result of a formula matches
any value in a set (Switch) and then returns a result or executes an action.
Description
The If function tests one or more conditions until a true result is found. If such a result is
found, a corresponding value is returned. If no such result is found, a default value is
returned. In either case, the returned value might be a string to show, a formula to
evaluate, or another form of result.
The Switch function evaluates a formula and determines whether the result matches any
value in a sequence that you specify. If a match is found, a corresponding value is
returned. If no match is found, a default value is returned. In either case, the returned
value might be a string to show, a formula to evaluate, or another form of result.
If and Switch are very similar, but you should use the best function for your situation:
Use If to evaluate a single condition. The most common syntax for this function is
If( Condition, ThenResult, DefaultResult ), which provides the common “if … then …
else …” pattern seen in other programming tools.
Use If to evaluate multiple unrelated conditions. In Power Apps (unlike Microsoft
Excel), you can specify multiple conditions without having to nest If formulas.
Use Switch to evaluate a single condition against multiple possible matches. You
can also use If in this case, but you'd need to repeat the formula for each possible
match.
You can use both of these functions in behavior formulas to branch between two or
more actions. Only one branch will trigger an action. Conditions and matches are
evaluated in order, and they stop if a condition is true or a match is found.
Blank is returned if no conditions are true, no matches are found, and you don't specify
a default result.
Syntax
If( Condition, ThenResult [, DefaultResult ] )
Examples
Values in formulas
In the following examples, a Slider control (named Slider1) has a value of 25.
If( Slider1.Value = 25, The condition is true, and the corresponding result "Result1"
"Result1" ) is returned.
If( Slider1.Value = 25, The condition is true, and the corresponding result "Result1"
"Result1", "Result2" ) is returned.
If( Slider1.Value = 25, The first condition is true, and the corresponding "Result1"
"Result1", result is returned. The second condition is also
Slider1.Value > 0, true, but it isn't evaluated because it appears later
"Result2" ) in the argument list than a condition that evaluates
to true.
Formula Description Result
If( IsBlank( Slider1.Value ), The first condition is false because the slider isn't "Result2"
"Result1", blank. The second condition is true because the
IsNumeric( Slider1.Value ), slider's value is a number, and the corresponding
"Result2" ) result is returned.
If( Slider1.Value > 1000, Both the first and second conditions are false, a "Result3"
"Result1", DefaultResult was provided, and it's returned.
Slider1.Value > 50,
"Result2", "Result3")
Switch( Slider1.Value, 25, The slider's value matches the first value to be "Result1"
"Result1" ) checked, and the corresponding result is returned.
Switch( Slider1.Value, 20, The slider's value matches the second value to be "Result2"
"Result1", 25, "Result2", checked, and the corresponding result is returned.
30, "Result3" )
Switch( Slider1.Value, 20, The slider's value doesn't match any value to be "DefaultResult"
"Result1", 10, "Result2", 0, checked. A DefaultResult was provided, so it's
"Result3", "DefaultResult" returned.
)
Step by step
1. Add a Text input control, and name it Text1 if it doesn't have that name by default.
3. Add a Label control, and set its Text property to this formula:
If( Value(Text1.Text) < 20, "Order MANY more!", Value(Text1.Text) < 40, "Order
more!", Text1.Text )
The Label control shows Order more! because the value of Text1 is more than 20
but less than 40.
The Label control shows Order MANY more! because the value of Text1 is less
than 20.
The Label control shows the value that you typed because it's more than 40.
Table function in Power Apps
Article • 02/23/2023 • 2 minutes to read
Description
The Table function creates a table from an argument list of records.
The table's columns will be the union of all the properties from all the argument records.
A blank value is added to any column for which a record doesn't include a value.
A table is a value in Power Apps, just like a string or a number. You can specify a table as
an argument for a function, and functions can return a table as a result. Table doesn't
create a permanent table. Instead it returns a temporary table made of its arguments.
You can specify this temporary table as an argument for another function, visualize it in
a gallery, or embed it in another table. See working with tables for more details.
You can also create a single-column table with the [ value1, value2, ... ] syntax.
Syntax
Table( Record1 [, Record2, ... ] )
Table( Untyped )
Examples
Set the Items property of a listbox to this formula:
The gallery shows two records, both of which contain the name and location of an
item. Only one record contains the name of the owner.
Acos, Acot, Asin, Atan, Atan2, Cos, Cot,
Degrees, Pi, Radians, Sin, and Tan
functions in Power Apps
Article • 03/17/2023 • 5 minutes to read
Description
Primary functions
The Cos function returns the cosine of its argument, an angle specified in radians.
The Cot function returns the cotangent of its argument, an angle specified in radians.
The Sin function returns the sine of its argument, an angle specified in radians.
The Tan function returns the tangent of its argument, an angle specified in radians.
Inverse functions
The Acos function returns the arccosine, or inverse cosine, of its argument. The
arccosine is the angle whose cosine is the argument. The returned angle is given in
radians in the range 0 (zero) to π.
The Acot function returns the principal value of the arccotangent, or inverse cotangent,
of its argument. The returned angle is given in radians in the range 0 (zero) to π.
The Asin function returns the arcsine, or inverse sine, of its argument. The arcsine is the
angle whose sine is the argument. The returned angle is given in radians in the range
-π/2 to π/2.
The Atan function returns the arctangent, or inverse tangent, of its argument. The
arctangent is the angle whose tangent is the argument. The returned angle is given in
radians in the range -π/2 to π/2.
The Atan2 function returns the arctangent, or inverse tangent, of the specified x and y
coordinates as arguments. The arctangent is the angle from the x-axis to a line that
contains the origin (0, 0) and a point with coordinates (x, y). The angle is given in radians
between -π and π, excluding -π. A positive result represents a counterclockwise angle
from the x-axis; a negative result represents a clockwise angle. Atan2( a, b ) equals
Atan( b/a ), except that a can equal 0 (zero) with the Atan2 function.
Helper functions
The Degrees function converts radians to degrees. π radians equals 180 degrees.
Notes
If you pass a single number to these functions, the return value is a single result. If you
pass a single-column table that contains numbers, the return value is a single-column
table of results with a Value column, one result for each record in the argument's table.
If you have a multi-column table, you can shape it into a single-column table, as
working with tables describes.
If an argument would result in an undefined value, the result is blank. This can happen,
for example, when using inverse functions with arguments that are out of range.
Syntax
Primary Functions
Cos( Radians )
Cot( Radians )
Sin( Radians )
Tan( Radians )
Cos( SingleColumnTable )
Cot( SingleColumnTable )
Sin( SingleColumnTable )
Tan( SingleColumnTable )
Inverse Functions
Acos( Number )
Acot( Number )
Asin( Number )
Atan( Number )
Acos( SingleColumnTable )
Acot( SingleColumnTable )
Asin( SingleColumnTable )
Atan( SingleColumnTable )
Atan2( X, Y )
Helper Functions
Degrees( Radians )
Pi()
Radians( Degrees )
Examples
Single number
Atan2( 5, 3 ) Returns the arctangent of the angle from the x-axis of the line 0.540419...
that contains the origin (0,0) and the coordinate (5,3), which is
approximately 31 degrees.
Atan2( 4, 4 ) Returns the arctangent of the angle from the x-axis of the line 0.785398...
that contains the origin (0,0) and the coordinate (4,4), which is
exactly π/4 radians or 45 degrees.
Single-column table
The examples in this section use a data source that's named ValueTable and that
contains the following data. The last record in the table is π/2 radians or 90 degrees.
Value
0.5
-2
1.570796...
Sin( ValueTable ) Returns the sine of each number A single-column table with a Value
in the table. column containing the following
values: 0.479425, -0.909297..., 1
Converts any value and formats a number or date/time value to a string of text.
Description
The Text function formats a number or a date/time value based on one of these types of
arguments:
The Text function can also convert any data type to a text representation using a default
format. Use this to pass non-text values to text-based functions such as Len, Right, and
IsMatch.
LongDate Four-digit year, month name, day of the month, and day "Tuesday, April 7,
of the week. The names of the month and day of the 2020"
week aren't abbreviated.
DateTimeFormat Description Examples (using
enum en-US)
LongDateTime Four-digit year, month name, day of the month, and day "Tuesday, April 7,
of the week, plus hour (12-hour clock), minutes, 2020 8:26:59 PM"
seconds, and AM/PM designation. The names of the
month and day of the week aren't abbreviated.
LongDateTime24 Four-digit year, month, day of the month, and day of "Tuesday, April 7,
the week, plus hour (24-hour clock), minutes, and 2020 20:26:59"
seconds. The names of the month and day of the week
aren't abbreviated.
LongTime Hour (12-hour clock), minutes, seconds, and AM/PM "8:26:59 PM"
designation.
ShortDate Four-digit year with numerical month and day of the "4/7/2020"
month.
ShortDateTime Four-digit year with numerical month and day of the "4/7/2020 8:26
month, plus hour (12-hour clock), minutes, and AM/PM PM"
designation.
ShortDateTime24 Four-digit year with numerical month and day of the "4/7/2020 20:26"
month, plus hour (24-hour clock) and minutes.
ShortTime Hour (12-hour clock), minutes, and AM/PM designation. "8:26 PM"
Number placeholders
Placeholder Description
0 (zero) Displays insignificant zeros if a number has fewer digits than there are zeros in the
format. For example, use the format #.00 if you want to display 8.9 as 8.90.
# Follows the same rules as the 0 (zero). However, Text doesn't return extra zeros
when the number has fewer digits on either side of the decimal than there are #
symbols in the format. For example, 8.9 is displayed if the custom format is #.##
and the number to format is 8.9.
Placeholder Description
. (period) Displays the decimal point in a number. Depends on the language of the custom
format; see global apps for more details.
, (comma) Displays the grouping separator in a number, often used for thousands. Text
separates groups by commas if the format contains a comma that's enclosed by
number signs (#) or by zeros. Depends on the language of the custom format; see
global apps for more details.
If a number has more digits to the right of the decimal point than there are placeholders
in the format, the number rounds to as many decimal places as there are placeholders. If
there are more digits to the left of the decimal point than there are placeholders, the
extra digits are displayed. If the format contains only number signs (#) to the left of the
decimal point, numbers less than 1 start with a decimal point (for example, .47).
Placeholder Description
hh Displays the hour as a number with a leading zero when appropriate. If the format
contains AM or PM, the hour is shown based on the 12-hour clock. Otherwise, the
hour is shown based on the 24-hour clock.
Placeholder Description
AM/PM, a/p Displays the hour based on a 12-hour clock. Text returns "AM" or "a" for times
from midnight until noon and "PM" or "p" for times from noon until midnight
Literal placeholders
You can include any of these characters in your format string. They will appear in the
result of Text as is. Additional characters are reserved for future placeholders, so you
shouldn't use them.
Character Description
Any currency symbol Dollar sign, cents sign, euro sign, etc.
+ Plus sign
( Left parenthesis
: Colon
' Apostrophe
= Equal sign
- Minus sign
Character Description
/ Slash mark
) Right parenthesis
& Ampersand
~ Tilde
Space character
Global apps
The Text function is globally aware. For a wide array of languages, it knows how to
properly write out dates, times, currencies, and numbers. To do its job, it needs two
pieces of information:
The language of the custom format: For makers, how should a custom format be
interpreted? The separator characters (. and ,) have different meanings in different
languages. If you specify a custom format, you can include a language placeholder
or take the default value, which reflects the language to which your device is set.
Even easier, you can use one of the predefined date/time formats, which are
language agnostic.
The language of the result: For users, in what language should the function result
appear? Names of months and weekdays must be in the appropriate language for
the user of the app, which you can specify by adding a third, optional argument to
the Text function.
For both, you specify the language by using a language tag. To see the list of supported
languages, type Text( 1234, "", ) in the formula bar or the Advanced tab of the right-
hand pane, and then scroll through the list of locales suggested for the third argument.
Language placeholder
To specify the language of the custom format, use:
Placeholder Description
Placeholder Description
[$-LanguageTag] LanguageTag is a language tag as returned from the Language function. It can
specify just the language (such as [$-en] for English), or it can also specify the
region (such as [$-en-GB] to further specify Great Britain).
The language placeholder can appear anywhere in the custom format but only once.
If you specify a custom format without a language placeholder and the format is
ambiguous from a global standpoint, the language tag for your current language is
inserted automatically.
[$-en-US] is assumed if this placeholder isn't present when your app is run.
7 Note
In a future version, the syntax of this placeholder may change to avoid confusion
with a similar, but different, placeholder that Excel supports.
By default, Text uses the language of the user running the app. The Language function
returns the language tag for the current user. You can override this default value by
supplying a language tag for the third argument to Text.
Syntax
Text( NumberOrDateTime, DateTimeFormatEnum [, ResultLanguageTag ] )
Text( AnyValue )
Text ( Untyped )
Untyped - Required. Untyped object that represents a string. Acceptable values are
dependent on the untyped provider. For JSON, the untyped object is expected to
be a JSON string. Values not inside of a string, such as false or 12.5 , are not
accepted. Consider converting such untyped objects to their respective types first,
then to text.
Examples
Unless otherwise specified, the user running these formulas is located in the United
States and has selected English as their language. The Language function is returning
"en-US".
Number
Text( 8.9, "#.000" ) Pads the decimal portion of the number with trailing "8.900"
zeros, if needed.
Text( 0.631, "0.#" ) Pads the whole portion of the number with leading "0.6"
zeros, if needed.
Text( 12, "#.0#" )
Pads the decimal portion of the number with zeros "12.0"
Text( 1234.568, "#.0#" ) for one decimal place, and includes a second decimal "1234.57"
place if supplied.
Text( 12000, "$ #,###" )
Places a thousands separator every three digits, and "$ 12,000"
Date/Time
At 2:37:47 PM on Monday, November 23, 2015
United States Pacific Time Zone (UTC-8)
Text(1448318857*1000, "mmm. Shows a Unix date-time value in human- "Nov. 23, 2015
dd, yyyy (hh:mm:ss AM/PM)") readable format if you multiply the source (02:47:37 PM)"
value by 1,000.
Global apps
Text(1234567,89; If the source data follows the French custom of using a "1 234 567,89 €"
"[$-fr-FR]# comma as the decimal separator, you must change
###,## €") your locale to French and separate the arguments with
a semi-colon instead of a comma to get the same
result as above.
Text( Returns the weekday, month, and day of the month in "Sunday January 31"
Date(2016,1,31), the language of the current user. Because none of the
"dddd mmmm placeholders are language dependent, there is no need
d" ) for a format text language tag.
Text( Returns the weekday, month, and day of the month in "domingo enero 31"
Date(2016,1,31), the "es-ES" language.
"dddd mmmm
d", "es-ES" )
Some of these operators are dependent on the language of the author. For more
information about language support in canvas apps, see Global apps.
"..." Text string "Hello, World" Text strings are enclosed in double
quotes
. Property Slider1.Value
Extracts a property from a table,
Selector Color.Red
control, signal, or enumeration. For
Acceleration.X backward compatibility, ! may also be
used.
.
Decimal 1.23 Separator between whole and fractional
[language separator parts of a number. The character
dependent] depends on the language.
* 2*3 Multiplication
& String "hello" & " " & Makes multiple strings appear
concatenation "world" continuous
operator
&& or And Logical Price < 100 && Logical conjunction, equivalent to the
operators Slider1.Value = 20
And function
or Price < 100 And
Slider1.Value = 20
! or Not !(Price < 100) or Not Logical negation, equivalent to the Not
(Price < 100) function
,
List separator If( X < 10, "Low", Separates:
[language "Good" )
arguments in function calls
dependent] { X: 12, Y: 32 }
fields in a record
[ 1, 2, 3 ] records in a table
;
Formula Collect(T, A); Separate invocations of functions in
[language chaining Navigate(S1, "") behavior properties. The chaining
dependent] operator depends on the language.
7 Note
The @ operator can also be used to validate the type of the record object against a
data source. For example, Collect(coll,Account@{'Account Number: 1111')
The gallery shows all products except Callisto because the name of that product is
the only one that doesn't contain the letter you specified.
The gallery shows only Europa because only its name contains the letter that you
specified in the case that you specified.
ThisItem Gallery control
The default name for the current record in a Gallery or form
Edit form control
control.
Display form control
ThisRecord ForAll, Filter, With, The default name for the current record in ForAll and other
Sum and other record scope functions.
record scope
functions
As name Gallery control
Defines a name for the current record, replacing default
ForAll, Filter, With, ThisItem or ThisRecord. Use As to make formulas easier to
Sum and other understand and resolve ambiguity when nesting.
record scope
functions
ThisItem operator
For example, in the following Gallery control, the Items property is set to the Employees
data source (such as the Employees table included with the Northwind Traders sample):
Power Apps
Employees
The first item in the gallery is a template that is replicated for each employee. In the
template, the formula for the picture uses ThisItem to refer to the current item:
Power Apps
ThisItem.Picture
Power Apps
ThisRecord operator
ThisRecord is used in functions that have a record scope. For example, we can use the
Filter function with our gallery's Items property to only show first names that being with
M:
Power Apps
ThisRecord is optional and implied by using the fields directly, for example, in this case,
we could have written:
Power Apps
Although optional, using ThisRecord can make formulas easier to understand and may
be required in ambiguous situations where a field name may also be a relationship
name. ThisRecord is optional while ThisItem is always required.
Use ThisRecord to reference the whole record with Patch, Collect, and other record
scope functions. For example, the following formula sets the status for all inactive
employees to active:
Power Apps
ForAll( InactiveEmployees,
As operator
Use the As operator to name a record in a gallery or record scope function, overriding
the default ThisItem or ThisRecord. Naming the record can make your formulas easier
to understand and may be required in nested situations to access records in other
scopes.
For example, you can modify the Items property of our gallery to use As to identify that
we are working with an Employee:
Power Apps
Employees As Employee
The formulas for the picture and name are adjusted to use this name for the current
record:
Power Apps
Employee.Picture
Power Apps
Employee.'First Name' & " " & Employee.'Last Name'
As can also be used with record scope functions to replace the default name
ThisRecord. We can apply this to our previous example to clarify the record we're
working with:
Power Apps
When nesting galleries and record scope functions, ThisItem and ThisRecord always
refers to the inner most scope, leaving records in outer scopes unavailable. Use As to
make all record scopes available by giving each a unique name.
For example, this formula produces a chessboard pattern as a text string by nesting two
ForAll functions:
Power Apps
Concat(
Concat(
),
Value
) & Char(10)
),
Value
A similar example is possible with nested Gallery controls instead of ForAll functions.
Let's start with the vertical gallery for the Rank. This gallery control will have an Items
formula of:
Power Apps
Sequence(8) as Rank
Within this gallery, we'll place a horizontal gallery for the File, that will be replicated for
each Rank, with an Items property of:
Power Apps
Sequence(8) as File
And finally, within this gallery, we'll add a Label control that will be replicated for each
File and each Rank. We'll size it to fill the entire space and use the Fill property to
provide the color with this formula:
Power Apps
Method Description
By Any control can be referenced by name from anywhere within the app.
control
name For example, Label1.Fill refers to the fill property of the control who's name is Label1.
Self It's often convenient to reference another property of the same control when writing a
operator formula. Instead of using an absolute reference by name, it's easier and more portable
to use a relative reference to oneself. The Self operator provides that easy access to
the current control.
For example, Self.Fill refers to the fill color of the current control.
Parent Some controls host other controls, such as the Screen and Gallery controls. The
operator hosting control of the controls within it's called the parent. Like the Self operator, the
Parent operator provides an easy relative reference to the container control.
For example, Parent.Fill refers to the fill property of the control that is the container for
the current control.
Self and Parent are operators and not properties on the controls themselves. Referring
to Parent.Parent, Self.Parent or Parent.Self is not supported.
Identifier names
The names of variables, data sources, columns, and other objects can contain any
Unicode .
Use single quotes around a name that contains a space or other special character.
Use two single quotes together to represent one single quote in the name. Names that
don't contain special characters don't require single quotes.
Here are some example column names you might encounter in a table, and how they're
represented in a formula:
SimpleName SimpleName
NameWith123Numbers NameWith123Numbers
Display name - A name that is user-friendly and intended to be seen by end users.
This name may not be unique, may change over time, may contain spaces and any
Unicode character, and may be localized into different languages. Corresponding
to the example above, the display name may be Custom Field with space in
between the words.
Since display names are easier to understand, Canvas apps will suggest them as choices
and not suggest logical names. Although logical names aren't suggested, they can still
be used if typed indirectly.
For example, imagine you've added a Custom Field to a table in Dataverse. A logical
name will be assigned for you by the system, which you can modify only when creating
the field. The result would look similar to:
When authoring a reference to a field of Accounts, the suggestion will be made to use
'Custom Field' since this is the display name. Single quotes must be used because this
name has a space in it:
After selecting the suggestion, 'Custom Field' is shown in the formula bar and the data is
retrieved:
Although it isn't suggested, we could also use the logical name for this field. This will
result in the same data being retrieved. Single quotes are not required since this name
doesn't contain spaces or special characters:
Behind the scenes, a mapping is maintained between the display names seen in
formulas and the underlying logical names. Since logical names must be used to interact
with the data source, this mapping is used to convert from the current display name to
the logical name automatically and that is what is seen in the network traffic. This
mapping is also used to convert back to logical names to switch into new display names,
for example, if a display name changes or a maker in a different language edits the app.
7 Note
Logical names are not translated when moving an app between environments. For
Dataverse system table and field names, this should not be a problem as logical
names are consistent across environments. But any custom fields, such as
cra3a_customfield in this example above, may have a different environment prefix
(cra3a in this case). Display names are preferred as they can be matched against
display names in the new environment.
Name disambiguation
Since display names aren't unique, the same display name may appear more than once
in the same table. When this happens, the logical name will be added to the end of the
display name in parenthesis for one of more of the conflicting names. Building on the
example above, if there was a second field with the same display name of Custom Field
with a logical name of cra3a_customfieldalt then the suggestions would show:
Name disambiguation strings are added in other situations where name conflicts occur,
such as the names of table, choices, and other Dataverse items.
Disambiguation operator
Some functions create record scopes for accessing the fields of table while processing
each record, such as Filter, AddColumns, and Sum. Field names added with the record
scope override the same names from elsewhere in the app. When this happens, you can
still access values from outside the record scope with the @ disambiguation operator:
To access values from nested record scopes, use the @ operator with the name of
the table being operated upon using this pattern:
Table[@FieldName]
To access global values, such as data sources, collections, and context variables,
use the pattern [@ObjectName] (without a table designation).
Some of these operators are dependent on the language of the author. For more
information about language support in canvas apps, see Global apps.
"..." Text string "Hello, World" Text strings are enclosed in double
quotes
. Property Slider1.Value
Extracts a property from a table,
Selector Color.Red
control, signal, or enumeration. For
Acceleration.X backward compatibility, ! may also be
used.
.
Decimal 1.23 Separator between whole and fractional
[language separator parts of a number. The character
dependent] depends on the language.
* 2*3 Multiplication
& String "hello" & " " & Makes multiple strings appear
concatenation "world" continuous
operator
&& or And Logical Price < 100 && Logical conjunction, equivalent to the
operators Slider1.Value = 20
And function
or Price < 100 And
Slider1.Value = 20
! or Not !(Price < 100) or Not Logical negation, equivalent to the Not
(Price < 100) function
,
List separator If( X < 10, "Low", Separates:
[language "Good" )
arguments in function calls
dependent] { X: 12, Y: 32 }
fields in a record
[ 1, 2, 3 ] records in a table
;
Formula Collect(T, A); Separate invocations of functions in
[language chaining Navigate(S1, "") behavior properties. The chaining
dependent] operator depends on the language.
7 Note
The @ operator can also be used to validate the type of the record object against a
data source. For example, Collect(coll,Account@{'Account Number: 1111')
The gallery shows all products except Callisto because the name of that product is
the only one that doesn't contain the letter you specified.
The gallery shows only Europa because only its name contains the letter that you
specified in the case that you specified.
ThisItem Gallery control
The default name for the current record in a Gallery or form
Edit form control
control.
Display form control
ThisRecord ForAll, Filter, With, The default name for the current record in ForAll and other
Sum and other record scope functions.
record scope
functions
As name Gallery control
Defines a name for the current record, replacing default
ForAll, Filter, With, ThisItem or ThisRecord. Use As to make formulas easier to
Sum and other understand and resolve ambiguity when nesting.
record scope
functions
ThisItem operator
For example, in the following Gallery control, the Items property is set to the Employees
data source (such as the Employees table included with the Northwind Traders sample):
Power Apps
Employees
The first item in the gallery is a template that is replicated for each employee. In the
template, the formula for the picture uses ThisItem to refer to the current item:
Power Apps
ThisItem.Picture
Power Apps
ThisRecord operator
ThisRecord is used in functions that have a record scope. For example, we can use the
Filter function with our gallery's Items property to only show first names that being with
M:
Power Apps
ThisRecord is optional and implied by using the fields directly, for example, in this case,
we could have written:
Power Apps
Although optional, using ThisRecord can make formulas easier to understand and may
be required in ambiguous situations where a field name may also be a relationship
name. ThisRecord is optional while ThisItem is always required.
Use ThisRecord to reference the whole record with Patch, Collect, and other record
scope functions. For example, the following formula sets the status for all inactive
employees to active:
Power Apps
ForAll( InactiveEmployees,
As operator
Use the As operator to name a record in a gallery or record scope function, overriding
the default ThisItem or ThisRecord. Naming the record can make your formulas easier
to understand and may be required in nested situations to access records in other
scopes.
For example, you can modify the Items property of our gallery to use As to identify that
we are working with an Employee:
Power Apps
Employees As Employee
The formulas for the picture and name are adjusted to use this name for the current
record:
Power Apps
Employee.Picture
Power Apps
Employee.'First Name' & " " & Employee.'Last Name'
As can also be used with record scope functions to replace the default name
ThisRecord. We can apply this to our previous example to clarify the record we're
working with:
Power Apps
When nesting galleries and record scope functions, ThisItem and ThisRecord always
refers to the inner most scope, leaving records in outer scopes unavailable. Use As to
make all record scopes available by giving each a unique name.
For example, this formula produces a chessboard pattern as a text string by nesting two
ForAll functions:
Power Apps
Concat(
Concat(
),
Value
) & Char(10)
),
Value
A similar example is possible with nested Gallery controls instead of ForAll functions.
Let's start with the vertical gallery for the Rank. This gallery control will have an Items
formula of:
Power Apps
Sequence(8) as Rank
Within this gallery, we'll place a horizontal gallery for the File, that will be replicated for
each Rank, with an Items property of:
Power Apps
Sequence(8) as File
And finally, within this gallery, we'll add a Label control that will be replicated for each
File and each Rank. We'll size it to fill the entire space and use the Fill property to
provide the color with this formula:
Power Apps
Method Description
By Any control can be referenced by name from anywhere within the app.
control
name For example, Label1.Fill refers to the fill property of the control who's name is Label1.
Self It's often convenient to reference another property of the same control when writing a
operator formula. Instead of using an absolute reference by name, it's easier and more portable
to use a relative reference to oneself. The Self operator provides that easy access to
the current control.
For example, Self.Fill refers to the fill color of the current control.
Parent Some controls host other controls, such as the Screen and Gallery controls. The
operator hosting control of the controls within it's called the parent. Like the Self operator, the
Parent operator provides an easy relative reference to the container control.
For example, Parent.Fill refers to the fill property of the control that is the container for
the current control.
Self and Parent are operators and not properties on the controls themselves. Referring
to Parent.Parent, Self.Parent or Parent.Self is not supported.
Identifier names
The names of variables, data sources, columns, and other objects can contain any
Unicode .
Use single quotes around a name that contains a space or other special character.
Use two single quotes together to represent one single quote in the name. Names that
don't contain special characters don't require single quotes.
Here are some example column names you might encounter in a table, and how they're
represented in a formula:
SimpleName SimpleName
NameWith123Numbers NameWith123Numbers
Display name - A name that is user-friendly and intended to be seen by end users.
This name may not be unique, may change over time, may contain spaces and any
Unicode character, and may be localized into different languages. Corresponding
to the example above, the display name may be Custom Field with space in
between the words.
Since display names are easier to understand, Canvas apps will suggest them as choices
and not suggest logical names. Although logical names aren't suggested, they can still
be used if typed indirectly.
For example, imagine you've added a Custom Field to a table in Dataverse. A logical
name will be assigned for you by the system, which you can modify only when creating
the field. The result would look similar to:
When authoring a reference to a field of Accounts, the suggestion will be made to use
'Custom Field' since this is the display name. Single quotes must be used because this
name has a space in it:
After selecting the suggestion, 'Custom Field' is shown in the formula bar and the data is
retrieved:
Although it isn't suggested, we could also use the logical name for this field. This will
result in the same data being retrieved. Single quotes are not required since this name
doesn't contain spaces or special characters:
Behind the scenes, a mapping is maintained between the display names seen in
formulas and the underlying logical names. Since logical names must be used to interact
with the data source, this mapping is used to convert from the current display name to
the logical name automatically and that is what is seen in the network traffic. This
mapping is also used to convert back to logical names to switch into new display names,
for example, if a display name changes or a maker in a different language edits the app.
7 Note
Logical names are not translated when moving an app between environments. For
Dataverse system table and field names, this should not be a problem as logical
names are consistent across environments. But any custom fields, such as
cra3a_customfield in this example above, may have a different environment prefix
(cra3a in this case). Display names are preferred as they can be matched against
display names in the new environment.
Name disambiguation
Since display names aren't unique, the same display name may appear more than once
in the same table. When this happens, the logical name will be added to the end of the
display name in parenthesis for one of more of the conflicting names. Building on the
example above, if there was a second field with the same display name of Custom Field
with a logical name of cra3a_customfieldalt then the suggestions would show:
Name disambiguation strings are added in other situations where name conflicts occur,
such as the names of table, choices, and other Dataverse items.
Disambiguation operator
Some functions create record scopes for accessing the fields of table while processing
each record, such as Filter, AddColumns, and Sum. Field names added with the record
scope override the same names from elsewhere in the app. When this happens, you can
still access values from outside the record scope with the @ disambiguation operator:
To access values from nested record scopes, use the @ operator with the name of
the table being operated upon using this pattern:
Table[@FieldName]
To access global values, such as data sources, collections, and context variables,
use the pattern [@ObjectName] (without a table designation).
Description
The Date function converts individual Year, Month, and Day values to a Date/Time value.
The time portion is midnight.
If Year is between 0 and 1899 (inclusive), the function adds that value to 1900 to
calculate the year. 70 becomes 1970.
If Month is less than 1 or more than 12, the result subtracts or adds that many
months from the beginning of the specified year.
If Day is greater than the number of days in the specified month, the function adds
that many days to the first day of the month and returns the corresponding date
from a subsequent month. If Day is less than 1, the function subtracts that many
days, plus 1, from the first day of the specified month.
The Time function converts individual Hour, Minute, and Second values to a Date/Time
value. The result has no date associated with it.
See the DateValue, TimeValue, and DateTimeValue functions for information about how
to convert a string to a value.
Also see working with dates and times for more information.
Syntax
Date( Year, Month, Day )
Year - Required. Numbers greater than 1899 are interpreted as absolute (1980 is
interpreted as 1980); numbers that range from 0 to 1899 are interpreted as relative
to 1900. (For example, 80 is interpreted as 1980.)
Month - Required. A number that ranges from 1 to 12.
Day - Required. A number that ranges from 1 to 31.
Hour - Required. A number that ranges from 0 (12:00 AM) to 23 (11:00 PM).
Minute - Required. A number that ranges from 0 to 59.
Second - Required. A number that ranges from 0 to 59.
Examples
Date
If a user typed 1979 in a text-input control named HireYear, 3 in a text-input control
named HireMonth, and 17 in a text-input control named HireDay, this function would
return 3/17/1979:
Time
If a user typed 14 in a text-input control named BirthHour, 50 in a text-input control
named BirthMinute, and 24 in a text-input control named BirthSecond, this function
would return 02:50:24 p.
Description
DateValue function converts a date string (for example, "10/01/2014") to a
date/time value.
TimeValue function converts a time string (for example, "12:15 PM") to a date/time
value.
DateTimeValue function converts a date and time string (for example, "January 10,
2013 12:13 AM") to a date/time value.
DateValue function ignores any time information in the date string, and the TimeValue
function ignores any date information in the time string.
7 Note
MM/DD/YYYY or MM-DD-YYYY
DD/MM/YYYY or DD-MM-YYYY
YYYY/MM/DD or YYYY-MM-DD
MM/DD/YY or MM-DD-YY
DD/MM/YY or DD-MM-YY
DD Mon YYYY
Month DD, YYYY
To convert from numeric date, month and year components, read Date.
To convert from numeric hour, minute and second components, read Time.
For more information, read:
Syntax
DateValue( String [, Language ])
String - Required. A text string that contains a date, time, or combination date and
time value.
Language - Optional. A language string, such as would be returned by the first two
characters from the Language function. If not provided, the language of the
current user's settings is used.
DateValue( Untyped )
DateTimeValue( Untyped )
TimeValue( Untyped )
Examples
DateValue
If you type 10/11/2014 into a text-input control named Startdate, and then set the Text
property of a label to these formulas:
Convert a date from a string in the user's locale and show the result as a long date.
Power Apps
Device set to en locale shows the label as Saturday, October 11, 2014.
7 Note
You can use several options with the DateTimeFormat enum. To display a list
of options, type the parameter followed by a dot or period (.) in the formula
bar or check Text function reference.
Convert date from a string in the French locale and show the result as a long date.
In this example, the months and day of the month are interpreted differently from
English.
Power Apps
Device set to en locale shows the label as Monday, November 10, 2014.
Convert a date from a string in the user's locale and calculate the difference
between two days, in days
Power Apps
Device set to en locale shows the label as 9, indicating the number of days
between October 11 and October 20. The DateDiff function can also show the
difference in months, quarters, or years.
DateTimeValue
If you typed 10/11/2014 1:50:24.765 PM into a text-input control named Start, and then
set the Text property of a label to the following formula:
Power Apps
Device set to en locale shows the label as Saturday, October 11, 2014 1:50:24 PM.
7 Note
You can use several options with the DateTimeFormat enum. To display a list
of options, type the parameter followed by a dot or period (.) in the formula
bar or check Text function reference.
Convert both a date and time string in the French locale. Month and day of the
month are interpreted differently.
Power Apps
Device set to en locale shows the label as Monday, November 10, 2014 1:50:24
PM.
Convert both a date and time string in the user's locale, and display the result with
a fractional second.
Power Apps
Device set to en locale shows the label as Saturday, October 11, 2014 01:50:24.765
PM.
TimeValue
Name a text-input control FinishedAt, and set the Text property of a label to this
formula:
Power Apps
"Too late!"
If you type 4:59:59.999 PM in the FinishedAt control, the label shows "You made
it!"
If you type 5:00:00.000 PM in the FinishedAt control, the label shows "Too late!"
DateAdd, DateDiff, and TimeZoneOffset
functions in Power Apps
Article • 03/08/2023 • 3 minutes to read
Adds to or finds the difference in date/time values and converts between local time and
UTC.
Description
The DateAdd function adds a number of units to a date/time value. The result is a new
date/time value. You can also subtract a number of units from a date/time value by
specifying a negative value.
The DateDiff function returns the difference between two date/time values. The result is
a whole number of units.
The TimeZoneOffset function returns the number of minutes between the user's local
time and UTC (Coordinated Universal Time).
You can use DateAdd with the TimeZoneOffset to convert between the user's local time
and UTC (Coordinated Universal Time). Adding TimeZoneOffset will convert a local time
to UTC, and subtracting it (adding the negative) will convert from UTC to local time.
Also see Date, Time, and DateTime data types and working with dates and times for
more information.
Syntax
DateAdd( DateTime, Addition [, Units ] )
TimeZoneOffset( [ DateTime ] )
DateTime - Optional. Date/time value for which to return the offset. By default, the
current date/time is used.
Examples
In all of these examples, assume that the current date and time is July 15, 2013, 1:02 PM.
Simple DateAdd
Text( DateAdd( Now(), 4, Add four hours to the current date and time. "15-07-
TimeUnit.Hours ),
2013
"dd-mm-yyyy hh:mm" ) 17:02"
Text( DateAdd( Today(), 1, Adds one month to the current date, without time as "15-08-
TimeUnit.Months ),
Today doesn't return a time component. 2013
"dd-mm-yyyy hh:mm" ) 00:00"
Text( DateAdd( Now(), ‑30, Subtracts 30 minutes from the current date and time. "15-07-
TimeUnit.Minutes ),
2013
"dd-mm-yyyy hh:mm" ) 12:32"
Simple DateDiff
DateDiff( Now(), Returns the difference between the two units in the default 170
DateValue("1/1/2014") ) units of TimeUnit.Days
DateDiff( Now(), Returns the difference between the current date/time and the -782
Today(), current date only (no time) in minutes. Since the Now is later
TimeUnit.Minutes ) than Today the result will be negative.
DateDiff( TimeValue("09:45:00"), The minutes are used in the difference, and the 0.5
TimeValue("10:15:36"), result is divided by 60 to have the difference in
TimeUnit.Minutes )/60 hours.
DateDiff( TimeValue("09:45:00"), The minutes and seconds are used in the 0.51
TimeValue("10:15:36"), difference; the result is divided by 3600 to have
TimeUnit.Seconds )/3600 the difference in hours.
Converting to UTC
To convert to UTC (Coordinated Universal Time), add the TimeZoneOffset for the given
time.
For example, imagine the current date and time is July 15, 2013, 1:02 PM in Pacific
Daylight Time (PDT, UTC-7). To determine the current time in UTC, use:
TimeZoneOffset defaults to the current time, so you don't need to pass it an argument.
To see the result, use the Text function with the format dd-mm-yyyy hh:mm, which will
return 15-07-2013 20:02.
For example, imagine the UTC date and time July 15, 2013, 8:02 PM is stored in a
variable named StartTime. To adjust the time for the user's time zone, use:
Note the negative sign before TimeZoneOffset to subtract the offset rather than add it.
To see the result, use the Text function with the format dd-mm-yyyy hh:mm, which will
result in 15-07-2013 13:02 if you're in Pacific Daylight Time.
Now, Today, IsToday, UTCNow,
UTCToday, IsUTCToday functions in
Power Apps
Article • 02/23/2023 • 4 minutes to read
Returns the current date and time, and tests whether a date/time value is today.
Description
The Now function returns the current date and time as a date/time value.
The Today function returns the current date as a date/time value. The time portion is
midnight. Today has the same value throughout a day, from midnight today to midnight
tomorrow.
The IsToday function tests whether a date/time value is between midnight today and
midnight tomorrow. This function returns a Boolean (true or false) value.
Now, Today, and IsToday functions work with the local time of the current user.
UTCNow, UTCToday, and IsUTCToday functions are the same as their non-UTC
countrparts but work with time zone independent values and use Coordinated Universal
Time (UTC).
7 Note
More information: Work with formula table columns in Dataverse for Teams
See Date, Time, and DateTime in the data types documentation and working with dates
and times for more information.
Volatile Functions
Now, Today, UTCNow, and UTCToday are volatile functions. These functions return a
different value for each evaluation.
When used in a data flow formula, a volatile function will only return a different value if
the formula in which it appears is reevaluated. If nothing else changes in the formula
then it will have the same value throughout the execution of your app.
For example, a label control with Label1.Text = Now() will not change while your app is
active. Only closing and reopening the app will result in a new value.
The function will be reevaluated if it is part of a formula in which something else has
changed. For example, if we change our example to involve a slider control with
Label1.Text = DateAdd( Now(), Slider1.Value, Minutes ) then the current time is
retrieved each time the Slider control's value changes and the label's text property is
reevaluated.
When used in a behavior formula, volatile functions will be evaluated each time the
behavior formula is evaluated. See below for an example.
Syntax
Now()
Today()
IsToday( DateTime )
UTCNow()
UTCToday()
IsUTCToday( TimeZoneIndependentTime )
Text( Now(), Retrieves the current date and time in the user's time "07/11/2021
"mm/dd/yyyy hh:mm:ss" ) zone, and displays it as a string. 20:58:00"
Text( Today(), Retrieves the current date only, leaving the time "07/12/2021
"mm/dd/yyyy hh:mm:ss" ) portion as midnight, and displays it as a string. 00:00:00"
IsToday( Now() ) Tests whether the current date and time is between true
midnight today and midnight tomorrow.
IsToday( Today() ) Tests whether the current date is between midnight true
today and midnight tomorrow.
Text( DateAdd( Now(), 12 Retrieves the current date and time, adds 12 days to "07/23/2021
), "mm/dd/yyyy the result, and displays it as a string. 20:58:00"
hh:mm:ss" )
Text( DateAdd( Today(), 12 Retrieves the current date, adds 12 days to the result, "07/23/2021
), "mm/dd/yyyy and displays it as a string. 00:00:00"
hh:mm:ss" )
IsToday( DateAdd( Now(), Tests whether the current date and time, plus 12 false
12 ) ) days, is between midnight today and midnight
tomorrow.
IsToday( DateAdd( Tests whether the current date, plus 12 days, is false
Today(), 12 ) ) between midnight today and midnight tomorrow.
Hour( UTCNow() ) Retrieves the current date and time in UTC and 4
extracts the hour only, which is 8 hours ahead of
local time.
Day( UTCToday() ) Retrives the current date only in UTC and extracts the 12
day, which is 1 day ahead of local time.
IsUTCToday( UTCNow() ) Tests whether the current date and time is between true
midnight today and midnight tomorrow, all in UTC
time.
IsUTCToday( UTCToday() ) Tests whether the current date is between midnight true
today and midnight tomorrow, all in UTC time.
The timer will run for one second, automatically start over, and continue that
pattern.
Whenever the timer starts over (after each second), this formula sets the
CurrentTime global variable to the current value of the Now function.
3. Add a Label control, and set its Text property to this formula:
Use the Text function to format the date and time however you want, or set this
property to just CurrentTime to show hours and minutes but not seconds.
4. Preview the app by pressing F5, and then start the timer by clicking or tapping it.
The label continually shows the current time, down to the second.
5. Set the timer's AutoStart property to true and its Visible property to false.
6. Set the screen's OnStart property so that the CurrentTime variable has a valid
value, as in this example:
Set(CurrentTime, Now())
The label appears as soon as the app starts (before the timer runs for a full
second).
Trace function in Power Apps
Article • 02/23/2023 • 2 minutes to read
Often there is a lot of logic working behind the scenes in an app. Sometimes the impact
is obvious, for example a control's value or color changes, confirming the logic operated
correctly. However, sometimes it isn't obvious and it can be difficult to visualize and
understand what is happening inside the app. Use the Trace function to record
diagnostic information from behind the scenes, creating a timeline of what actually
happened, to better understand how your app is operating and to help debug issues.
When used in Power Apps, the output from Trace appears in the Power Apps Monitor
tool along with other app activities. If you've allowed your app to send telemetry data to
Azure Application Insights, the Trace function can also be used to send information to
your Application Insights resource. Trace can only be used in behavior formulas.
When used with Test Studio, Trace is an optional expression that can be used to provide
additional information in your test results from the OnTestCaseComplete event. Trace
event messages are combined with passed and failed assertion messages in the Traces
table of the TestCaseResult record. The Traces table has two properties, Message and
Timestamp. Trace information used in tests will also be recorded in Application Insights.
Test trace information won't be available in the Monitor tool as the Monitor is
connected to the app when it's played from the Power Apps Studio.
Syntax
Trace( Message [, TraceSeverity [, CustomRecord [, TraceOptions ] ] ] )
Example
1. Create a button control in Power Apps Studio.
2. Set the OnSelect formula to the formula:
Power Apps
Set( x, x+1 );
Trace( x );
3. Open the Power Apps Monitor in another browser window by selecting the
"Advanced tools" icon in the left hand pane and select "Open monitor":
4. Return to the original Studio browser window and select your button four times.
Use Alt-click on your mouse if in design mode.
5. View the Power Apps Monitor.
6. The Monitor's grid will contain an event for each button click and for each Trace
call, which will show the value of the variable after each increment. Drill into a
Trace event to see where the Trace was initiated, and the expression used for the
message, in the right hand panel:
See Also
Power Apps Monitor Overview
Description
The Trim function removes all spaces from a string of text except for single spaces
between words.
The TrimEnds function removes all spaces from the start and end of a string of text but
leaves spaces between words intact.
If you specify a single string of text, the return value for either function is the string with
any extra spaces removed. If you specify a single-column table that contains strings, the
return value is a single-column table of trimmed strings. If you have a multi-column
table, you can shape it into a single-column table, as working with tables describes.
By trimming spaces between words, Trim is consistent with the function of the same
name in Microsoft Excel. However, TrimEnds is consistent with programming tools that
trim spaces only from the start and end of each string.
Syntax
Trim( String )
TrimEnds( String )
Trim( SingleColumnTable )
TrimEnds( SingleColumnTable )
Example
Formula Description Result
Formula Description Result
Trim( " Hello World " ) Removes all spaces from the start and end "Hello World"
of a string and extra spaces from within the
string.
TrimEnds( " Hello World " ) Removes all spaces from the start and end "Hello World"
of a string.
The following examples use a single-column collection, named Spaces, that contains
these strings:
Value
" Jane Doe "
" Jack and Jill"
"Already trimmed"
" Venus, Earth, Mars "
"Oil and Water "
To create this collection, set the OnSelect property of a Button control to this formula,
open Preview mode, and then click or tap the button:
Trim( Spaces ) Trims all spaces from the start A single-column table with a Value column
and end of each string and containing the following values:
extra spaces from within each "Jane Doe", "Jack and Jill",
string in the Spaces collection. "Already trimmed", "Venus, Earth, Mars",
"Oil and Water"
TrimEnds( Spaces ) Trims all spaces from the start A single-column table with a Value column
and end of each string in the containing the following values:
Spaces collection. "Jane Doe", "Jack and Jill",
"Already trimmed", "Venus, Earth, Mars",
"Oil and Water"
7 Note
Description
The Trim function removes all spaces from a string of text except for single spaces
between words.
The TrimEnds function removes all spaces from the start and end of a string of text but
leaves spaces between words intact.
If you specify a single string of text, the return value for either function is the string with
any extra spaces removed. If you specify a single-column table that contains strings, the
return value is a single-column table of trimmed strings. If you have a multi-column
table, you can shape it into a single-column table, as working with tables describes.
By trimming spaces between words, Trim is consistent with the function of the same
name in Microsoft Excel. However, TrimEnds is consistent with programming tools that
trim spaces only from the start and end of each string.
Syntax
Trim( String )
TrimEnds( String )
Trim( SingleColumnTable )
TrimEnds( SingleColumnTable )
Example
Formula Description Result
Formula Description Result
Trim( " Hello World " ) Removes all spaces from the start and end "Hello World"
of a string and extra spaces from within the
string.
TrimEnds( " Hello World " ) Removes all spaces from the start and end "Hello World"
of a string.
The following examples use a single-column collection, named Spaces, that contains
these strings:
Value
" Jane Doe "
" Jack and Jill"
"Already trimmed"
" Venus, Earth, Mars "
"Oil and Water "
To create this collection, set the OnSelect property of a Button control to this formula,
open Preview mode, and then click or tap the button:
Trim( Spaces ) Trims all spaces from the start A single-column table with a Value column
and end of each string and containing the following values:
extra spaces from within each "Jane Doe", "Jack and Jill",
string in the Spaces collection. "Already trimmed", "Venus, Earth, Mars",
"Oil and Water"
TrimEnds( Spaces ) Trims all spaces from the start A single-column table with a Value column
and end of each string in the containing the following values:
Spaces collection. "Jane Doe", "Jack and Jill",
"Already trimmed", "Venus, Earth, Mars",
"Oil and Water"
7 Note
Rounds a number.
Round rounds up if the next digit is 5 or higher. Otherwise, this function rounds
down.
RoundDown always rounds down to the previous lower number, towards zero.
RoundUp always rounds up to the next higher number, away from zero.
Greater than The number is rounded to the right of the decimal Round( 12.37, 1 ) returns
0 separator. 12.4.
Less than 0 The number is rounded to the left of the decimal Round( 12.37, -1 )
separator. returns 10.
The difference between Int and Trunc is in the handling of negative numbers. For
example, for an argument of -4.3 , Int will return the integer further away from zero, -5 ,
while Trunc will return the integer closer to zero, -4 . Int returns values that are unique
amongst the five rounding functions, while Trunc returns the same values as
RoundDown.
Use Trunc to extract the decimal portion of a number by subtracting it from the original,
for example X - Trunc(X) .
Decimal places cannot be specified with Trunc as it can with Microsoft Excel. Use
RoundDown instead when this is needed.
Single-column tables
These functions support single-column tables. If you pass a single number, the return
value is the rounded version of that number. If you pass a single-column table that
contains numbers, the return value is a single-column table of rounded numbers. The
DecimalPlaces parameter can be a single value or a single-column table. If the single-
column table has less values that the Number, zero is used for the remaining values. Use
ShowColumns and other table shaping functions to extract a single-column table from
a larger table.
Syntax
Round(Number, DecimalPlaces)
RoundDown(Number, DecimalPlaces)
RoundUp(Number, DecimalPlaces)
Int(Number)
Trunc(Number)
Examples
Rounding to a whole number.
7.9 8 8 7 7 7
-7.9 -8 -8 -7 -8 -7
7.5 8 8 7 7 7
-7.5 -8 -8 -7 -8 -7
7.1 7 8 7 7 7
-7.1 -7 -8 -7 -8 -7
Rounding to two decimal places to the right of the decimal separator (0.01).
Rounding to two decimal places to the left of the decimal separator (100).
[ 123.456,
[ 123,
[ 123.46,
[ 123,
[ 123.46,
987.593,
987,
987.59,
987.5,
988,
Description
The GroupBy function returns a table with records grouped together based on the
values in one or more columns. Records in the same group are placed into a single
record, with a column added that holds a nested table of the remaining columns.
The Ungroup function reverses the GroupBy process. This function returns a table,
breaking into separate records any records that were grouped together.
You can group records by using GroupBy, modify the table that it returns, and then
ungroup records in the modified table by using Ungroup. For example, you can remove
a group of records by following this approach:
Ungroup tries to preserve the original order of the records that were fed to GroupBy.
This isn't always possible (for example, if the original table contains blank records).
A table is a value in Power Apps, just like a string or a number. You can specify a table as
an argument for a function, and a function can return a table. GroupBy and Ungroup
don't modify a table; instead they take a table as an argument and return a different
table. See working with tables for more details.
Syntax
GroupBy( Table, ColumnName1 [, ColumnName2, ... ], GroupColumnName )
Table - Required. Table to be grouped.
GroupColumnName - Required. The column name for the storage of record data
not in the ColumnName(s).
7 Note
For SharePoint and Excel data sources that contain column names with
spaces, specify each space as "_x0020_". For example, specify "Column
Name" as "Column_x0020_Name".
GroupColumnName - Required. The column that contains the record data setup
with the GroupBy function.
7 Note
For SharePoint and Excel data sources that contain column names with
spaces, specify each space as "_x0020_". For example, specify "Column
Name" as "Column_x0020_Name".
Examples
Create a collection
1. Add a button, and set its Text property so that the button shows Original.
2. Set the OnSelect property of the Original button to this formula:
Power Apps
ClearCollect( CityPopulations,
3. While holding down the Alt key, select the Original button.
You just created a collection, named CityPopulations, that contains this data:
You just created a collection, named CityPopulations, that contains this data:
4. To display this collection, select Collections on the File menu and then select the
CityPopulations collection. The first five records in the collection appear:
Group records
1. Add another button, and set its Text property to "Group".
2. Set the OnSelect property of this button to this formula:
3. While holding down the Alt key, select the Group button.
You just created a collection, named CitiesByCountry, in which the records of the
previous collection are grouped by the Country column.
4. To display the first five records in this collection, select Collections on the File
menu.
5. To display the populations of cities in a country, select the table icon in the Cities
column for that country (for example, Germany):
3. While holding down the Alt key, select the button that you added.
Aggregate results
Something else we can do with a grouped table is to aggregate the results. In this
example, we will sum the population of the major cities in each country.
1. Add another button, and set its Text property so that the button shows "Sum".
Now that we have the sum that we want, we can use DropColumns to remove the
sub tables.
3. Add another button, and set its Text property so that the button shows
"SumOnly".
Description
The Relate function links two records through a one-to-many or many-to-many
relationship in Microsoft Dataverse. The Unrelate function reverses the process and
removes the link.
For one-to-many relationships, the Many table has a foreign-key field that points to a
record of the One table. Relate sets this field to point to a specific record of the One
table, while Unrelate sets this field to blank. If the field is already set when Relate is
called, the existing link is lost in favor of the new link. You can also set this field by using
the Patch function or an Edit form control; you need not use the Relate function.
For many-to-many relationships, the system that links the records maintains a hidden
join table. You can't access this join table directly; it can be read only through a one-to-
many projection and set through the Relate and Unrelate functions. Neither related
table has a foreign key.
The data for the table that you specify in the first argument will be refreshed to reflect
the change, but the data for the table that you specify in the second argument won't.
That data must be manually refreshed with the Refresh function to show the result of
the operation.
These functions never create or delete a record. They only relate or unrelate two records
that already exist.
7 Note
These functions are part of a preview feature, and their behavior is available only
when the Relational data, option sets, and other new features for CDS feature is
enabled. This is an app-level setting that's enabled by default for new apps. To find
this feature switch, select Settings, and then select Upcoming features. Your
feedback is very valuable to us - please let us know what you think in the Power
Apps community forums .
Syntax
Relate( Table1RelatedTable, Table2Record )
Examples
Consider a Products table with the following relationships as seen in the Power Apps
portal's table viewer:
At no time did we create or remove or a record, only the relationship between records
was modified.
Products and Contacts are related through a Many-to-Many relationship. To relate the
first record of the Contacts table with the first record of the Products table:
or:
The walk through that follows does exactly these operations on these tables using an
app with Gallery and Combo box controls for selecting the records involved.
These examples depend on the sample data being installed in your environment. Either
create a trial environment including sample data or add sample data to an existing
environment.
One-to-many
Relate function
You'll first create a simple app to view and reassign the reservations that are associated
with a product.
5. Ensure that the control that you just added is named Gallery1, and then move and
resize it to fill the left-hand side of the screen.
6. On the Properties tab, set Gallery1's Items property to Products and its Layout to
Image and title.
7. In Gallery1, ensure that the Label control is named Title1, and then set its Text
property to ThisItem.Name.
8. Select the screen to avoid inserting the next item into Gallery1. Add a second blank
vertical Gallery control, and ensure that it's named Gallery2.
Gallery2 will show the reservations for whatever product the user selects in
Gallery1.
9. Move and resize Gallery2 to fill the upper-right quadrant of the screen.
10. (optional) Add the blue Label control above Gallery2, as the next graphic shows.
13. In Gallery2, add a Combo box control, ensure that it's named ComboBox1, and
then move and resize it to avoid blocking the other controls in Gallery2.
15. Scroll down in the Properties tab and set ComboBox1's Allow multiple selection
property to Off.
16. In the formula bar, set ComboBox1's DefaultSelectedItems property to
ThisItem.'Product Reservation'.
Power Apps
When the user selects this icon, the current reservation changes to the product
that the user selected in ComboBox1.
18. Press F5 to test the app in Preview mode.
With this app, the user can move a reservation from one product to another. For a
reservation on one product, the user can select a different product in ComboBox1 and
then select NextArrow2 to change that reservation.
Unrelate function
At this point, you can move the relationship from one record to another, but you can't
remove the relationship altogether. You can use the Unrelate function to disconnect a
reservation record from any product.
2. In the Data pane, select Add data source > Microsoft Dataverse > Reservations >
Connect.
3. In Gallery2, set the OnSelect formula for NextArrow2 to this formula:
Power Apps
);
Refresh( Reservations )
5. Paste a duplicate of Gallery2 to the same screen by pressing Ctrl-V, and then move
it to the lower-right quadrant of the screen.
6. (optional) If you added a label above Gallery2, repeat the previous two steps for
that label.
7. Ensure that the duplicate of Gallery2 is named Gallery2_1, and then set its Items
property to this formula:
Power Apps
A delegation warning appears, but it won't matter with the small amount of data in
this example.
With these changes, users can clear the selection in ComboBox1 for a contact if that
person hasn't reserved a product. Contacts who haven't reserved a product appear in
Gallery2_1 where users can assign each contact to a product.
Many-to-many
1. From this page , select Data in the left navigation bar, and then select Tables.
2. Change the table filter to include all tables.
1. In a blank app for tablets, create Gallery1 as the first procedure in this topic
describes.
2. Add another blank vertical Gallery control, ensure that it's named Gallery2, and
then move it into the upper-right corner of the screen.
Later in this topic, you'll add a Combo box control under Gallery2.
5. In Gallery2, ensure that the Label control is named Title2, and then set its Text
property to ThisItem.'Full Name'.
No text will appear in that control until you finish this procedure and assign a
contact to a product.
6. Delete NextArrow2, insert a Cancel icon, and ensure that it's named icon1.
Power Apps
9. In the Data pane, select Add data source > Microsoft Dataverse > Contacts >
Connect.
10. Under Gallery2, add a Combo box control, ensure that it's named ComboBox1,
and then set its Items property to Contacts.
11. On the Properties tab, set Allow multiple selection to Off.
12. Insert an Add icon, and set its OnSelect property to this formula:
Power Apps
With this app, users can now freely relate and unrelate a set of contacts to each product.
To add a contact to a product, select the contact in the combo box at the bottom
of the screen, and then select the Add icon.
To remove a contact from a product, select the Cancel icon for that contact.
The duplicate will be named Screen1_1 and form the basis for looking at the
relationships from the contacts side.
3. To create the reverse view, change these formulas on the controls of Screen1_1:
4. Insert an Arrows up down icon and set its OnSelect property to Navigate(
Screen1, None ). Do the same thing on Screen1 with the formula Navigate(
Screen1_1, None ).
With this new screen, users can add a contact to a product and then flip to a view of
contacts and see the associated product. The relationships are symmetric and shared
between the two screens.
Update and UpdateIf functions in Power
Apps
Article • 03/08/2023 • 3 minutes to read
Description
Update function
Use the Update function to replace an entire record in a data source. In contrast, the
UpdateIf and the Patch functions modify one or more values in a record, leaving the
other values alone.
For a collection, the entire record must match. Collections allow duplicate records, so
multiple records might match. You can use the RemoveFlags.All argument to update all
copies of a record; otherwise, only one copy of the record is updated.
If the data source generates a column's value automatically, the value of that column
must be reaffirmed.
UpdateIf function
Use the UpdateIf function to modify one or more values in one or more records that
match one or more conditions. The condition can be any formula that results in a true
or false and can reference columns of the data source by name. The function evaluates
the condition for each record and modifies any record for which the result is true.
To specify a modification, use a change record that contains new property values. If you
provide this change record inline with curly braces, property formulas can reference
properties of the record that's being modified. You can use this behavior to modify
records based on a formula.
Similar to UpdateIf, you can also use the Patch function to change specific columns of a
record without affecting other columns.
Both Update and UpdateIf return the modified data source as a table. You must use
either function in a behavior formula.
Delegation
When used with a data source, these functions can't be delegated. Only the first portion
of the data source will be retrieved and then the function applied. The result may not
represent the complete story. A warning may appear at authoring time to remind you of
this limitation and to suggest switching to delegable alternatives where possible. For
more information, see the delegation overview.
Syntax
Update( DataSource, OldRecord, NewRecord [, RemoveFlags.All ] )
DataSource – Required. The data source that contains the record that you want to
replace.
OldRecord – Required. The record to replace.
NewRecord – Required. The replacement record. This isn't a change record. The
entire record is replaced, and missing properties will contain blank.
RemoveFlags.All – Optional. In a collection, the same record may appear more than
once. Specify the RemoveFlags.All argument to update all copies of the record.
DataSource – Required. The data source that contains the record or records that
you want to modify.
Condition(s) – Required. A formula that evaluates to true for the record or records
that you want to modify. You can use column names of DataSource in the formula.
ChangeRecord(s) - Required. For each corresponding condition, a change record of
new property values to apply to records of DataSource that satisfy the condition. If
you provide the record inline using curly braces, property values of the existing
record can be used in the property formulas.
Examples
In these examples, you'll replace or modify records in a data source that's named
IceCream and that starts with the data in this table:
Formula Description Result
Update( IceCream,
Replaces a record from the data
First( Filter( IceCream, Flavor="Chocolate" ) ), source.
{ ID: 1, Flavor: "Mint Chocolate", Quantity:150 }
The
)
IceCream
data
source
has been
modified.
Update( IceCream,
Replaces a record from the data
First( Filter( IceCream, Flavor="Strawberry" ) ),
source. The Quantity property
{ ID: 3, Flavor: "Strawberry Swirl"} ) hasn't been supplied in the
The
replacement record, so that
IceCream
property will be blank in the result.
data
source
has been
modified.
Step by step
1. Import or create a collection named Inventory, and show it in a gallery as Show
data in a gallery describes.
ProductGallery.Selected.UnitsInStock
5. Press F5, select a product in the gallery, specify a value with the slider, and then
select the button.
The number of units in stock for the product you specified decreases by the
amount that you specified.
UpdateContext function in Power Apps
Article • 02/23/2023 • 5 minutes to read
Overview
Use the UpdateContext function to create a context variable, which temporarily holds a
piece of information, such as the number of times the user has selected a button or the
result of a data operation.
Context variables are scoped to a screen, which means that you can't build a formula
that refers to a context variable on another screen. If you've used another programming
tool, you can think of a context variable as similar to a local variable. Use the Set
function to work with global variables that are available throughout your app.
Power Apps are based on formulas that automatically recalculate as the user interacts
with an app. Context variables don't offer this benefit and can make your app harder to
create and understand. Before you use a context variable, review working with variables.
Description
To create or update a context variable, pass a single record to the UpdateContext
function. In each record, specify the name of a column, which defines or matches the
name of the variable, and the value to which you want to set that variable.
You can see your variables' values, definitions, and uses with the Variables view under
the File menu in the authoring environment.
You reference a context variable in a formula by using the variable's column name. For
example, UpdateContext( { ShowLogo: true } ) creates a context variable named
ShowLogo and sets its value to true. You can then use the value of this context variable
by using the name ShowLogo in a formula. You can write ShowLogo as the formula for
the Visible property of an image control and show or hide that control based on
whether the value of the context variable is true or false.
As the examples later in this topic show, context variables can hold several kinds of
information, including these:
a single value
a record
a table
an object reference
any result from a formula
A context variable holds its value until the app is closed. If you define a context variable
and set its value on a particular screen, that information remains intact even if the user
switches to a different screen. Once the app is closed, the context variable's value will be
lost and must be recreated when the app is loaded again.
Every context variable is scoped to a screen. If you want to define a context variable on
one screen and modify that variable from another screen, you must build a formula
that's based on the Navigate function. Or use a global variable.
UpdateContext has no return value, and you can use it only within a behavior formula.
Syntax
UpdateContext( UpdateRecord )
UpdateRecord – Required. A record that contains the name of at least one column
and a value for that column. A context variable is created or updated for each
column and value that you specify.
UpdateContext( { Counter: 2 } ) Sets the value of the Counter has the value 2.
Counter context variable
from the previous example
to 2.
UpdateContext( { Person: Works with the Patch Person now has the
Patch( Person, {Address: "2 Main St" } ) function to update the value of record
} ) Person context variable by { Name: "Milton",
setting the value of the Address: "2 Main St" } }.
Address column to 2 Main
St.
Step-by-step example 1
1. Name the default screen Source, add another screen, and name it Target.
2. On the Source screen, add two buttons, and set their Text properties so that one
says English and the other says Spanish.
3. Set the OnSelect property of the English button to this expression:
5. On the Target screen, add a label, and set its Text property to this expression:
6. On the Target screen, select Shapes on the Insert tab, and then select the Back
arrow.
Navigate(Source, ScreenTransition.Fade)
8. From the Source screen, press F5, and then select the button for either language.
On the Target screen, the label appears in the language that corresponds to the
button that you selected.
9. Select the Back arrow to return to the Source screen, and then select the button
for the other language.
On the Target screen, the label appears in the language that corresponds to the
button that you selected.
Step-by-step example 2
1. Open the canvas app where you want to use this formula.
2. Add a new blank screen by selecting New screen from the command bar.
3. Add a button, and set its OnSelect property to this formula:
Description
Update function
Use the Update function to replace an entire record in a data source. In contrast, the
UpdateIf and the Patch functions modify one or more values in a record, leaving the
other values alone.
For a collection, the entire record must match. Collections allow duplicate records, so
multiple records might match. You can use the RemoveFlags.All argument to update all
copies of a record; otherwise, only one copy of the record is updated.
If the data source generates a column's value automatically, the value of that column
must be reaffirmed.
UpdateIf function
Use the UpdateIf function to modify one or more values in one or more records that
match one or more conditions. The condition can be any formula that results in a true
or false and can reference columns of the data source by name. The function evaluates
the condition for each record and modifies any record for which the result is true.
To specify a modification, use a change record that contains new property values. If you
provide this change record inline with curly braces, property formulas can reference
properties of the record that's being modified. You can use this behavior to modify
records based on a formula.
Similar to UpdateIf, you can also use the Patch function to change specific columns of a
record without affecting other columns.
Both Update and UpdateIf return the modified data source as a table. You must use
either function in a behavior formula.
Delegation
When used with a data source, these functions can't be delegated. Only the first portion
of the data source will be retrieved and then the function applied. The result may not
represent the complete story. A warning may appear at authoring time to remind you of
this limitation and to suggest switching to delegable alternatives where possible. For
more information, see the delegation overview.
Syntax
Update( DataSource, OldRecord, NewRecord [, RemoveFlags.All ] )
DataSource – Required. The data source that contains the record that you want to
replace.
OldRecord – Required. The record to replace.
NewRecord – Required. The replacement record. This isn't a change record. The
entire record is replaced, and missing properties will contain blank.
RemoveFlags.All – Optional. In a collection, the same record may appear more than
once. Specify the RemoveFlags.All argument to update all copies of the record.
DataSource – Required. The data source that contains the record or records that
you want to modify.
Condition(s) – Required. A formula that evaluates to true for the record or records
that you want to modify. You can use column names of DataSource in the formula.
ChangeRecord(s) - Required. For each corresponding condition, a change record of
new property values to apply to records of DataSource that satisfy the condition. If
you provide the record inline using curly braces, property values of the existing
record can be used in the property formulas.
Examples
In these examples, you'll replace or modify records in a data source that's named
IceCream and that starts with the data in this table:
Formula Description Result
Update( IceCream,
Replaces a record from the data
First( Filter( IceCream, Flavor="Chocolate" ) ), source.
{ ID: 1, Flavor: "Mint Chocolate", Quantity:150 }
The
)
IceCream
data
source
has been
modified.
Update( IceCream,
Replaces a record from the data
First( Filter( IceCream, Flavor="Strawberry" ) ),
source. The Quantity property
{ ID: 3, Flavor: "Strawberry Swirl"} ) hasn't been supplied in the
The
replacement record, so that
IceCream
property will be blank in the result.
data
source
has been
modified.
Step by step
1. Import or create a collection named Inventory, and show it in a gallery as Show
data in a gallery describes.
ProductGallery.Selected.UnitsInStock
5. Press F5, select a product in the gallery, specify a value with the slider, and then
select the button.
The number of units in stock for the product you specified decreases by the
amount that you specified.
Lower, Upper, and Proper functions in
Power Apps
Article • 03/17/2023 • 2 minutes to read
Converts letters in a string of text to all lowercase, all uppercase, or proper case.
Description
The Lower, Upper, and Proper functions convert the case of letters in strings.
If you pass a single string, the return value is the converted version of that string. If you
pass a single-column table that contains strings, the return value is a single-column
table of converted strings. If you have a multi-column table, you can shape it into a
single-column table, as working with tables describes.
Syntax
Lower( String )
Upper( String )
Proper( String )
Lower( SingleColumnTable )
Upper( SingleColumnTable )
Proper( SingleColumnTable )
Examples
Single string
The examples in this section use a text-input control, named Author, as their data
source. The control contains the string "E. E. CummINGS".
Proper( Author.Text ) Converts the first letter of each word to uppercase if it's "E. E.
lowercase, and converts any other uppercase letters to Cummings"
lowercase.
Single-column table
The examples in this section convert strings from the Address column of the People
data source, which contains this data:
Name Address
Each formula returns a single-column table that contains the converted strings.
Proper(Source.Text)
3. Press F5, and then type WE ARE THE BEST! into the Source box.
Description
The User function returns a record of information about the current user:
Property Description
User().Email Email address of the current user. The User().Email function returns the user's
UPN and not the SMTP email address.
User().FullName Full name of the current user, including first and last names.
User().Image Image of the current user. This will be an image URL of the form
"blob:identifier". Set the Image property of the Image control to this value to
display the image in the app.
7 Note
The information returned is for the current Power Apps user. It will match the
"Account" information that is displayed in the Power Apps players and studio,
which can be found outside of any authored apps. This may not match the current
user's information in Office 365 or other services.
7 Note
If you published your application with a User function prior to March 2020, you
may find that it, intermittently, will not retrieve photos. The issues were fixed in the
late March 2020 release. To take advantage of the updated implementation, simply
re-open your application, save it, and republish it.
Syntax
User()
Examples
The current Power Apps user has the following information:
Image:
User().FullName The full name of the current Power Apps "John Doe"
user.
User().Image The image URL for the current Power Apps "blob:1234...5678"
the app.
Now, Today, IsToday, UTCNow,
UTCToday, IsUTCToday functions in
Power Apps
Article • 02/23/2023 • 4 minutes to read
Returns the current date and time, and tests whether a date/time value is today.
Description
The Now function returns the current date and time as a date/time value.
The Today function returns the current date as a date/time value. The time portion is
midnight. Today has the same value throughout a day, from midnight today to midnight
tomorrow.
The IsToday function tests whether a date/time value is between midnight today and
midnight tomorrow. This function returns a Boolean (true or false) value.
Now, Today, and IsToday functions work with the local time of the current user.
UTCNow, UTCToday, and IsUTCToday functions are the same as their non-UTC
countrparts but work with time zone independent values and use Coordinated Universal
Time (UTC).
7 Note
More information: Work with formula table columns in Dataverse for Teams
See Date, Time, and DateTime in the data types documentation and working with dates
and times for more information.
Volatile Functions
Now, Today, UTCNow, and UTCToday are volatile functions. These functions return a
different value for each evaluation.
When used in a data flow formula, a volatile function will only return a different value if
the formula in which it appears is reevaluated. If nothing else changes in the formula
then it will have the same value throughout the execution of your app.
For example, a label control with Label1.Text = Now() will not change while your app is
active. Only closing and reopening the app will result in a new value.
The function will be reevaluated if it is part of a formula in which something else has
changed. For example, if we change our example to involve a slider control with
Label1.Text = DateAdd( Now(), Slider1.Value, Minutes ) then the current time is
retrieved each time the Slider control's value changes and the label's text property is
reevaluated.
When used in a behavior formula, volatile functions will be evaluated each time the
behavior formula is evaluated. See below for an example.
Syntax
Now()
Today()
IsToday( DateTime )
UTCNow()
UTCToday()
IsUTCToday( TimeZoneIndependentTime )
Text( Now(), Retrieves the current date and time in the user's time "07/11/2021
"mm/dd/yyyy hh:mm:ss" ) zone, and displays it as a string. 20:58:00"
Text( Today(), Retrieves the current date only, leaving the time "07/12/2021
"mm/dd/yyyy hh:mm:ss" ) portion as midnight, and displays it as a string. 00:00:00"
IsToday( Now() ) Tests whether the current date and time is between true
midnight today and midnight tomorrow.
IsToday( Today() ) Tests whether the current date is between midnight true
today and midnight tomorrow.
Text( DateAdd( Now(), 12 Retrieves the current date and time, adds 12 days to "07/23/2021
), "mm/dd/yyyy the result, and displays it as a string. 20:58:00"
hh:mm:ss" )
Text( DateAdd( Today(), 12 Retrieves the current date, adds 12 days to the result, "07/23/2021
), "mm/dd/yyyy and displays it as a string. 00:00:00"
hh:mm:ss" )
IsToday( DateAdd( Now(), Tests whether the current date and time, plus 12 false
12 ) ) days, is between midnight today and midnight
tomorrow.
IsToday( DateAdd( Tests whether the current date, plus 12 days, is false
Today(), 12 ) ) between midnight today and midnight tomorrow.
Hour( UTCNow() ) Retrieves the current date and time in UTC and 4
extracts the hour only, which is 8 hours ahead of
local time.
Day( UTCToday() ) Retrives the current date only in UTC and extracts the 12
day, which is 1 day ahead of local time.
IsUTCToday( UTCNow() ) Tests whether the current date and time is between true
midnight today and midnight tomorrow, all in UTC
time.
IsUTCToday( UTCToday() ) Tests whether the current date is between midnight true
today and midnight tomorrow, all in UTC time.
The timer will run for one second, automatically start over, and continue that
pattern.
Whenever the timer starts over (after each second), this formula sets the
CurrentTime global variable to the current value of the Now function.
3. Add a Label control, and set its Text property to this formula:
Use the Text function to format the date and time however you want, or set this
property to just CurrentTime to show hours and minutes but not seconds.
4. Preview the app by pressing F5, and then start the timer by clicking or tapping it.
The label continually shows the current time, down to the second.
5. Set the timer's AutoStart property to true and its Visible property to false.
6. Set the screen's OnStart property so that the CurrentTime variable has a valid
value, as in this example:
Set(CurrentTime, Now())
The label appears as soon as the app starts (before the timer runs for a full
second).
Now, Today, IsToday, UTCNow,
UTCToday, IsUTCToday functions in
Power Apps
Article • 02/23/2023 • 4 minutes to read
Returns the current date and time, and tests whether a date/time value is today.
Description
The Now function returns the current date and time as a date/time value.
The Today function returns the current date as a date/time value. The time portion is
midnight. Today has the same value throughout a day, from midnight today to midnight
tomorrow.
The IsToday function tests whether a date/time value is between midnight today and
midnight tomorrow. This function returns a Boolean (true or false) value.
Now, Today, and IsToday functions work with the local time of the current user.
UTCNow, UTCToday, and IsUTCToday functions are the same as their non-UTC
countrparts but work with time zone independent values and use Coordinated Universal
Time (UTC).
7 Note
More information: Work with formula table columns in Dataverse for Teams
See Date, Time, and DateTime in the data types documentation and working with dates
and times for more information.
Volatile Functions
Now, Today, UTCNow, and UTCToday are volatile functions. These functions return a
different value for each evaluation.
When used in a data flow formula, a volatile function will only return a different value if
the formula in which it appears is reevaluated. If nothing else changes in the formula
then it will have the same value throughout the execution of your app.
For example, a label control with Label1.Text = Now() will not change while your app is
active. Only closing and reopening the app will result in a new value.
The function will be reevaluated if it is part of a formula in which something else has
changed. For example, if we change our example to involve a slider control with
Label1.Text = DateAdd( Now(), Slider1.Value, Minutes ) then the current time is
retrieved each time the Slider control's value changes and the label's text property is
reevaluated.
When used in a behavior formula, volatile functions will be evaluated each time the
behavior formula is evaluated. See below for an example.
Syntax
Now()
Today()
IsToday( DateTime )
UTCNow()
UTCToday()
IsUTCToday( TimeZoneIndependentTime )
Text( Now(), Retrieves the current date and time in the user's time "07/11/2021
"mm/dd/yyyy hh:mm:ss" ) zone, and displays it as a string. 20:58:00"
Text( Today(), Retrieves the current date only, leaving the time "07/12/2021
"mm/dd/yyyy hh:mm:ss" ) portion as midnight, and displays it as a string. 00:00:00"
IsToday( Now() ) Tests whether the current date and time is between true
midnight today and midnight tomorrow.
IsToday( Today() ) Tests whether the current date is between midnight true
today and midnight tomorrow.
Text( DateAdd( Now(), 12 Retrieves the current date and time, adds 12 days to "07/23/2021
), "mm/dd/yyyy the result, and displays it as a string. 20:58:00"
hh:mm:ss" )
Text( DateAdd( Today(), 12 Retrieves the current date, adds 12 days to the result, "07/23/2021
), "mm/dd/yyyy and displays it as a string. 00:00:00"
hh:mm:ss" )
IsToday( DateAdd( Now(), Tests whether the current date and time, plus 12 false
12 ) ) days, is between midnight today and midnight
tomorrow.
IsToday( DateAdd( Tests whether the current date, plus 12 days, is false
Today(), 12 ) ) between midnight today and midnight tomorrow.
Hour( UTCNow() ) Retrieves the current date and time in UTC and 4
extracts the hour only, which is 8 hours ahead of
local time.
Day( UTCToday() ) Retrives the current date only in UTC and extracts the 12
day, which is 1 day ahead of local time.
IsUTCToday( UTCNow() ) Tests whether the current date and time is between true
midnight today and midnight tomorrow, all in UTC
time.
IsUTCToday( UTCToday() ) Tests whether the current date is between midnight true
today and midnight tomorrow, all in UTC time.
The timer will run for one second, automatically start over, and continue that
pattern.
Whenever the timer starts over (after each second), this formula sets the
CurrentTime global variable to the current value of the Now function.
3. Add a Label control, and set its Text property to this formula:
Use the Text function to format the date and time however you want, or set this
property to just CurrentTime to show hours and minutes but not seconds.
4. Preview the app by pressing F5, and then start the timer by clicking or tapping it.
The label continually shows the current time, down to the second.
5. Set the timer's AutoStart property to true and its Visible property to false.
6. Set the screen's OnStart property so that the CurrentTime variable has a valid
value, as in this example:
Set(CurrentTime, Now())
The label appears as soon as the app starts (before the timer runs for a full
second).
Validate function in Power Apps
Article • 02/23/2023 • 2 minutes to read
The Validate function checks whether the value of a single column or a complete record
is valid for a data source.
Description
Before a user submits a data change, you can provide immediate feedback on the
validity of that submission, resulting in a better user experience.
Data sources can provide information on what constitutes valid values within a record.
This information can include many constraints, such as these examples:
The Validate function uses this information to determine whether a value is valid and to
return an appropriate error message if not. You can use the DataSourceInfo function to
view the same information that Validate uses.
Data sources vary in how much validation information they provide, including not
providing any at all. Validate can only verify values based on this information. Even if
Validate doesn't find a problem, applying the data change may still fail. You can use the
Errors function to obtain information about the failure.
If Validate finds a problem, the function returns an error message that you can show to
the user of the app. If all values are valid, Validate returns blank. When you work with a
collection that has no validation information, values are always valid.
Syntax
Validate( DataSource, Column, Value )
Examples
For these examples, values in the Percentage column of the Scores data source must be
between 0 and 100, inclusive. If the data passes validation, the function returns blank.
Otherwise, the function returns an error message.
Validate( Scores, Checks whether 120 is a valid value for the "Values must be
Percentage, 120 ) Percentage column in the Scores data source. between 0 and 100."
Validate( Scores, Checks whether values in all columns are valid for the blank
EditRecord, Scores data source. In this example, the value in the
Gallery.Updates ) Percentage column is 10.
Validate( Scores, Checks whether values in all columns are valid for the "Values must
EditRecord, Scores data source. In this example, the value in the be between 0
Gallery.Updates ) Percentage column is 120. and 100."
Value function in Power Apps
Article • 03/04/2023 • 2 minutes to read
Description
The Value function converts a string of text that contains number characters to a
number value. Use this function when you need to perform calculations on numbers
that were entered as text by a user.
Different languages interpret , and . differently. By default, the text is interpreted in the
language of the current user. You can specify the language to use with a language tag,
using the same language tags that are returned by the Language function.
The string may be prefixed with the currency symbol for the current language. The
currency symbol is ignored. Currency symbols for other languages are not ignored.
The string may be include a percent sign (%) at the end, indicating that it is a
percentage. The number will be divided by 100 before being returned. Percentages
and currency symbols cannot be mixed.
The string may be in scientific notation, with 12 x 103 expressed as "12e3".
To convert date and time values, use the DateValue, TimeValue, or DateTimeValue
functions.
Syntax
Value( String [, LanguageTag ] )
Value( Untyped )
Examples
The user running these formulas is located in the United States and has selected English
as their language. The Language function is returning "en-US".
Value( "123.456" ) The default language of "en-US" will be used, which uses a period 123.456
as the decimal separator.
Value( "123.456", "es-ES" is the language tag for Spanish in Spain. In Spain, a period 123456
"es-ES" ) is a thousands separator.
Value( "123,456" ) The default language of "en-US" will be used, which uses a 123456
comma as a thousands separator.
Value( "123,456", "es-ES" is the language tag for Spanish in Spain. In Spain, a 123.456
"es-ES" ) comma is the decimal separator.
Value( "12.34%" ) The percentage sign at the end of the string indicates that this is a 0.1234
percentage.
Value( "$ 12.34" ) The currency symbol for the current language is ignored. 12.34
Description
The Average function calculates the average, or arithmetic mean, of its arguments.
Fields of the record currently being processed are available within the formula. Use the
ThisRecord operator or simply reference fields by name as you would any other value.
The As operator can also be used to name the record being processed which can help
make your formula easier to understand and make nested records accessible. For more
information, see the examples below and working with record scope.
These functions operate on numeric values only. Other types of values, such as strings or
records, are ignored. Use the Value function to convert a string into a number.
The Average, Max, Min, and Sum functions can be delegated when used with a data
source that supports delegation for these functions. However, StdevP and VarP can't be
delegated for any data sources. If delegation is not supported, only the first portion of
the data will be retrieved and then the function applied locally. The result may not
represent the complete story. A delegation warning will appear at authoring time to
remind you of this limitation and to suggest switching to delegable alternatives where
possible. For more information, see the delegation overview.
Syntax
Average( NumericalFormula1, [ NumericalFormula2, ... ] )
Examples
Step by step
Let's say that you had a data source named Sales that contained a CostPerUnit column
and a UnitsSold column, and you set the Text property of a label to this function:
The label would show total sales by multiplying the values in those columns for each
record and then adding the results from all records together:
As a different example, let's say that you had sliders that were named Slider1, Slider2,
and Slider3 and a label with its Text property set to this formula:
Sum(Slider1.Value, Slider2.Value, Slider3.Value): The label would show the sum of all
values to which the sliders were set.
View, edit, or create an item, save the contents, and reset the controls in an Edit form
control.
Overview
These functions change the state of the Edit form control. The form control can be in
one of these modes:
Mode Description
FormMode.Edit The form is populated with an existing record and the user can modify the
values of the fields. Once complete, the user can save the changes to the
record.
FormMode.New The form is populated with default values and the user can modify the values
of the fields. Once complete, the user can add the record to the data source.
FormMode.View The form is populated with an existing record but the user cannot modify the
values of the fields.
Description
These functions are often invoked from the OnSelect formula of a Button or Image
control so that the user can save edits, abandon edits, or create a record. You can use
controls and these functions together to create a complete solution.
SubmitForm
Use the SubmitForm function in the OnSelect property of a Button control to save any
changes in a Form control to the data source.
Before submitting any changes, this function checks for validation issues with any field
that's marked as required or that has one or more constraints on its value. This behavior
matches that of the Validate function.
SubmitForm also checks the Valid property of the Form, which is an aggregation of all
the Valid properties of the Card controls that the Form control contains. If a problem
occurs, the data isn't submitted, and the Error and ErrorKind properties of the Form
control are set accordingly.
If successful, the Form's OnSuccess behavior runs, and the Error and ErrorKind
properties are cleared. If the form was in FormMode.New mode, it is returned to
FormMode.Edit mode.
If unsuccessful, the Form's OnFailure behavior runs, and the Error and ErrorKind
properties are set accordingly. The mode of the form is unchanged.
EditForm
The EditForm function changes the Form control's mode to FormMode.Edit. In this
mode, the contents of the Form control's Item property are used to populate the form.
If the SubmitForm function runs when the form is in this mode, a record is changed, not
created. FormMode.Edit is the default for the Form control.
NewForm
The NewForm function changes the Form control's mode to FormMode.New. In this
mode, the contents of the Form control's Item property are ignored, and the default
values of the Form's DataSource property populate the form. If the SubmitForm
function runs when the form is in this mode, a record is created, not changed.
ResetForm
The ResetForm function resets the contents of a form to their initial values, before the
user made any changes. If the form is in FormMode.New mode, the form is reset to
FormMode.Edit mode. The OnReset behavior of the form control also runs. You can also
reset individual controls with the Reset function but only from within the form.
ViewForm
The ViewForm function changes the Form control's mode to FormMode.View. In this
mode, the contents of the Form control's Item property are used to populate the form.
The SubmitForm and ResetForm functions have no effect when in this mode.
DisplayMode Property
The current mode can be read through the Mode property. The mode also determines
the value of the DisplayMode property, which can be used by data cards and controls
within the form control. Often, the data card's DisplayMode property will be set to
Parent.DisplayMode (referencing the form) as will the control's DisplayMode property
(referencing the data card):
FormMode.Edit DisplayMode.Edit Data cards and controls are editable, ready to accept
changes to a record.
FormMode.New DisplayMode.Edit Data cards and controls are editable, ready to accept a
new record.
FormMode.View DisplayMode.View Data cards and controls are not editable and optimized
for viewing.
Syntax
SubmitForm( FormName )
EditForm( FormName )
NewForm( FormName )
ResetForm( FormName )
FormName - Required. Form control to reset to initial values. Also switches the
form from FormMode.New mode to FormMode.Edit mode.
ViewForm( FormName )
1. Add a Button control, set its Text property to show Save, and set its OnSelect
property to this formula:
SubmitForm( EditForm )
2. Set the OnFailure property of a Form control to blank and its OnSuccess property
to this formula:
Back()
3. Name a Label control ErrorText, and set its Text property to this formula:
EditForm.Error
When the user selects the Save button, any changes in the Form control are
submitted to the underlying data source.
If the submission succeeds, any changes are saved or, if the Form control is in
New mode, a record is created. ErrorText is blank and the previous screen
reappears.
If the submission fails, ErrorText shows a user-friendly error message, and the
current screen remains visible so that the user can correct the problem and
try again.
4. Add a Button control, set its Text property to show Cancel, and set its OnSelect
property to this formula:
When the user selects the Cancel button, the values in the Form control are reset
to what they were before the user started to edit it, the previous screen reappears,
and the Form control is returned to Edit mode if it was in New mode.
5. Add a Button control, set its Text property to show New, and set its OnSelect
property to this formula:
When the user selects the New button, the Form control switches to New mode,
the default values for the Form control's data source populate that control, and the
screen that contains the Form control appears. When the SubmitForm function
runs, a record is created instead of updated.
Day, Month, Year, Hour, Minute, Second,
and Weekday functions in Power Apps
Article • 02/23/2023 • 2 minutes to read
Description
The Day function returns the day component of a Date/Time value, ranging from 1 to
31.
The Month function returns the month component of a Date/Time value, ranging from
1 to 12.
The Year function returns the year component of a Date/Time value, starting with 1900.
The Hour function returns the hour component of a Date/Time value, ranging from 0
(12:00 AM) to 23 (11:00 PM).
The Minute function returns the minute component of a Date/Time value, ranging from
0 to 59.
The Second function returns the second component of a Date/Time value, ranging from
0 to 59.
The Weekday function returns the weekday of a Date/Time value. By default, the result
ranges from 1 (Sunday) to 7 (Saturday). You can specify a different range with an
Microsoft Excel Weekday function code or a StartOfWeek enumeration value:
Syntax
Day( DateTime )
Month( DateTime )
Year( DateTime )
Hour( DateTime )
Minute( DateTime )
Second( DateTime )
Examples
For the following example, the current time is 3:59:37 PM on Thursday, April 9, 2015.
Description
Use the WeekNum and ISOWeekNum functions to determine the week number of a date.
These functions differ in how they determine the first week of the year (week 1):
WeekNum uses the week containing January 1 as the first week of the year. The result
from this function can range from 1 to 54.
ISOWeekNum uses the week containing the first Thursday of the year as the first week
of the year. This follows the ISO 8601 date and time standard definition for week
numbering. The result from this function can range from 1 to 53. It is possible that 52
or 53 may be returned for the first days of January since the dates could belong to the
last week of the previous year.
Use the second parameter to WeekNum to specify which day begins a week. You can
provide either an Excel code number or use the StartOfWeek enumeration:
ISOWeekNum always uses Monday as the start of the week. In Excel, the WeekNum
function supports an addition code 21 that is not supported here; use ISOWeekNum
instead.
If you pass a single number to these functions, the return value is a single result. If you pass
a single-column table that contains numbers, the return value is a single-column table of
results, one result for each record in the argument's table. If you have a multi-column table,
you can shape it into a single-column table, as working with tables describes.
Syntax
WeekNum(DateTime [, StartOfWeek ])
ISOWeekNum(DateTime)
DateTime - Required. Date/Time value to operate on. The week always begins on
Monday.
Examples
First and last calendar weeks of 2021
Friday, January 1, 2021 1 53 1
Saturday, January 2, 2021 1 53 1
Sunday, January 3, 2021 2 53 1
Monday, January 4, 2021 2 1 1
Tuesday, January 5, 2021 2 1 1
Wednesday, January 6, 2021 2 1 2
Thursday, January 7, 2021 2 1 2
Saturday, December 25, 2021 52 51 52
Sunday, December 26, 2021 53 51 52
Monday, December 27, 2021 53 52 52
Tuesday, December 28, 2021 53 52 52
Wednesday, December 29, 2021 53 52 53
Thursday, December 30, 2021 53 52 53
Friday, December 31, 2021 53 52 53
With function in Power Apps
Article • 02/23/2023 • 4 minutes to read
Calculates values and performs actions for a single record, including inline records of
named values.
Description
The With function evaluates a formula for a single record. The formula can calculate a
value and/or perform actions, such as modifying data or working with a connection. Use
the ForAll function to evaluate a formula for all the records in a table of records.
Fields of the record currently being processed are available within the formula. Use the
ThisRecord operator or simply reference fields by name as you would any other value.
The As operator can also be used to name the record being processed which can help
make your formula easier to understand and make nested records accessible. For more
information, see the examples below and working with record scope.
Use With to improve the readability of complex formulas by dividing it into smaller
named sub-formulas. These named values act like simple local variables confined to the
scope of the With. The same inline record syntax that is used with the UpdateContext
function can be used with With. Using With is preferred over context or global variables
as it is self contained, easy to understand, and can be used in any declarative formula
context.
Use With to access the fields of the record that are returned by functions such as such
as Patch or Match. With holds the value from these functions long enough to be used in
further calculations or actions.
If the Record argument to With is an error, that error will be returned by the function
and the Formula will not be evaluated.
Syntax
With( Record, Formula )
Record – Required. The record to be acted upon. For names values, use the inline
syntax { name1: value1, name2: value2, ... }
Formula – Required. The formula to evaluate for Record. The formula can reference
any of the fields of Record directly as a record scope.
Examples
height: 15 },
This example uses a record of named values to calculate the volume of a cylinder. With
is being used to capture all the input values together, making it easy to separate them
from the calculation itself.
Nested With
Power Apps
This example nests With functions to create a two-tier calculation for monthly mortgage
payments . As long as there is no conflict, all of the outer With named values are
available within the inner With.
Since the slider controls can only move in increments of 1, the sliders are divided or
multiplied to create effectively a custom increment. In the case of the interest rate, the
RateSlider has its Max property set to 48, divided by 8 for a 1/8 percentage point
increment and divided by 100 to convert from a percentage to a decimal, covering the
range 0.125% to 6%. In the case of of the loan amount, the AmountSlider has its Max
property set to 60 and multiplied by 10,000, covering the range 10,000 to 600,000.
The With is automatically recalculated as the sliders move and the new loan payment
displayed. No variables are used and there is no need to use the OnChange property of
the slider controls.
ForAll( NewOrderDetails,
This example adds a record to the Order table in SQL Server. It then uses the returned
primary key for the order, returned by the Patch function in the OrderID field, to create
related records in the OrderDetails table.
With(
// Result: 2:01 AM (as shown in a label control, use the Text function to
see the seconds)
This example extracts the hours, minutes, and seconds from an ISO 8601 duration value
and then uses these sub-matches to create a Date/Time value.
Note that although the sub-matches contain numbers they are still in a text string. Use
the Value function to convert to a number before performing mathematical operations.
Description
The Day function returns the day component of a Date/Time value, ranging from 1 to
31.
The Month function returns the month component of a Date/Time value, ranging from
1 to 12.
The Year function returns the year component of a Date/Time value, starting with 1900.
The Hour function returns the hour component of a Date/Time value, ranging from 0
(12:00 AM) to 23 (11:00 PM).
The Minute function returns the minute component of a Date/Time value, ranging from
0 to 59.
The Second function returns the second component of a Date/Time value, ranging from
0 to 59.
The Weekday function returns the weekday of a Date/Time value. By default, the result
ranges from 1 (Sunday) to 7 (Saturday). You can specify a different range with an
Microsoft Excel Weekday function code or a StartOfWeek enumeration value:
Syntax
Day( DateTime )
Month( DateTime )
Year( DateTime )
Hour( DateTime )
Minute( DateTime )
Second( DateTime )
Examples
For the following example, the current time is 3:59:37 PM on Thursday, April 9, 2015.
7 Note
Microsoft Power Fx is the new name for the formula language for canvas apps.
These articles are a work in progress as we extract the language from canvas apps,
integrate it with other Microsoft Power Platform products, and make it available as
open source. Start with the Microsoft Power Fx overview for an introduction to the
language.
Microsoft Power Fx is based on formulas that bind a name to an expression. Just like in
Excel worksheets, as inbound dependencies to the expression change, the expression is
recalculated and the value of the name changes, possibly cascading the recalculation
into other formulas.
This grammar covers the expression part of the formula. Binding to a name to create a
formula is dependent on how Power Fx is integrated. In worksheets, the binding syntax
isn't exposed, it's implied by the location where the expression is written—for example,
entering =B1 in the A1 cell. In some cases, no binding is required at all and Power Fx is
used as an expression evaluator, for example in supporting calculated columns of a
database table. For Power Apps, the binding is implied when working in Power Apps
Studio with a serialization format based on YAML for use outside Power Apps Studio.
Grammar conventions
The lexical and syntactic grammars are presented by using grammar productions. Each
grammar production defines a non-terminal symbol and the possible expansions of that
non-terminal symbol into sequences of non-terminal or terminal symbols. In grammar
productions, non-terminal symbols are shown in italic type, and terminal symbols are
shown in a fixed-width font.
The first line of a grammar production is the name of the non-terminal symbol being
defined, followed by a colon. Each successive indented line contains a possible
expansion of the non-terminal symbol given as a sequence of non-terminal or terminal
symbols. For example, the production:
GlobalIdentifier :
[@ Identifier ]
defines a GlobalIdentifier to consist of the token [@ , followed by an Identifier, followed
by the token ] .
When there is more than one possible expansion of a non-terminal symbol, the
alternatives are listed on separate lines. The subscript "opt" is used to indicate an
optional symbol. For example, the production:
FunctionCall :
FunctionIdentifier ( FunctionArgumentsopt )
is shorthand for:
FunctionCall :
FunctionIdentifier ( )
FunctionIdentifier ( FunctionArguments )
Alternatives are normally listed on separate lines, though in cases where there are many
alternatives, the phrase "one of" might precede a list of expansions given on a single
line. This is simply shorthand for listing each of the alternatives on separate lines.
DecimalDigit : one of
0 1 2 3 4 5 6 7 8 9
is shorthand for:
DecimalDigit :
0
1
2
3
4
5
6
7
8
9
Lexical analysis
The lexical-unit production defines the lexical grammar for a Power Fx expression. Every
valid Power Fx expression conforms to this grammar.
ExpressionUnit :
ExpressionElementsopt
ExpressionElements :
ExpressionElement
ExpressionElement ExpressionElementsopt
ExpressionElement :
Whitespace
Comment
Whitespace
Whitespace is used to separate comments and tokens within a Power Apps document.
Whitespace :
Comments
Two forms of comments are supported:
Single-line comments that start with the characters // and extend to the end of
the source line.
Delimited comments that start with the characters /* and end with the characters
*/ . Delimited comments can span multiple lines.
Comment :
DelimitedComment
SingleLineComment
SingleLineComment :
// SingleLineCommentCharactersopt
SingleLineCommentCharacters :
SingleLineCommentCharacter
SingleLineCommentCharacter SingleLineCommentCharactersopt
SingleLineCommentCharacter :
DelimitedComment :
/* DelimitedCommentCharactersopt */
DelimitedCommentCharacters :
DelimitedCommentCharactersNoAsterisk DelimitedCommentCharactersopt
* DelimitedCommentAfterAsteriskCharacters
DelimitedCommentAfterAsteriskCharacters :
DelimitedCommentNoSlashAsteriskCharacter DelimitedCommentCharactersopt
* DelimitedCommentAfterAsteriskCharacters
DelimitedCommentCharactersNoAsterisk :
DelimitedCommentNoSlashAsteriskCharacter :
Comments aren't nested. The character sequences /* and */ have no special meaning
within a single-line comment, and the character sequences // and /* have no special
meaning within a delimited comment.
Power Apps
/* Hello, world
*/
Power Apps
// Hello, world
//
Literals
A literal is a source code representation of a value.
Literal :
LogicalLiteral
NumberLiteral
TextLiteral
Logical literals
A logical literal is used to write the values true and false, and produce a logical value.
LogicalLiteral : one of
Number literals
A number literal is used to write a numeric value and produce a number value.
NumberLiteral :
DecimalDigits ExponentPartopt
DecimalDigits DecimalSeparator DecimalDigitsopt ExponentPartopt
DecimalSeparator DecimalDigits ExponentPartopt
DecimalDigits :
DecimalDigit
DecimalDigits DecimalDigit
DecimalDigit : one of
0 1 2 3 4 5 6 7 8 9
ExponentPart :
ExponentIndicator Signopt DecimalDigits
ExponentIndicator : one of
e E
Sign : one of
+ -
Text literals
A text literal is used to write a sequence of Unicode characters and produce a text value.
Text literals are enclosed in double quotation marks. To include double quotation marks
in the text value, repeat the double quotation marks, as shown in the following example:
Power Apps
TextLiteral :
TextLiteralCharacters :
TextLiteralCharacter TextLiteralCharactersopt
TextLiteralCharacter :
TextCharacterNoDoubleQuote
DoubleQuoteEscapeSequence
TextCharacterNoDoubleQuote :
DoubleQuoteEscapeSequence :
Identifiers
An identifier is a name used to refer to a value. Identifiers can either be regular
identifiers or single quoted identifiers.
Identifier :
IdentifierName :
IdentifierStartCharacter IdentifierContinueCharactersopt
IdentifierStartCharacter :
LetterCharacter
_
IdentifierContinueCharacter :
IdentifierStartCharacter
DecimalDigitCharacter
ConnectingCharacter
CombiningCharacter
FormattingCharacter
IdentifierContinueCharacters :
IdentifierContinueCharacter IdentifierContinueCharactersopt
LetterCharacter :
any Unicode character of the class Uppercase letter (Lu) or Lowercase letter
(Ll)
any Unicode character of the class Letter modifier (Lm) or Letter other (Lo)
CombiningCharacter :
DecimalDigitCharacter :
ConnectingCharacter :
FormattingCharacter :
SingleQuotedIdentifier :
SingleQuotedIdentifierCharacters
SingleQuotedIdentifierCharacters :
SingleQuotedIdentifierCharacter SingleQuotedIdentifierCharactersopt
SingleQuotedIdentifierCharacter :
TextCharactersNoSingleQuote
SingleQuoteEscapeSequence
TextCharactersNoSingleQuote :
SingleQuoteEscapeSequence :
Disambiguated identifier
DisambiguatedIdentifier:
TableColumnIdentifier
GlobalIdentifier
TableColumnIdentifier :
Identifier [@ Identifier ]
GlobalIdentifier:
[@ Identifier ]
Context keywords
ContextKeyword:
Parent
Self
ThisItem
ThisRecord
Case sensitivity
Power Apps identifiers are case-sensitive. The authoring tool will automatically change
them to the correct case when a formula is being written.
Separators
DecimalSeparator:
. (dot) for languages that use a dot as the separator for decimal numbers, for
example 1.23
, (comma) for languages that use a comma as the separator for decimal
numbers, for example 1,23
ListSeparator:
ChainingSeparator:
Operators
Operators are used in formulas to describe operations involving one or more operands.
For example, the expression a + b uses the + operator to add the two operands a and
b.
Operator:
BinaryOperator
BinaryOperatorRequiresWhitespace
PrefixOperator
PrefixOperatorRequiresWhitespace
PostfixOperator
BinaryOperator: one of
+ - * / ^
&
&& ||
in exactin
BinaryOperatorRequiresWhitespace:
Or Whitespace
PrefixOperator:
!
PrefixOperatorRequiresWhitespace:
PostfixOperator:
%
Reference operator
ReferenceOperator: one of
. !
Object reference
Reference:
BaseReference
BaseReference ReferenceOperator ReferenceList
BaseReference:
Identifier
DisambiguatedIdentifier
ContextKeyword
ReferenceList:
Identifier
Identifier ReferenceOperator ReferenceList
Inline record
InlineRecord:
{ InlineRecordListopt }
InlineRecordList:
Identifier : Expression
Identifier : Expression ListSeparator InlineRecordList
Inline table
InlineTable:
[ InlineTableListopt ]
InlineTableList:
Expression
Expression ListSeparator InlineTableList
Expression
Expression:
Literal
Reference
InlineRecord
InlineTable
FunctionCall
( Expression )
PrefixOperator Expression
Expression PostfixOperator
Expression BinaryOperator Expression
Chained expressions
ChainedExpression:
Expression
Expression ChainingSeparator ChainedExpressionopt
Function call
FunctionCall:
FunctionIdentifier ( FunctionArgumentsopt )
FunctionIdentifier:
Identifier
Identifier . FunctionIdentifier
FunctionArguments:
ChainedExpression
ChainedExpression ListSeparator FunctionArguments
7 Note
Microsoft Power Fx is the new name for the formula language for canvas apps.
These articles are a work in progress as we extract the language from canvas apps,
integrate it with other Microsoft Power Platform products, and make it available as
open source. Start with the Microsoft Power Fx overview for an introduction to the
language.
We've selected the industry standard YAML as our language for this binding. There are
already a large number of editors, tools, and libraries for working with YAML. This article
describes how we represent formulas in YAML.
At this time, we support only a restricted subset of YAML. Only the constructs described
in this article are supported.
Not everything that defines a canvas app is represented here; additional information
flows through other files that the tool produces and consumes.
Visible: =true
X: =34
Text: |
"World"
It's consistent with Excel, which uses a leading = to bind an expression to a cell.
It effectively escapes the formula language's syntax so that YAML doesn't attempt
to parse it. Normally, YAML would treat text: 1:00 as minutes and seconds,
converting it to a number. By inserting an = , YAML won't use its implicit typing
rules and formulas won't be harmed. Using = covers most cases, but not all, and
those exceptions are described in the following section, Single-line formulas.
In the future, we will support both formulas (starts with = ) and non-formulas (no
= ) in the same file, just as Excel does We can do this in YAML and non-YAML files
alike across Microsoft Power Platform source files. Anywhere a formula is
supported, the leading = differentiates a Power Apps formula expression from a
static scalar value.
Single-line formulas
Single-line formulas are written in the form:
The space between the colon and the equal sign is required to be YAML-compliant. The
equal sign disrupts YAML's normal interpretation of the expression, allowing the rest of
the line to be interpreted as Power Fx.
For example:
Boolean1: =true
Time1: =1:34
The number sign # and colon : aren't allowed anywhere in single-line formulas, even if
they're in a quoted text string or identifier name. To use a number sign or colon, you
must express the formula as a multiline formula. The number sign is interpreted as a
comment in YAML, and the colon is interpreted as a new name map in YAML. To add a
comment to a single-line comment, use the Power Fx line comment starting with // .
Using normal YAML escaping with single quotes and C-like backslashes isn't supported;
use a multiline formula instead. This is for consistency and to facilitate cut/paste
between the formula bar in Power Apps Studio and YAML source files.
See the canvas apps operators and identifiers documentation for details on allowed
names and the structure of an expression.
Multiline formulas
Formulas can span multiple lines by using YAML's block scalar indicators:
Name : SPACE ( | or |+ or |- )
= Expression-Line
Expression-Line
...
All lines that are a part of the block must be indented at least one space in from the
level of the first line.
For example:
Text1: |
="Hello, World"
Text2: |
="Hello" &
"," &
"World"
All forms of YAML multiline scalar notations are accepted on import, including >+ , for
example. However, to ensure that whitespace is properly preserved, only | , |+ , or |-
are produced.
Component instance
Components are instanced by using YAML object notation. The type of the object is
established with the As operator as a part of the left-side YAML tag. For container
controls, objects can be nested.
All lines that are a part of the block must be indented at least one space in from the
level of the first line.
For example:
Gallery1 As Gallery.horizontalGallery:
Fill: = Color.White
Label1 As Label:
X: =20
Y: =40
Fill: |
Color.Red,
Color.Black
Component-Type can be any canvas component or control. Base types, such as Number,
aren't supported.
If Name contains special characters and is wrapped with single quotation marks, the
entire phrase to the left side of the colon will need to be escaped. This can be done in
one of the following ways:
Use single quotation marks to wrap the entire left side, which requires that the
existing single quotation marks be used twice:
Use double quotation marks to wrap the entire left side, but be sure that there are
no double quotation marks in the name:
Component definition
Similarly, components are defined by creating an instance of one of the supported base
types. The base types can't be instanced directly. Within an object definition, properties
can be added to what the base type provides.
For input properties, the expression provides the default to be inserted into the app
when the component is instanced. The maker can modify this expression as they see fit,
but can't change the type.
For output properties, the expression provides the calculation to be performed. The
maker can't modify this expression, it's encapsulated in the component.
At this time, all properties are data flow only and can't contain side effects.
At this time, additional metadata about the property isn't defined here but is instead
defined in the other files of the .msapp file, for example the property's description.
For example:
DateRangePicker As CanvasComponent:
DefaultStart: |-
Now()
DefaultEnd: |-
YAML compatibility
YAML comments
YAML line comments delimited by the number sign # aren't preserved anywhere in the
source format. Instead, within a formula, delimit line comments with // characters or
block comments with /* and */ . More information: Comments
Record: ={ a: 1, b: 2 }
the number sign # is treated as a comment by YAML, even though it's embedded in
what Excel considers a text string (wrapped by double quotation marks). To avoid
confusion, this case will throw an error during import. A YAML multiline form can be
used instead.
In the case of the value for record , YAML considers a: and b: to be another name map
binding. YAML allows the same name map to be reused, with the last one silently
overriding any previous definitions. Because this can be confusing for a low-code maker
and can result in the loss of a property formula, an error is thrown if the same name is
encountered twice.