Microsoft Power FX
Microsoft Power FX
Microsoft Power Fx
Power Fx
Overview
Expression grammar
YAML formula grammar
Global apps
Data types
Untyped objects (experimental)
Working with JSON (experimental)
Imperatives
Operators
Tables
Variables
Formula reference
Overview
Abs
Acceleration
Acos
Acot
AddColumns
And
App
As
Asin
Assert
AsType
Atan
Atan2
Average
Back
Blank
Boolean
Calendar
Char
Choices
Clear
ClearCollect
Clock
Coalesce
Collect
Color
ColorFade
ColorValue
Compass
Concat
Concatenate
Concurrent
Connection
Count
Cos
Cot
CountA
CountIf
CountRows
DataSourceInfo
Date
DateAdd
DateDiff
DateTimeValue
DateValue
Day
Defaults
Degrees
Disable
Distinct
Download
DropColumns
EditForm
Enable
EncodeUrl
EndsWith
Error
Errors
exactin
Exit
Exp
Filter
Find
First
FirstN
ForAll
GroupBy
GUID
HashTags
Hour
Identifiers
If
IfError
in
Index
Int
IsBlank
IsBlankOrError
IsEmpty
IsError
IsMatch
IsNumeric
ISOWeekNum
IsToday
IsType
IsUTCToday
JSON
Language
Last
LastN
Launch
Left
Len
Ln
LoadData
Location
LookUp
Lower
Match
MatchAll
Max
Mid
Min
Minute
Mod
Month
Navigate
NewForm
Not
Notify
Now
Operators
Or
Param
Parent
ParseJSON (experimental)
Patch
PDF
Pi
PlainText
Power
Print
Proper
Radians
Rand
RandBetween
ReadNFC
RecordInfo
Refresh
Relate
Remove
RemoveIf
RenameColumns
Replace
Reset
ResetForm
Revert
RequestHide
RGBA
Right
Round
RoundDown
RoundUp
SaveData
Search
Second
Select
Self
Set
SetFocus
SetProperty
Sequence
ShowColumns
Shuffle
Sin
Sort
SortByColumns
Split
Sqrt
StartsWith
StdevP
Substitute
SubmitForm
Sum
Switch
Table
Tan
Text
ThisItem
ThisRecord
Time
TimeValue
TimeZoneOffset
Today
Trace
Trim
TrimEnds
Trunc
Ungroup
Unrelate
Update
UpdateContext
UpdateIf
Upper
User
UTCNow
UTCToday
Validate
Value
VarP
ViewForm
Weekday
WeekNum
With
Year
Use Power Fx formulas in Power Apps
Microsoft Power Fx overview
11/19/2022 • 20 minutes to read • Edit Online
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.
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.
Power Fx binds objects together with declarative spreadsheet-like formulas. For example, think of the Visible
property of a UI control as a cell in an Excel worksheet, with an associated formula that calculates its value based
on the properties of other controls. The formula logic recalculates the value automatically, similar to how a
spreadsheet does, which affects the visibility of the control.
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?
What if you could take advantage of your existing spreadsheet knowledge?
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 result of an expression can be placed in a variable, used as an
argument to a procedure, or nested in a bigger expression.
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, force is
automatically updated to a new value. The expression described a calculation, a formula gave that calculation a
name and used it as a recipe. This is why we refer to Power Fx as a formula language.
For example, this formula from Stack Overflow searches a string in reverse order. In Excel, it looks like the
following image.
Screenshot of a formula bar in Excel with the formula: =RIGHT(A1,LEN(A1)- FIND("|", SUBSTITUTE(A1," ","|",
LEN(A1)-LEN(SUBSTITUTE(A1," ","")))) Cell A1 contains the text "Hello, World! It is great to meet you!" Cell A2
contains the text "you!"
Power Fx works with this same formula, with the cell references replaced with control property references:
Screenshot of a Power Fx formula bar in Power Apps. The formula is =RIGHT(Input.Text,Len(Input.Text)- FIND("|",
SUBSTITUTE(Input.Text," ","|", Len(Input.Text)-Len(Substitute(Input.Text," ","")))) In the Input box below the
formula, the text "Hello, World! It is great to meet you!" appears, letter by letter. At the same time in the Label
box, the letters of the last word appear. When the full text appears in the Input box, the word "you!" appears in
the Label box.
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:
Asynchronous : All data operations in Power Fx are asynchronous. The maker doesn't need to specify
this, nor does the maker need to synchronize operations after the call is over. The maker doesn't need to
be aware of this concept at all, they don't need to know what a promise or lambda function is.
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.
Professionals want to use professional tools to be most productive. Power Fx formulas can be stored in YAML
source files, which are easy to edit with Visual Studio Code, Visual Studio, or any other text editor and enable
Power Fx to be put under source control with GitHub, Azure DevOps, or any other source code control system.
Power Fx supports formula-based components for sharing and reuse. We announced support for parameters to
component properties, enabling the creation of pure user-defined functions with more enhancements on the
way.
Also, Power Fx is great at stitching together components and services built by professionals. Out-of-the-box
connectors provide access to hundreds of data sources and web services, custom connectors enable Power Fx to
talk to any REST web service, and code components enable Power Fx to interact with fully custom JavaScript on
the screen and page.
Design principles
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 Galler y 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.
Conflicting type usage results in a compile-time error.
Locale -sensitive decimal separators
Some regions of the world use a dot (.) as the decimal separator, while others use a comma (,). This is what Excel
does, too. This is commonly not done in other programming languages, which generally use a canonical dot (.)
as the decimal separator for all users worldwide. To be as approachable as possible for makers at all levels, it's
important that 3,14 is a decimal number for a person in France who has used that syntax all their lives.
The choice of decimal separator has a cascading impact on the list separator, used for function call arguments,
and the chaining operator.
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
Operators and identifiers
Tables
Variables
Imperative logic
Global support
Expression grammar
YAML formula grammar
Formulas in canvas apps
Expression grammar
11/19/2022 • 8 minutes to read • Edit Online
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.
For example, the production:
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
At the lexical level, a Power Fx expression consists of a stream of Whitespace, Comment, and Token elements.
Each of these productions is covered in the following sections. Only Token elements are significant in the
syntactic grammar.
Whitespace
Whitespace is used to separate comments and tokens within a Power Apps document.
Whitespace :
any Unicode Space separator (class Zs)
any Unicode Line separator (class Zl)
any Unicode Paragraph separator (class Zp)
Horizontal tab character (U+0009)
Line feed character (U+000A)
Vertical tab character (U+000B)
Form feed character (U+000C)
Carriage return character (U+000D)
Next line character (U+0085)
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 :
any Unicode characters except a NewLineCharacter
DelimitedComment :
/* DelimitedCommentCharactersopt */
DelimitedCommentCharacters :
DelimitedCommentCharactersNoAsterisk DelimitedCommentCharactersopt
* DelimitedCommentAfterAsteriskCharacters
DelimitedCommentAfterAsteriskCharacters :
DelimitedCommentNoSlashAsteriskCharacter DelimitedCommentCharactersopt
* DelimitedCommentAfterAsteriskCharacters
DelimitedCommentCharactersNoAsterisk :
any Unicode character except * (asterisk)
DelimitedCommentNoSlashAsteriskCharacter :
any Unicode character except a / (slash) or * (asterisk)
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.
Comments aren't processed within text-literal strings.
The following example includes two delimited comments:
/* Hello, world
*/
"Hello, world" /* This is an example of a text literal */
// Hello, world
//
"Hello, world" // This is an example of a text literal
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
true false
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:
TextLiteral :
" TextLiteralCharactersopt "
TextLiteralCharacters :
TextLiteralCharacter TextLiteralCharactersopt
TextLiteralCharacter :
TextCharacterNoDoubleQuote
DoubleQuoteEscapeSequence
TextCharacterNoDoubleQuote :
any Unicode code point except double quote
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 but not Operator or ContextKeyword
IdentifierName :
IdentifierStartCharacter IdentifierContinueCharactersopt
' SingleQuotedIdentifier '
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 Titlecase letter (Lt )
any Unicode character of the class Letter modifier (Lm ) or Letter other (Lo )
any Unicode character of the class Number letter (Nl )
CombiningCharacter :
any Unicode character of the class Non-spacing mark (Mn ) or Spacing combining mark (Mc )
DecimalDigitCharacter :
any Unicode character of the class Decimal digit (Nd )
ConnectingCharacter :
any Unicode character of the class Connector punctuation (Pc )
FormattingCharacter :
any Unicode character of the class Format (Cf )
Single quoted identifiers
A single quoted identifier can contain any sequence of Unicode characters to be used as an identifier, including
keywords, whitespace, comments, and operators. Single quotation mark characters are supported with an
escape sequence of two single quotation marks.
SingleQuotedIdentifier :
SingleQuotedIdentifierCharacters
SingleQuotedIdentifierCharacters :
SingleQuotedIdentifierCharacter SingleQuotedIdentifierCharactersopt
SingleQuotedIdentifierCharacter :
TextCharactersNoSingleQuote
SingleQuoteEscapeSequence
TextCharactersNoSingleQuote :
any Unicode character except ' (U+0027)
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:
, (comma) if DecimalSeparator is . (dot)
; (semicolon) if DecimalSeparator is , (comma)
ChainingSeparator:
; (semicolon) if DecimalSeparator is . (dot)
;; (double semicolon) if DecimalSeparator is , (comma)
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:
And Whitespace
Or Whitespace
PrefixOperator:
!
PrefixOperatorRequiresWhitespace:
Not Whitespace
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
Power Fx YAML formula grammar
11/19/2022 • 6 minutes to read • Edit Online
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 has a well-established grammar for expressions based on Excel. However, when used in
Power Apps and other hosts where UI provides the name-to-expression binding for a formula, there is no
standard way of editing the formula binding as text.
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: |
="Hello, " &
"World"
Single-line formulas
Single-line formulas are written in the form:
Name : SPACE = Expression
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:
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.
Name As Component-Type [ . Component-Template ] : ( Single-Line-Formula or Multi-Line-
Formula or Object-instance ) ...
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:
Text: ="Hello, World"
X: =20
Y: =40
Fill: |
=If( Lower( Left( Self.Text, 6 ) ) = "error:",
Color.Red,
Color.Black
)
Component-Type can be any canvas component or control. Base types, such as Number, aren't supported.
Component-Template is an optional specifier for components that have different templates, such as the Gallery.
Not all components have templates.
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.
The supported base types are: CanvasComponent
Simple property definition
Components use properties to communicate with the app in which they're hosted.
Name : ( Single-Line-Expression or Multi-Line-Expression )
The type of the formula is implied by the type of the expression.
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: |-
=// input property, customizable default for the component instance
Now()
DefaultEnd: |-
=// input property, customizable default for the component instance
DateAdd( Now(), 1, Days )
SelectedStart: =DatePicker1.SelectedDate // output property
SelectedEnd: =DatePicker2.SelectedDate // output property
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
Errors for common pitfalls
There are a few places where the Power Fx and YAML grammars are incompatible or might be confusing for a
user. In these cases, an error is thrown.
For example, in the following:
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.
Global support
11/19/2022 • 7 minutes to read • Edit Online
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:
Function names: If , Navigate , Collect , and so on.
Control property names: Screen.Fill , Button.OnSelect , Textbox.Font , and so on.
Enumeration names: Color.Aqua , DataSourceInfo.MaxValue , FontWeight.Bold , and so on.
Signal records: Compass.Heading , Location. Latitude , App.ActiveScreen , and so on.
Operators: Parent , in , exactIn , and so on.
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.
You can use whatever names you like for:
Control names
Collection names
Context variable names
Formula separators and chaining operator
Some separators and operators will shift based on the decimal separator of the author's language:
The change in the Power Apps list separator is consistent with what happens to the Excel list separator. It
impacts:
Arguments in function calls.
Fields in a record.
Records in a table.
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.
And then use a formula such as the following to pull translated strings from the table:
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.
Formatting numbers, dates, and times
Numbers, dates, and times are written in different formats in different parts of the world. The meaning of
commas, decimals, and the order of month, date, and year vary from location to location.
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:
A global aware enumeration. For example, Text( Now(), DateTimeFormat.LongDate ) . This formula
will format the current date in a language appropriate format. This method is the preferred way to specify the
format string.
A custom format string. For example, Text( Now(), "[$-en-US]dddd, mmmm dd, yyyy" ) displays the
same text as the enumeration when used in the language "en-US". The advantage of the custom format
string is that you can specify exactly what you want.
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.
Reading numbers, dates, and times
There are four functions for reading numbers, dates, and times provided by the user:
Value : Converts a number in a text string to a number value.
DateValue : Converts a date value in a text string to a date/time value. Anytime specified in the text string is
ignored.
TimeValue : Converts a time value in a text string to a date/time value. Any date specified in the text string is
ignored.
DateTimeValue : Converts a date and time value in a text string to a date/time value.
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.
All of these functions have the same arguments:
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:
Value( "12,345.678", "en-US" ) or Value( "12,345.678" ) when located where "en-US" is the user's
language returns the number 12345.678 , ready for calculations.
DateValue( "1/2/01", "es-ES" ) or DateValue( "1/2/01" ) when located where "es-ES" is the user's
language returns the date/time value Februar y 1, 2001 at midnight .
TimeValue( "11:43:02", "fr-FR" ) or TimeValue( "11:43:02" ) when located where "fr-FR" is the user's
language returns the date/time value Januar y 1, 1970 at 11:43:02 .
DateTimeValue( "11:43:02 1/2/01", "de-DE" ) or DateTimeValue( "11:43:02 1/2/01" ) when located
where "de-DE" is the user's language returns the date/time value Februar y 1, 2001 at 11:43:02 .
For more information, see the documentation for the Value and DateValue, TimeValue, and DateTimeValue
functions.
Calendar and Clock information
The Calendar and Clock functions provide calendar and clock information for the user's current language.
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.
Data types
11/19/2022 • 17 minutes to read • Edit Online
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 Bir thday field and an Anniversar y 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
the app's user. 1:23:09 PM" )
Media A URI text string to a video or audio MyVideo added as an app resource
recording. "https://nor thwindtraders.com/int
ro.mp4"
"appres://blobmanager/3ba411c...
"
Time A time without a date, in the time zone Time( 11, 23, 45 )
of the app's user.
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.
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:
$"We have {Apples} apples, {Bananas} bananas, yielding {Apples+Bananas} fruit total."
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:
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:
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".
Newlines
Embedded text strings can contain newlines. For example, consider setting the Text property of a Label control
to the following:
"Line 1
Line 2
Line 3"
The above formula results in three lines shown in the label control:
Newlines are also supported with string interpolation, as shown below:
$"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:
URIs for images and other media
You can dig a little deeper into that last example by setting the Text property of a Label control to nwindlogo .
The label shows a text string:
Canvas apps reference each image or other media file, whether it's in the cloud or added as an app resource, by
a URI text string.
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:
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAFAQMAAACtnVQoAAAABlBMVEUAAAB0J3UMNU6VAAAAAXRSTlMAQObYZ
gAAABRJREFUCNdjUGJgCGVg6GgAkkA2AA8/AffqCEBsAAAAAElFTkSuQmCC"
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.
VA L UE DISP L AY ED A N D VA L UE DISP L AY ED A N D
VA L UE STO RED IN T H E EN T ERED 7 H O URS W EST EN T ERED 4 H O URS EA ST O F
DAT E/ T IM E T Y P E DATA B A SE O F UTC UTC
User local Sunday, May 19, 2019 Saturday, May 18, 2019 Sunday, May 19, 2019
4:00 AM 9:00 PM 8:00 AM
Time zone independent Sunday, May 19, 2019 Sunday, May 19, 2019 Sunday, May 19, 2019
4:00 AM 4:00 AM 4:00 AM
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.
Returning to our example from above:
VA L UE DISP L AY ED A N D
VA L UE STO RED IN T H E EN T ERED 7 H O URS W EST
DAT E/ T IM E T Y P E DATA B A SE O F UTC VA L UE F UN C T IO N RET URN S
User local Sunday, May 19, 2019 Saturday, May 18, 2019 1,558,238,400,000
4:00 AM 9:00 PM (Sunday, May 19, 2019
4:00 AM UTC)
Time zone independent Sunday, May 19, 2019 Sunday, May 19, 2019 1,558,263,600,000
4:00 AM 4:00 AM (Sunday, May 19, 2019
11:00 AM UTC)
Converting Unix times
Unix times reflect the number of seconds since January 1, 1970 00:00:00 UTC. Because canvas apps use
milliseconds instead of seconds, you can convert between the two by multiplying or dividing by 1,000.
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.
To convert to a Unix time, divide the result from Value by 1,000:
RoundDown( Value( UnixTime ) / 1000, 0 )
If you need the Unix time in a Date value for further calculations or display within Power Apps, use this formula:
DateAdd( Date( 1970,1,1 ), UnixTime, Seconds )
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:
With(
Match( "PT2H1M39S", "PT(?:(?<hours>\d+)H)?(?:(?<minutes>\d+)M)?(?:(?<seconds>\d+)S)?" ),
Time( Value( hours ), Value( minutes ), Value( seconds ) )
)
// Result: 2:01 AM (as shown in a label control, use the Text function to see the seconds)
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:
If( ThisItem.Taxable = TaxStatus.Taxable, ...
IMPORTANT
This is an experimental feature.
Experimental features aren’t meant for production use and may have restricted functionality. These features are
available before an official release so that customers can get early access and provide feedback. More information:
Understand experimental, preview, and deprecated features in Power Apps
The behavior that this article describes is available only when the ParseJSON function and untyped objects
experimental feature in Settings > Upcoming features > Experimental is turned on (off by default).
Your feedback is very valuable to us - please let us know what you think in the Power Apps experimental features
community forum.
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 .
Text(UOValue)
Value(UOValue)
The following table lists the data types and corresponding functions to convert untyped object to that data
type.
Date, DateTime, Time DateValue(), TimeValue() or Date, time and datetime can be
DateTimeValue() directly converted from untyped
object to their respective type, when
represented in ISO 8601 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, Image, Media Text() These data types are text data types,
and can be converted to text and then
used in Power Fx.
Choice, Two Option Switch() or If() Choices and two options are
presented as localized strings in Power
Fx. Choices are backed by a number
and two options as 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.
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 .
Text(UORecord.StringField)
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:
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:
Value( Index( UOArray, 2 ) )
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 :
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.
When using the Table() function, first retrieve the single-column Value column to get the untyped object ,
then access the Field column:
To convert an array of records to a typed table, you can use the ForAll() function and convert each individual
field.
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.
IMPORTANT
This is an experimental feature.
Experimental features aren’t meant for production use and may have restricted functionality. These features are
available before an official release so that customers can get early access and provide feedback. More information:
Understand experimental, preview, and deprecated features in Power Apps
The behavior that this article describes is available only when the ParseJSON function and untyped objects
experimental feature in Settings > Upcoming features > Experimental is turned on (off by default).
Your feedback is very valuable to us - please let us know what you think in the Power Apps experimental features
community forum.
Power Fx allows makers to read JSON into an Untyped object using the ParseJSON function.
{
"ItemName" : "Widget 1",
"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 .
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:
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.
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.
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.
{
"Version" : 1,
"RootElement" : {
"Parent" : {
"Name" : "This is the parent",
"Child" : {
"Name" : "This is the child"
}
}
}
}
When converting this JSON string to an Untyped object variable named jsonObject , the fields can be
accessed using the dot notation.
If any of the fields in the dot notation expression don't exist, Blank() will be returned.
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.
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.
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.
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.
Set( jsonRecord, Index( orderLines, 2 ) ); // Get the second record in the table
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.
The new typedOrderLines variable is now a fully typed Power Fx table with the following columns and values:
IT EM Q UA N T IT Y
"Widget 1" 3
IT EM Q UA N T IT Y
"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.
We can retrieve one of the items from the array using the Index() function, and convert it to text.
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.
Most formulas in Microsoft Power Fx calculate a value. Like an Excel spreadsheet, recalculation happens
automatically as values change. For example, you might want to show the value in a Label control in red if the
value is less than zero or in black otherwise. So you can set the Color property of that control to this formula:
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:
Change the screen that's displayed: Back functions.
Control a signal (Power Apps only): Enable and Disable functions.
Refresh, update, or remove items in a data source: Refresh , Update , UpdateIf , Patch , Remove , RemoveIf
functions.
Update a context variable (Power Apps canvas only): UpdateContext function.
Create, update, or remove items in a collection: Collect , Clear , ClearCollect functions.
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.
More than one action
Use semicolons to create a list of actions to perform. For example, you might want to update a context variable
and then return to the previous screen:
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.
Operators and Identifiers
11/19/2022 • 12 minutes to read • Edit Online
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.
* 2*3 Multiplication
& String concatenation "hello" & " " & "world" Makes multiple strings
operator appear continuous
&& or And Logical operators Price < 100 && Logical conjunction,
Slider1.Value = 20 equivalent to the And
or Price < 100 And function
Slider1.Value = 20
ThisRecord ForAll, Filter , With , Sum and other The default name for the current
record scope functions record in ForAll and other record
scope functions.
ThisItem operator
For example, in the following Galler y control, the Items property is set to the Employees data source (such as
the Employees entity included with the Northwind Traders sample):
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:
ThisItem.Picture
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:
ThisRecord is optional and implied by using the fields directly, for example, in this case, we could have written:
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:
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:
Employees As Employee
The formulas for the picture and name are adjusted to use this name for the current record:
Employee.Picture
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:
With( { InactiveEmployees: Filter( Employees, Status = 'Status (Employees)'.Inactive ) },
ForAll( InactiveEmployees As Employee,
Patch( Employees, Employee, { Status: 'Status (Employees)'.Active } ) ) )
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:
Concat(
ForAll( Sequence(8) As Rank,
Concat(
ForAll( Sequence(8) As File,
If( Mod(Rank.Value + File.Value, 2) = 1, " X ", " . " )
),
Value
) & Char(10)
),
Value
)
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:
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:
M ET H O D DESC RIP T IO N
Parent operator Some controls host other controls, such as the Screen and
Galler y controls. The 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.
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
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.
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).
For more information and examples, see record scopes.
Tables
11/19/2022 • 12 minutes to read • Edit Online
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.
A record contains one or more categories of information about a person, a place, or a thing. For example, a
record might contain the name, the email address, and the phone number of a single customer. Other tools
refer to a record as a "row" or an "item."
A table holds one or more records that contain the same categories of information. For example, a table
might contain the names, the email addresses, and the phone numbers of 50 customers.
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:
to update a record in a table by specifying that table as one of multiple arguments for the Patch function
to add, remove, and rename columns in a table by specifying that table as an argument for the
AddColumns , DropColumns , or RenameColumns function. None of those functions modifies the original
table. Instead, the function returns another table based on the other arguments that you specify.
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
The column's name reflects the fields in that column.
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.
You may have referred to columns as "fields" in other tools.
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:
Table( { Value: "Strawberry" }, { Value: "Vanilla" } )
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.
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:
AddColumns - Formula provides the value of the added field.
Average , Max , Min , Sum , StdevP , VarP - Formula provides the value to aggregate.
Filter , Lookup - Formula determines if the record should be included in the output.
Concat - Formula determines the strings to concatenate together.
Distinct - Formula returns a value, used to identify duplicate records.
ForAll - Formula can return any value, potentially with side effects.
Sor t - Formula provides the value to sort the records on.
With - Formula can return any value, potentially with side effects.
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.
For example, take a table of Products placed in a global variable:
Set( Products,
Table(
{ Product: "Widget", 'Quantity Requested': 6, 'Quantity Available': 3 },
{ Product: "Gadget", 'Quantity Requested': 10, 'Quantity Available': 20 },
{ Product: "Gizmo", 'Quantity Requested': 4, 'Quantity Available': 11 },
{ Product: "Apparatus", 'Quantity Requested': 7, 'Quantity Available': 6 }
)
)
To determine whether any of any of these products had more requested than is available:
Filter( Products, 'Quantity Requested' > 'Quantity Available' )
The first argument to Filter is the table of records to operate on, and the second argument is a formula. Filter
creates a record scope for evaluating this formula in which the fields of each record are available, in this case
Product , Quantity Requested , and Quantity Available . The result of the comparison determines if each
record should be included in the result of the function:
Adding to this example, we can calculate how much of each product to order:
AddColumns(
Filter( Products, 'Quantity Requested' > 'Quantity Available' ),
"Quantity To Order", 'Quantity Requested' - 'Quantity Available'
)
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:
ShowColumns(
AddColumns(
Filter( Products, 'Quantity Requested' > 'Quantity Available' ),
"Quantity To Order", 'Quantity Requested' - 'Quantity Available'
),
"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.
For example, imagine having a collection X :
Ungroup(
ForAll( X,
ForAll( Y,
Y[@Value] & Text( X[@Value] ) & [@Value]
)
),
"Value"
)
Ungroup(
ForAll( X,
ForAll( Y,
Value & Text( X[@Value] ) & [@Value]
)
),
"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:
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 .
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:
{ Name: "Chocolate", Price: 3.95, 'Quantity on Hand': 12, 'Quantity on Order': 10 }
You can also embed formulas within other formulas, as this example shows:
{ Name: First(Products).Name, Price: First(Products).Price * 1.095 }
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:
Table(
{ Name: "Chocolate", Price: 3.95, 'Quantity on Hand': 12, 'Quantity on Order': 10 },
{ Name: "Bread", Price: 4.95, 'Quantity on Hand': 34, 'Quantity on Order': 0 },
{ Name: "Water", Price: 4.95, 'Quantity on Hand': 10, 'Quantity on Order': 0 }
)
Table(
{ Name: "Chocolate",
'Quantity History': Table( { Quarter: "Q1", OnHand: 10, OnOrder: 10 },
{ Quarter: "Q2", OnHand: 18, OnOrder: 0 } )
}
)
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 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:
If( Value(Label1.Text) < 0, Red, Black )
You can use formulas for a wide variety of scenarios:
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.
The red dot represents the user's finger in the text-input box,
where the user enters 77 .
Our adding machine uses something that doesn't exist in Excel: a button. In this app, you can't use only formulas
to calculate the running total because its value depends on a series of actions that the user takes. Instead, our
running total must be recorded and updated manually. Most programming tools store this information in a
variable.
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?
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 )
5. Add a Label control, and set its Text property to RunningTotal .
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:
F UN C T IO N S T H AT
VA RIA B L ES T Y P E SC O P E DESC RIP T IO N ESTA B L ISH
F UN C T IO N S T H AT
VA RIA B L ES T Y P E SC O P E DESC RIP T IO N ESTA B L ISH
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] .
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:
Navigate( Screen1, None, { RunningTotal: -1000 } )
Hold down the Alt key while you select this button to both show Screen1 and set the context variable
RunningTotal to -1000.
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.
How collections work:
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:
First( VariableName ).Value
Let's recreate our adding machine by using a collection:
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:
Sum( PaperTape, Value )
6. To run the adding machine, press F5 to open Preview, enter numbers in the text-input control, and select
buttons.
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:
Clear( PaperTape ); LoadData( PaperTape, "StoredPaperTape", true )
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:
SaveData( PaperTape, "StoredPaperTape" )
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.
Power Fx formula reference for Power Apps
11/19/2022 • 11 minutes to read • Edit Online
A
Abs – Absolute value of a number.
Acceleration – Reads the acceleration sensor in your device.
Acos – Returns the arccosine of a number, in radians.
Acot – Returns the arccotangent of a number, in radians.
AddColumns – Returns a table with columns added.
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.
Asin – Returns the arcsine of a number, in radians.
Asser t – Evaluates to true or false in a test.
As – Names the current record in gallery, form, and record scope functions such as ForAll , With , and Sum .
AsType – Treats a record reference as a specific table type.
Atan – Returns the arctangent of a number, in radians.
Atan2 – Returns the arctangent based on an (x,y) coordinate, in radians.
Average – Calculates the average of a table expression or a set of arguments.
B
Back – Displays the previous screen.
Blank – Returns a blank value that can be used to insert a NULL value in a data source.
Boolean – Converts a text string, number, or untyped value to a Boolean value.
C
Calendar – Retrieves information about the calendar for the current locale.
Char – Translates a character code into a string.
Choices – Returns a table of the possible values for a lookup column.
Clear – Deletes all data from a collection.
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.
Coalesce – Replaces blank values while leaving non-blank values unchanged.
Collect – Creates a collection or adds data to a data source.
Color – Sets a property to a built-in color value.
ColorFade – Fades a color value.
ColorValue – Translates a CSS color name or a hex code to a color value.
Compass – Returns your compass heading.
Concat – Concatenates strings in a data source.
Concatenate – Concatenates strings.
Concurrent – Evaluates multiple formulas concurrently with one another.
Connection – Returns information about your network connection.
Count – Counts table records that contain numbers.
Cos – Returns the cosine of an angle specified in radians.
Cot – Returns the cotangent of an angle specified in radians.
CountA – Counts table records that aren't empty.
CountIf – Counts table records that satisfy a condition.
CountRows – Counts table records.
D
DataSourceInfo – Provides information about a data source.
Date – Returns a date/time value, based on Year , Month , and Day values.
DateAdd – Adds days, months, quarters, or years to a date/time value.
DateDiff – Subtracts two date values, and shows the result in days, months, quarters, or years.
DateTimeValue – Converts a date and time string to a date/time value.
DateValue – Converts a date-only string to a date/time value.
Day – Retrieves the day portion of a date/time value.
Defaults – Returns the default values for a data source.
Degrees - Converts radians to degrees.
Disable – Disables a signal, such as Location for reading the GPS.
Distinct – Summarizes records of a table, removing duplicates.
Download – Downloads a file from the web to the local device.
DropColumns – Returns a table with one or more columns removed.
E
EditForm – Resets a form control for editing of an item.
Enable – Enables a signal, such as Location for reading the GPS.
EncodeUrl – Encodes special characters using URL encoding.
EndsWith – Checks whether a text string ends with another text string.
Error – Create a custom error or pass throguh an error.
Errors – Provides error information for previous changes to a data source.
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.
Exp - Returns e raised to a power.
F
Filter – Returns a filtered table based on one or more criteria.
Find – Checks whether one string appears within another and returns the location.
First – Returns the first record of a table.
FirstN – Returns the first set of records (N records) of a table.
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.
Hour – Returns the hour portion of a date/time value.
I
If – Returns one value if a condition is true and another value if not.
IfError - Detects errors and provides an alternative value or takes action.
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.
Index – Returns a record from a table based on ordered position.
Int – Rounds down to the nearest integer.
IsBlank – Checks for a blank value.
IsBlankOrError – Checks for a blank value or error.
IsEmpty – Checks for an empty table.
IsError – Checks for an error.
IsMatch – Checks a string against a pattern. Regular expressions can be used.
IsNumeric – Checks for a numeric value.
ISOWeekNum – Returns the ISO week number of a date/time value.
IsToday – Checks whether a date/time value is sometime today in the user's time zone.
IsType – Checks whether a record reference refers to a specific table type.
IsUTCToday – Checks whether a date/time value is sometime today in Coordinated Universal Time (UTC).
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.
Last – Returns the last record of a table.
LastN – Returns the last set of records (N records) of a table.
Launch – Launches a webpage or a canvas app.
Left – Returns the left-most portion of a string.
Len – Returns the length of a string.
Ln – Returns the natural log.
LoadData – Loads a collection from an app host such as a local device.
Location – Returns your location as a map coordinate by using the Global Positioning System (GPS) and other
information.
Log – Returns the logarithm in any base of a number.
LookUp – Looks up a single record in a table based on one or more criteria.
Lower – Converts letters in a string of text to all lowercase.
M
Match – Extracts a substring based on a pattern. Regular expressions can be used.
MatchAll – Extracts multiple substrings based on a pattern. Regular expressions can be used.
Max – Maximum value of a table expression or a set of arguments.
Mid – Returns the middle portion of a string.
Min – Minimum value of a table expression or a set of arguments.
Minute – Retrieves the minute portion of a date/time value.
Mod – Returns the remainder after a dividend is divided by a divisor.
Month – Retrieves the month portion of a date/time value.
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.
Notify – Displays a banner message to the user.
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.
Parent – Provides access to a container control's properties.
ParseJSON – Converts JSON document represented as text to an Untyped object value.
Patch – Modifies or creates a record in a data source, or merges records outside of a data source.
Pi – Returns the number π.
PlainText – Removes HTML and XML tags from a string.
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.
Rand – Returns a pseudo-random number between 0 and 1.
RandBetween – Returns a pseudo-random number between two numbers.
ReadNFC – Reads a Near Field Communication (NFC) tag.
RecordInfo – Provides information about a record of a data source.
Refresh – Refreshes the records of a data source.
Relate – Relates records of two tables through a one-to-many or many-to-many relationship.
Remove – Removes one or more specific records from a data source.
RemoveIf – Removes records from a data source based on a condition.
RenameColumns – Renames columns of a table.
Replace – Replaces part of a string with another string, by starting position of the string.
RequestHide – Hides a SharePoint form.
Reset – Resets an input control to its default value, discarding any user changes.
ResetForm – Resets a form control for editing of an existing item.
Rever t – 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.
Right – Returns the right-most portion of a string.
Round – Rounds to the closest number.
RoundDown – Rounds down to the largest previous number.
RoundUp – Rounds up to the smallest next number.
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.
Second – Retrieves the second portion of a date/time value.
Select – Simulates a select action on a control, causing the OnSelect formula to be evaluated.
Self – Provides access to the properties of the current control.
Sequence – Generate a table of sequential numbers, useful when iterating with ForAll .
Set – Sets the value of a global variable.
SetFocus – Moves input focus to a specific control.
SetProper ty – Simulates interactions with input controls.
ShowColumns – Returns a table with only selected columns.
Shuffle – Randomly reorders the records of a table.
Sin – Returns the sine of an angle specified in radians.
Sor t – Returns a sorted table based on a formula.
Sor tByColumns – Returns a sorted table based on one or more columns.
Split – Splits a text string into a table of substrings.
Sqr t – Returns the square root of a number.
Star tsWith – Checks if a text string begins with another text string.
StdevP – Returns the standard deviation of its arguments.
Substitute – Replaces part of a string with another string, by matching strings.
SubmitForm – Saves the item in a form control to the data source.
Sum – Calculates the sum of a table expression or a set of arguments.
Switch – Matches with a set of values and then evaluates a corresponding formula.
T
Table – Creates a temporary table.
Tan - Returns the tangent of an angle specified in radians.
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.
TimeValue – Converts a time-only string to a date/time value.
TimeZoneOffset – Returns the difference between UTC and the user's local time in minutes.
Today – Returns the current date-only value.
Trace - Provide additional information in your test results.
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.
Unrelate – Unrelates records of two tables from a one-to-many or many-to-many relationship.
Update – Replaces a record in a data source.
UpdateContext – Sets the value of one or more context variables of the current screen.
UpdateIf – Modifies a set of records in a data source based on a condition.
Upper – Converts letters in a string of text to all uppercase.
User – Returns information about the current user.
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.
Value – Converts a string to a number.
VarP – Returns the variance of its arguments.
ViewForm – Resets a form control for viewing of an existing item.
W
Weekday – Retrieves the weekday portion of a date/time value.
WeekNum – Returns the week number of a date/time value.
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
11/19/2022 • 2 minutes to read • Edit Online
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 Ln function returns the natural logarithm (base e) of its argument.
The Power function returns a number raised to a power. It is 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 Sqr t 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, 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. This can happen, for example, with
square roots and logarithms of negative numbers.
Syntax
Abs ( Number )
Exp ( Number )
Ln ( Number )
Sqr t ( Number )
Number - Required. Number to operate on.
Power ( Base, Exponent )
Base - Required. Base number to raise.
Exponent - Required. The exponent to which the base number is raised.
Log ( Number, Base )
Number - Required. Number to calculate the logarithm.
Base - Optional. The base of the logarithm to calculate. By default, 10 (when not specified).
Abs ( SingleColumnTable )
Exp ( SingleColumnTable )
Ln ( SingleColumnTable )
Sqr t ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of numbers to operate on.
Examples
Single number
F O RM UL A DESC RIP T IO N RESULT
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:
Sqr t( Value( Source.Text ) )
3. Type a number into Source , and confirm that the Label control shows the square root of the number that
you typed.
Acceleration, App, Compass, Connection, and
Location signals in Power Apps
11/19/2022 • 4 minutes to read • Edit Online
Returns information about the app's environment, such as where the user is located in the world and which
screen is displayed.
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).
App
Among other properties, the App object includes a signal that indicates which screen is showing.
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.
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.
As the location changes, dependencies on the location will continuously recalculate, which will consume power
from the device's battery. To conserve battery life, you can use the Enable and Disable functions to turn
location updates on and off. Location is automatically turned off if the displayed screen doesn't depend on
location information.
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 8.2, while the pitcher throws the
front to back. The pitcher initially gives device.
the device a large acceleration when
throwing the device, going from 0 to 0, while the device is in the air.
90 miles per hour (132 feet per
second) in half a second. After the -8.2, as the catcher catches the device.
device is in the air, ignoring air friction,
the device doesn't accelerate further.
The device decelerates when the
catcher catches it, bringing it to a stop.
Acceleration.Z Returns the acceleration of the device 0, before the pitcher throws the device.
top to bottom. While in the air, the
device experiences the effects of 1, while the device is in the air.
gravity.
0, after the catcher catches 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.
The Pi function returns the transcendental number π, which begins 3.141592...
The Radians function converts degrees to radians.
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, 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 )
Radians - Required. Angle to operate on.
Cos ( SingleColumnTable )
Cot ( SingleColumnTable )
Sin ( SingleColumnTable )
Tan ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of angles to operate on.
Inverse Functions
Acos ( Number )
Acot ( Number )
Asin ( Number )
Atan ( Number )
Number - Required. Number to operate on.
Acos ( SingleColumnTable )
Acot ( SingleColumnTable )
Asin ( SingleColumnTable )
Atan ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of numbers to operate on.
Atan2 ( X, Y )
X - Required. X-axis coordinate.
Y - Required. Y-axis coordinate.
Helper Functions
Degrees ( Radians )
Radians - Required. Angle in radians to convert to degrees.
Pi ()
Radians ( Degrees )
Degrees - Required. Angle in degrees to convert to radians.
Examples
Single number
F O RM UL A DESC RIP T IO N RESULT
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.
The Pi function returns the transcendental number π, which begins 3.141592...
The Radians function converts degrees to radians.
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, 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 )
Radians - Required. Angle to operate on.
Cos ( SingleColumnTable )
Cot ( SingleColumnTable )
Sin ( SingleColumnTable )
Tan ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of angles to operate on.
Inverse Functions
Acos ( Number )
Acot ( Number )
Asin ( Number )
Atan ( Number )
Number - Required. Number to operate on.
Acos ( SingleColumnTable )
Acot ( SingleColumnTable )
Asin ( SingleColumnTable )
Atan ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of numbers to operate on.
Atan2 ( X, Y )
X - Required. X-axis coordinate.
Y - Required. Y-axis coordinate.
Helper Functions
Degrees ( Radians )
Radians - Required. Angle in radians to convert to degrees.
Pi ()
Radians ( Degrees )
Degrees - Required. Angle in degrees to convert to radians.
Examples
Single number
F O RM UL A DESC RIP T IO N RESULT
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.
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 formula is evaluated for each record of the table.
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 DropColumns function excludes columns from a table. All other columns remain unmodified.
DropColumns excludes columns, and ShowColumns includes columns.
Use the RenameColumns function to rename one or more columns of a table by providing at least one
argument pair that specifies the name of a column that the table contains (the old name, which you want to
replace) and the name of a column that the table doesn't contain (the new name, which you want to use). The
old name must already exist in the table, and the new name must not exist. Each column name may appear only
once in the argument list as either an old column name or a new column name. To rename a column to an
existing column name, first drop the existing column with DropColumns , or rename the existing column out of
the way by nesting one RenameColumns function within another.
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:
AddColumns( RealEstateAgents,
"Listings",
Filter( '[dbo].[AllListings]', ListingAgentName = AgentName )
)
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 OnStar t 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, ... ] )
Table - Required. Table to operate on.
ColumnName(s) - Required. Name(s) of the column(s) to add. You must specify a string (for example,
"Name" with double quotes included) for this argument.
Formula(s) - Required. Formula(s) to evaluate for each record. The result is added as the value of the
corresponding new column. You can reference other columns of the table in this formula.
DropColumns ( Table, ColumnName1 [, ColumnName2, ... ] )
Table - Required. Table to operate on.
ColumnName(s) - Required. Name(s) of the column(s) to drop. You must specify a string (for example,
"Name" with double quotes included) for this argument.
RenameColumns ( Table, OldColumnName1, NewColumnName1 [, OldColumnName2, NewColumnName2, ... ]
)
Table - Required. Table to operate on.
OldColumnName - Required. Name of a column to rename from the original table. This element appears first
in the argument pair (or first in each argument pair if the formula includes more than one pair). This name
must be a string (for example "Name" with double quotation marks included).
NewColumnName - Required. Replacement name. This element appears last in the argument pair (or last in
each argument pair if the formula includes more than one pair). You must specify a string (for example,
"Customer Name" with double quotation marks included) for this argument.
ShowColumns ( Table, ColumnName1 [, ColumnName2, ... ] )
Table - Required. Table to operate on.
ColumnName(s) - Required. Name(s) of the column(s) to include. You must specify a string (for example,
"Name" with double quotes included) for this argument.
Examples
The examples in this section use the IceCreamSales data source, which contains the data in this table:
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.
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:
ClearCollect( IceCreamSales,
Table(
{ Flavor: "Strawberry", UnitPrice: 1.99, QuantitySold: 20 },
{ Flavor: "Chocolate", UnitPrice: 2.99, QuantitySold: 45 },
{ Flavor: "Vanilla", UnitPrice: 1.50, QuantitySold: 35 }
)
)
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:
ClearCollect( FirstExample,
AddColumns( IceCreamSales, "Revenue", UnitPrice * QuantitySold )
)
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
11/19/2022 • 2 minutes to read • Edit Online
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 Or function returns true if any 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, ... ] )
Or ( LogicalFormula1, LogicalFormula2 [, LogicalFormula3, ... ] )
Not ( LogicalFormula )
LogicalFormula(s) - Required. Logical formulas to evaluate and operate on.
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:
Set( a, false ); Set( b, true ); Set( x, 10 ); Set( y, 100 ); Set( s, "Hello World" )
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.
Len( s ) < 20 And Not IsBlank( s ) Tests whether the length of s is less true
than 20 and whether it isn't a blank
value. The length is less than 20, and
the value isn't blank. Therefore, the
result is true.
Or( Len( s ) < 10, x < 100, Tests whether the length of s is less true
y < 100 ) than 10, whether x is less than 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.
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.
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:
Running the Exit function.
If the app is running in a browser:
Closing the browser or the browser tab in which the app is running.
Selecting the browser's back button.
Running the Launch function with a LaunchTarget of Self .
If the app is running in Power Apps Mobile (iOS or Android):
Swiping to switch to a different app in Power Apps Mobile.
Selecting the back button on an Android device.
Running the Launch function to launch another canvas app.
The exact look of the confirmation dialog box might vary across devices and versions of Power Apps.
The confirmation dialog box doesn't appear in Power Apps Studio.
ConfirmExitMessage
By default, the confirmation dialog box shows a generic message, such as "You may have unsaved changes."
in the user's language.
Use ConfirmExitMessage to provide a custom message in the confirmation dialog box. If this property is
blank, the default value is used. Custom messages are truncated as necessary to fit within the confirmation
dialog box, so keep the message to a few lines at most.
In a browser, the confirmation dialog box might appear with a generic message from the browser.
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 .
2. Set the App object's ConfirmExit property to this expression:
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.
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
NOTE
Formulas is an experimental feature and is subject to change. More information: Understand experimental, preview,
and deprecated features in Power Apps.
The behavior that this article describes is available only when the Named formulas experimental feature in Settings >
Upcoming features > Experimental is turned on (off by default).
Your feedback is very valuable to us - please let us know what you think in the Power Apps experimental features
community forums.
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:
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 OnStar t to set the color once, and then reuse the
value throughout the app:
While this method is better, it also depends on OnStar t 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.
Named formulas provide an alternative. Just as we commonly write control-property = expression, we can
instead write name = expression and then reuse name throughout our app to replace expression. The definitions
of these formulas are done in the Formulas property:
App.Formulas: BGColor = ColorValue( Param( "BackgroundColor" ) );
Label1.Fill: BGColor
Label2.Fill: BGColor
Label3.Fill: BGColor
UserEmail = User().Email;
UserInfo = LookUp( Users, 'Primary Email' = User().Email );
UserTitle = UserInfo.Title;
UserPhone = Switch( UserInfo.'Preferred Phone',
'Preferred Phone (Users)'.'Mobile Phone', UserInfo.'Mobile Phone',
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.
Some limitations of named formulas:
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
NOTE
OnError is part of an experimental feature and is subject to change. More information: Understand experimental,
preview, and deprecated features in Power Apps.
The behavior that this article describes is available only when the Formula-level error management experimental
feature in Settings > Upcoming features > Experimental is turned on (off by default).
Your feedback is very valuable to us - please let us know what you think in the Power Apps community forums.
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:
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:
Let's look at what happened in detail:
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.
If necessary, we could also modify the formula to Label1.Text = IfError( 1/Slider1.Value, 0 ) . This would
result in no error or error banner. We can't change the 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:
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:
Trace( $"Error {FirstError.Message} in {FirstError.Source}" );
Error( FirstError )
OnStart property
NOTE
The use of OnStar t 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 OnStar t 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 OnStar t property, test it by hovering over the App object in the Tree view pane, selecting
ellipsis (...), and then selecting Run OnStar t . 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.
NOTE
Using the Navigate function in the OnStar t 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 OnStar t before displaying the
first screen. Use the Star tScreen 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 OnStar t
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
NOTE
Star tScreen 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 Star tScreen property.
The Star tScreen 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.
Star tScreen 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:
Param function to read parameters used to start the app.
User function to read information about the current user.
LookUp , Filter , CountRows , Max , and other functions that read from a data source.
Any API calls through a connector, but be careful that it returns quickly.
Signals such as Connection , Compass , and App .
NOTE
Global variables and collections, including those created in OnStar t , are not available in Star tScreen . 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 Star tScreen returns an error, the first screen in the Studio Tree view will be shown as if Star tScreen hadn't
been set. Use the IfError function to catch any errors and redirect to an appropriate error screen.
After changing Star tScreen in Studio, test it by hovering over the App object in the Tree view pane, selecting
the ellipsis (...), and then selecting Navigate to Star tScreen . The screen will change as if the app has been
loaded.
Examples
Screen9
Indicates that Screen9 should be shown first whenever the app starts.
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.
Checks if an attendee to a conference is a staff member and directs them to the proper screen on startup.
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
11/19/2022 • 12 minutes to read • Edit Online
Some of these operators are dependent on the language of the author. For more information about language
support in canvas apps, see Global apps.
* 2*3 Multiplication
& String concatenation "hello" & " " & "world" Makes multiple strings
operator appear continuous
&& or And Logical operators Price < 100 && Logical conjunction,
Slider1.Value = 20 equivalent to the And
or Price < 100 And function
Slider1.Value = 20
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')
ThisRecord ForAll, Filter , With , Sum and other The default name for the current
record scope functions record in ForAll and other record
scope functions.
ThisItem operator
For example, in the following Galler y control, the Items property is set to the Employees data source (such as
the Employees table included with the Northwind Traders sample):
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:
ThisItem.Picture
Likewise, the formula for the name also uses ThisItem :
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:
ThisRecord is optional and implied by using the fields directly, for example, in this case, we could have written:
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:
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:
Employees As Employee
The formulas for the picture and name are adjusted to use this name for the current record:
Employee.Picture
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:
Concat(
ForAll( Sequence(8) As Rank,
Concat(
ForAll( Sequence(8) As File,
If( Mod(Rank.Value + File.Value, 2) = 1, " X ", " . " )
),
Value
) & Char(10)
),
Value
)
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:
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:
M ET H O D DESC RIP T IO N
M ET H O D DESC RIP T IO N
Parent operator Some controls host other controls, such as the Screen and
Galler y controls. The 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.
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
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 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.
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).
For more information and examples, see record scopes.
Acos, Acot, Asin, Atan, Atan2, Cos, Cot, Degrees, Pi,
Radians, Sin, and Tan functions in Power Apps
11/19/2022 • 4 minutes to read • Edit Online
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.
The Pi function returns the transcendental number π, which begins 3.141592...
The Radians function converts degrees to radians.
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, 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 )
Radians - Required. Angle to operate on.
Cos ( SingleColumnTable )
Cot ( SingleColumnTable )
Sin ( SingleColumnTable )
Tan ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of angles to operate on.
Inverse Functions
Acos ( Number )
Acot ( Number )
Asin ( Number )
Atan ( Number )
Number - Required. Number to operate on.
Acos ( SingleColumnTable )
Acot ( SingleColumnTable )
Asin ( SingleColumnTable )
Atan ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of numbers to operate on.
Atan2 ( X, Y )
X - Required. X-axis coordinate.
Y - Required. Y-axis coordinate.
Helper Functions
Degrees ( Radians )
Radians - Required. Angle in radians to convert to degrees.
Pi ()
Radians ( Degrees )
Degrees - Required. Angle in degrees to convert to radians.
Examples
Single number
F O RM UL A DESC RIP T IO N RESULT
An assertion is a condition or an expression that evaluates to true or false in a test. If the expression returns
false, the test case will fail. Assertions are used to validate the expected result of a test or test step, against the
actual result and to fail the test if the condition is false. Assertions can be used to validate the state of controls in
your app such as label values, list box selections and other control properties.
Assertion messages, for both passed and failed assertions, are also contained in a Traces table in the
TestCaseResult record.
Syntax
Assert(expression, message)
Expression – Required. An expression that evaluates to true or false.
Message – Not Required. A message that describes the assertion failure.
Examples
Assert(lblResult.Text = "Success", "lblResult value Expected : Success , Actual : " & lblResult.Text)
Assert(ListBox1.Selected.Value = "Success", "ListBox1 selection Expected : Success, Actual : " &
ListBox1.Selected.Value)
Assert(kudosAfterTest = kudosBeforeTest + 1, "Kudos count. Expected : " & kudosBeforeTest + 1 & " Actual :" &
kudosAfterTest)
See Also
Test Studio Overview
Working with Test Studio
AsType and IsType functions in Power Apps
11/19/2022 • 4 minutes to read • Edit Online
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 ).'Primar y
Contact'.'Full Name' walks from the Accounts table to the Primar y 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.
LO O K UP F IEL D C A N REF ER TO
In canvas-app formulas, use record references to work with polymorphic lookups. Because a record reference
can refer to different tables, you don't know which fields will be available when you write a formula. The
Record.Field notation isn't available. Those formulas must adapt to the records that the app encounters when it
runs.
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:
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 :
Similarly, you can use record references with the Patch function:
Patch( Accounts, First( Accounts ), { Owner: First( Teams ) } )
If used in a record context, such as within a Galler y 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:
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.
IsType ( 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 for which to test.
Example
Understand record references and polymorphic lookups contains extensive examples.
1. Create a blank canvas app for tablets.
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 ver tical galler y .
4. Select Connect to data , and then select Contacts as the data source.
5. Set the gallery's layout to Title and subtitle .
6. In the Data pane, open the Title1 list, and then select Full Name .
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.
The Pi function returns the transcendental number π, which begins 3.141592...
The Radians function converts degrees to radians.
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, 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 )
Radians - Required. Angle to operate on.
Cos ( SingleColumnTable )
Cot ( SingleColumnTable )
Sin ( SingleColumnTable )
Tan ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of angles to operate on.
Inverse Functions
Acos ( Number )
Acot ( Number )
Asin ( Number )
Atan ( Number )
Number - Required. Number to operate on.
Acos ( SingleColumnTable )
Acot ( SingleColumnTable )
Asin ( SingleColumnTable )
Atan ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of numbers to operate on.
Atan2 ( X, Y )
X - Required. X-axis coordinate.
Y - Required. Y-axis coordinate.
Helper Functions
Degrees ( Radians )
Radians - Required. Angle in radians to convert to degrees.
Pi ()
Radians ( Degrees )
Degrees - Required. Angle in degrees to convert to radians.
Examples
Single number
F O RM UL A DESC RIP T IO N RESULT
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.
The Pi function returns the transcendental number π, which begins 3.141592...
The Radians function converts degrees to radians.
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, 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 )
Radians - Required. Angle to operate on.
Cos ( SingleColumnTable )
Cot ( SingleColumnTable )
Sin ( SingleColumnTable )
Tan ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of angles to operate on.
Inverse Functions
Acos ( Number )
Acot ( Number )
Asin ( Number )
Atan ( Number )
Number - Required. Number to operate on.
Acos ( SingleColumnTable )
Acot ( SingleColumnTable )
Asin ( SingleColumnTable )
Atan ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of numbers to operate on.
Atan2 ( X, Y )
X - Required. X-axis coordinate.
Y - Required. Y-axis coordinate.
Helper Functions
Degrees ( Radians )
Radians - Required. Angle in radians to convert to degrees.
Pi ()
Radians ( Degrees )
Degrees - Required. Angle in degrees to convert to radians.
Examples
Single number
F O RM UL A DESC RIP T IO N RESULT
Description
The Average function calculates the average, or arithmetic mean, of its arguments.
The Max function finds the maximum value.
The Min function finds the minimum value.
The Sum function calculates the sum of its arguments.
The StdevP function calculates the standard deviation of its arguments.
The VarP function calculates the variance of its arguments.
You can supply the values for these functions as:
Separate arguments. For example, Sum( 1, 2, 3 ) returns 6.
A table and a formula to operate over that table. The aggregate will be calculated on the values of the
formula for each 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.
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, ... ] )
Max ( NumericalFormula1, [ NumericalFormula2, ... ] )
Min ( NumericalFormula1, [ NumericalFormula2, ... ] )
Sum ( NumericalFormula1, [ NumericalFormula2, ... ] )
StdevP ( NumericalFormula1, [ NumericalFormula2, ... ] )
VarP ( NumericalFormula1, [ NumericalFormula2, ... ] )
NumericalFormula(s) - Required. Numeric values to operate on.
Average ( Table, NumericalFormula )
Max ( Table, NumericalFormula )
Min ( Table, NumericalFormula )
Sum ( Table, NumericalFormula )
StdevP ( Table, NumericalFormula )
VarP ( Table, NumericalFormula )
Table - Required. Table to operate on.
NumericalFormula - Required. Formula to evaluate for each record. The result of this formula is used for the
aggregation. You can use columns of the table in the formula.
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:
Sum(Sales, CostPerUnit * UnitsSold)
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.
Average(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the average of all values to
which the sliders were set.
Max(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the maximum of all values to
which the sliders were set.
Min(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the minimum of all values to which
the sliders were set.
StdevP(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the standard deviation of all
values to which the sliders were set.
VarP(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the variance of all values to which
the sliders were set.
Back and Navigate functions in Power Apps
11/19/2022 • 5 minutes to read • Edit Online
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 Star tScreen property to control the first screen to be displayed.
You can use either function only within a behavior formula.
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.
Navigate ( Screen [, Transition [, UpdateContextRecord ] ] )
Screen - Required. The screen to display.
Transition - Optional. The visual transition to use between the current screen and the next screen. See the list
of valid values for this argument earlier in this article. The default value is None .
UpdateContextRecord - Optional. A record that contains the name of at least one column and a value for each
column. This record updates the context variables of the new screen as if passed to the UpdateContext
function.
Examples
F O RM UL A DESC RIP T IO N RESULT
Navigate( Details ) Displays the Details screen with no The Details screen appears quickly.
transition or change in value for a
context variable.
Navigate( Details, Displays the Details screen with a The current screen fades away to show
ScreenTransition.Fade ) Fade transition. No value of a context the Details screen.
variable is changed.
Navigate( Details, Displays the Details screen with a The current screen fades away to show
ScreenTransition.Fade, { ID: 12 } ) Fade transition, and updates the value the Details screen, and the context
of the ID context variable to 12 . variable ID on that screen is set to 12 .
Navigate( Details, Displays the Details screen with a The current screen fades away to show
ScreenTransition.Fade, Fade transition. Updates the value of the Details screen. The context
{ ID: 12 , Shade: Color.Red } ) the ID context variable to 12 , and variable ID on the Details screen is
updates the value of the Shade set to 12 , and the context variable
context variable to Color.Red . Shade is set to Color.Red . If you set
the Fill property of a control on the
Details screen to Shade , that control
would display as red.
Back() Displays the previous screen with the Displays the previous screen through
default return transition. the inverse transition of the transition
through which the current screen
appeared.
Back( ScreenTransition.Cover ) Displays the previous screen with the Displays the previous screen through
Cover transition. the Cover transition, regardless of the
transition through which the current
screen appeared.
Step-by-step
1. Create a blank app.
2. Add a second screen to it.
The app contains two blank screens: Screen1 and Screen2 .
3. Set the Fill property of Screen2 to the value Gray .
4. On Screen2 , add a button, and set its OnSelect property to this formula:
Back()
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.
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 .
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 .
The return value for IsBlank is a boolean true or false .
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.
The return value for IsEmpty is a Boolean true or false .
Syntax
Blank ()
Coalesce ( Value1 [, Value2, ... ] )
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 )
Value – Required. Value to test for a blank value or empty string.
IsEmpty ( Table )
Table - Required. Table to test for records.
Examples
Blank
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.
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:
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
F O RM UL A DESC RIP T IO N RESULT
F O RM UL A DESC RIP T IO N RESULT
IsBlank
1. Create an app from scratch, add a text-input control, and name it FirstName .
2. Add a label, and set its Text property to this formula:
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 true
function, which always returns a blank
value.
IsBlank( Mid( "Hello", 17, 2 ) ) The starting character for Mid is true
beyond the end of the string. The
result is an empty string.
IsEmpty
1. Create an app from scratch, and add a Button control.
2. Set the button's OnSelect property to this formula:
Collect( IceCream, { Flavor : "Strawberr y", Quantity: 300 }, { Flavor : "Chocolate", Quantity:
100 } )
3. Preview your app, click or tap the button that you added, and then close Preview.
A collection named IceCream is created and contains this data:
This collection has two records and isn't empty. IsEmpty( IceCream ) returns false , and CountRows(
IceCream ) returns 2 .
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 collection is now empty:
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:
F O RM UL A DESC RIP T IO N RESULT
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 explicit conversion is desired or when using an untyped value.
Syntax
Boolean ( String )
Boolean ( StringSingleColumnTable )
String - Required. The string(s) to convert. Must be a case insensitive version of "true" or "false" . These
strings aren't localized. blank and empty string is also accepted and converted to a blank. All other text
strings return an error.
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 )
Untyped - Required. The untyped value to convert. Acceptable values are dependent on the untyped provider.
For JSON , JSON boolean values true , false , and null are accepted, corresponding to true, false, and
blank values in Power Fx. All other values will return an error. Values inside of a string, such as "true" and
"false" , aren't accepted.
Examples
Basic usage
Boolean( "Truthful" ) Attempts to convert the text string error (invalid argument)
"Truthful" to a boolean value, but
since it isn't a case insensitive variation
of true and false , an error is
returned.
Untyped usage
F O RM UL A DESC RIP T IO N RESULT
Boolean( ParseJSON( " Attempts to convert the untyped error (invalid argument)
{ ""bool"": "true" }" ).bool ) value "true" (a JSON string) to a
boolean value, but since it isn't a valid
boolean value in JSON, an error is
returned.
Boolean( [ "true", "false", Blank() ] Converts the single column table of [ true, false, blank ]
) text strings to a single column table of
boolean values.
F O RM UL A DESC RIP T IO N RESULT
Boolean( [ "true", "falsified" ] ) Converts the single column table of [ true, error (invalid argument) ]
text strings to a single column table of
boolean values. Since the second
record in this table isn't a case
insensitive variation of true and
false , an error is returned for this
record.
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.
F UN C T IO N DESC RIP T IO N
Clock .AmPmShor t() 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.MonthsShor t ()
Calendar.WeekdaysLong ()
Calendar.WeekdaysShor t ()
Clock .AmPm ()
Clock .AmPmShor t ()
Clock .IsClock24 ()
Examples
1. Insert a Dropdown control.
2. Set the formula for the Items property to:
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 name [ "January", "February", "March",
of each month, starting with "January". "April", "May", "June", "July", "August",
"September", "October", "November",
"December" ]
Calendar.MonthsShor t() The return value contains the [ "Jan", "Feb", "Mar", "Apr", "May",
abbreviated name of each month, "Jun", "Jul", "Aug", "Sep", "Oct", "Nov",
starting with "January". "Dec" ]
Calendar.WeekdaysLong() The return value contains the full name [ "Sunday", "Monday", "Tuesday",
of each day, starting with "Sunday". "Wednesday", "Thursday", "Friday",
"Saturday" ]
Calendar.WeekdaysShor t() The return value contains the [ "Sun", "Mon", "Tue", "Wed", "Thu",
abbreviated name of each day, starting "Fri", "Sat" ]
with "Sunday".
Clock .AmPmShor t() This language uses a 12-hour clock. [ "A", "P" ]
The return value contains the
uppercase versions of the short AM
and PM designations.
Description
The Char function translates a number into a string with the corresponding ASCII character.
Syntax
Char ( CharacterCode )
CharacterCode - Required. ASCII character code to translate.
Examples
F O RM UL A DESC RIP T IO N RESULT
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:
Sequence( 8, 128, 16 ) As HighNibble
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
11/19/2022 • 3 minutes to read • Edit Online
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 , Sor t , 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 SL A , the column reference would be Accounts.SL A . The reference can't pass through a function, a
variable, or a control. Furthering this example, if Accounts is fed to a Galler y control, use the formula
Galler y.Selected.SL A 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.SL A .
At this time, you can use lookup columns only with SharePoint and Microsoft Dataverse.
Syntax
Choices ( column-reference )
column-reference – Required. A lookup column of a data source. Don't enclose the column name in double
quotes. The reference must be directly to the column of the data source and not pass through a function or a
control.
Examples
Choices for a lookup
1. Create a database in Dataverse, and select the Include sample apps and data box.
Many tables, such as Accounts , are created.
Note : Table names are singular on make.powerapps.com and plural in Power Apps Studio.
The Accounts table has a Primar y 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.
2. Generate an app from the Accounts table.
3. In the list of screens and controls near the left edge, scroll down until EditScreen1 appears, and then
select EditForm1 just under it.
4. On the Proper ties tab of the right pane, select Edit fields .
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 .
10. On the Inser t tab, select Data table .
11. Set the Items property of the Data table control to this formula:
Choices( Accounts.'Primar y Contact' )
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
11/19/2022 • 4 minutes to read • Edit Online
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.
If the data source doesn't already exist, a collection is created.
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.
You can use the Remove function to selectively remove records.
Clear has no return value. It can only be used in a behavior formula.
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.
ClearCollect ( Collection, Item, ... )
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
Clearing and adding records to a data source
In these examples, you'll erase and add to a collection that's named IceCream . The data source begins with
these contents:
For step-by-step examples of how to create a collection, see Create and update a collection.
Records and tables
These examples examine how record and table arguments to Collect and ClearCollect are handled.
F O RM UL A DESC RIP T IO N RESULT
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.
If the data source doesn't already exist, a collection is created.
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.
You can use the Remove function to selectively remove records.
Clear has no return value. It can only be used in a behavior formula.
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.
ClearCollect ( Collection, Item, ... )
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
Clearing and adding records to a data source
In these examples, you'll erase and add to a collection that's named IceCream . The data source begins with
these contents:
For step-by-step examples of how to create a collection, see Create and update a collection.
Records and tables
These examples examine how record and table arguments to Collect and ClearCollect are handled.
F O RM UL A DESC RIP T IO N RESULT
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.
F UN C T IO N DESC RIP T IO N
Clock .AmPmShor t() 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.MonthsShor t ()
Calendar.WeekdaysLong ()
Calendar.WeekdaysShor t ()
Clock .AmPm ()
Clock .AmPmShor t ()
Clock .IsClock24 ()
Examples
1. Insert a Dropdown control.
2. Set the formula for the Items property to:
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 name [ "January", "February", "March",
of each month, starting with "January". "April", "May", "June", "July", "August",
"September", "October", "November",
"December" ]
Calendar.MonthsShor t() The return value contains the [ "Jan", "Feb", "Mar", "Apr", "May",
abbreviated name of each month, "Jun", "Jul", "Aug", "Sep", "Oct", "Nov",
starting with "January". "Dec" ]
Calendar.WeekdaysLong() The return value contains the full name [ "Sunday", "Monday", "Tuesday",
of each day, starting with "Sunday". "Wednesday", "Thursday", "Friday",
"Saturday" ]
Calendar.WeekdaysShor t() The return value contains the [ "Sun", "Mon", "Tue", "Wed", "Thu",
abbreviated name of each day, starting "Fri", "Sat" ]
with "Sunday".
Clock .AmPmShor t() This language uses a 12-hour clock. [ "A", "P" ]
The return value contains the
uppercase versions of the short AM
and PM designations.
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.
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 .
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 .
The return value for IsBlank is a boolean true or false .
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.
The return value for IsEmpty is a Boolean true or false .
Syntax
Blank ()
Coalesce ( Value1 [, Value2, ... ] )
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 )
Value – Required. Value to test for a blank value or empty string.
IsEmpty ( Table )
Table - Required. Table to test for records.
Examples
Blank
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.
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:
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
F O RM UL A DESC RIP T IO N RESULT
F O RM UL A DESC RIP T IO N RESULT
IsBlank
1. Create an app from scratch, add a text-input control, and name it FirstName .
2. Add a label, and set its Text property to this formula:
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 true
function, which always returns a blank
value.
IsBlank( Mid( "Hello", 17, 2 ) ) The starting character for Mid is true
beyond the end of the string. The
result is an empty string.
IsEmpty
1. Create an app from scratch, and add a Button control.
2. Set the button's OnSelect property to this formula:
Collect( IceCream, { Flavor : "Strawberr y", Quantity: 300 }, { Flavor : "Chocolate", Quantity:
100 } )
3. Preview your app, click or tap the button that you added, and then close Preview.
A collection named IceCream is created and contains this data:
This collection has two records and isn't empty. IsEmpty( IceCream ) returns false , and CountRows(
IceCream ) returns 2 .
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 collection is now empty:
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:
F O RM UL A DESC RIP T IO N RESULT
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.
If the data source doesn't already exist, a collection is created.
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.
You can use the Remove function to selectively remove records.
Clear has no return value. It can only be used in a behavior formula.
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.
ClearCollect ( Collection, Item, ... )
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
Clearing and adding records to a data source
In these examples, you'll erase and add to a collection that's named IceCream . The data source begins with
these contents:
For step-by-step examples of how to create a collection, see Create and update a collection.
Records and tables
These examples examine how record and table arguments to Collect and ClearCollect are handled.
F O RM UL A DESC RIP T IO N RESULT
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 )
Untyped - Required. An Untyped object containing a string that represents a Cascading Style Sheet (CSS)
color definition.
RGBA ( Red, Green, Blue, Alpha )
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%.
ColorFade ( Color, FadeAmount )
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
C O LO R EN UM ERAT IO N C O LO RVA L UE RGB A C O LO R SWATC H
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 )
Untyped - Required. An Untyped object containing a string that represents a Cascading Style Sheet (CSS)
color definition.
RGBA ( Red, Green, Blue, Alpha )
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%.
ColorFade ( Color, FadeAmount )
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
C O LO R EN UM ERAT IO N C O LO RVA L UE RGB A C O LO R SWATC H
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 )
Untyped - Required. An Untyped object containing a string that represents a Cascading Style Sheet (CSS)
color definition.
RGBA ( Red, Green, Blue, Alpha )
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%.
ColorFade ( Color, FadeAmount )
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
C O LO R EN UM ERAT IO N C O LO RVA L UE RGB A C O LO R SWATC H
Returns information about the app's environment, such as where the user is located in the world and which
screen is displayed.
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).
App
Among other properties, the App object includes a signal that indicates which screen is showing.
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.
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.
As the location changes, dependencies on the location will continuously recalculate, which will consume power
from the device's battery. To conserve battery life, you can use the Enable and Disable functions to turn
location updates on and off. Location is automatically turned off if the displayed screen doesn't depend on
location information.
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 8.2, while the pitcher throws the
front to back. The pitcher initially gives device.
the device a large acceleration when
throwing the device, going from 0 to 0, while the device is in the air.
90 miles per hour (132 feet per
second) in half a second. After the -8.2, as the catcher catches the device.
device is in the air, ignoring air friction,
the device doesn't accelerate further.
The device decelerates when the
catcher catches it, bringing it to a stop.
Acceleration.Z Returns the acceleration of the device 0, before the pitcher throws the device.
top to bottom. While in the air, the
device experiences the effects of 1, while the device is in the air.
gravity.
0, after the catcher catches 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)
Table - Required. Table to operate on.
Formula - Required. Formula to apply across the records of the table.
Separator - Optional. A text value to be inserted between concatenated rows of the table.
Concatenate ( String1 [, String2, ...] )
String(s) - Required. Mix of individual strings or a single-column table of strings.
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:
Set( FirstName, "Jane" ); Set( LastName, "Doe" );
Set( Products,
Table(
{ Name: "Violin", Type: "String" },
{ Name: "Cello", Type: "String" },
{ Name: "Trumpet", Type: "Wind" }
)
)
Select the button (by clicking it while you hold down the Alt key).
Concatenate function and the & operator
For these examples, set the Text property of a Label control to a formula from the first column of the next table.
Concatenate( LastName, ", ", First Concatenates the value in LastName , "Doe, Jane"
Name ) the string ", " (a comma followed by a
space), and the value in FirstName .
LastName & ", " & FirstName Same as the previous example except "Doe, Jane"
using the & operator instead of the
function.
Concatenate( FirstName, " ", Last Concatenates the value in FirstName , "Jane Doe"
Name ) the string " " (a single space), and the
value in LastName .
FirstName & " " & LastName Same as the previous example, using "Jane Doe"
the & operator instead of the function.
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.
F O RM UL A DESC RIP T IO N RESULT
Concat( Evaluates the formula Name & ", " "Violin, Cello, "
Filter( Products, Type = "String" ), for each record of Products that
Name & ", " ) satisfies the filter Type = "String",
and concatenates the results into a
single text string.
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)
Table - Required. Table to operate on.
Formula - Required. Formula to apply across the records of the table.
Separator - Optional. A text value to be inserted between concatenated rows of the table.
Concatenate ( String1 [, String2, ...] )
String(s) - Required. Mix of individual strings or a single-column table of strings.
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:
Set( FirstName, "Jane" ); Set( LastName, "Doe" );
Set( Products,
Table(
{ Name: "Violin", Type: "String" },
{ Name: "Cello", Type: "String" },
{ Name: "Trumpet", Type: "Wind" }
)
)
Select the button (by clicking it while you hold down the Alt key).
Concatenate function and the & operator
For these examples, set the Text property of a Label control to a formula from the first column of the next table.
Concatenate( LastName, ", ", First Concatenates the value in LastName , "Doe, Jane"
Name ) the string ", " (a comma followed by a
space), and the value in FirstName .
LastName & ", " & FirstName Same as the previous example except "Doe, Jane"
using the & operator instead of the
function.
Concatenate( FirstName, " ", Last Concatenates the value in FirstName , "Jane Doe"
Name ) the string " " (a single space), and the
value in LastName .
FirstName & " " & LastName Same as the previous example, using "Jane Doe"
the & operator instead of the function.
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.
F O RM UL A DESC RIP T IO N RESULT
Concat( Evaluates the formula Name & ", " "Violin, Cello, "
Filter( Products, Type = "String" ), for each record of Products that
Name & ", " ) satisfies the filter Type = "String",
and concatenates the results into a
single text string.
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 OnStar t 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.
You can use Concurrent only in behavior formulas.
Syntax
Concurrent ( Formula1, Formula2 [, ...] )
Formula(s) – Required. Formulas to evaluate concurrently. You must supply at least two formulas.
Examples
Loading data faster
1. Create an app, and add four data sources from Microsoft Dataverse, SQL Server, or SharePoint.
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:
3. In Microsoft Edge or Google Chrome, turn on developer tools to monitor network traffic while your app is
running.
4. (optional) Turn on network throttling to exaggerate the effects of this comparison.
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:
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.
8. Clear the network monitor in the browser.
9. If you were using network throttling before, turn it on again.
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:
4. Add a Data table control, and set its Items property to Results .
5. On the Proper ties 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.
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.
Acceleration, App, Compass, Connection, and
Location signals in Power Apps
11/19/2022 • 4 minutes to read • Edit Online
Returns information about the app's environment, such as where the user is located in the world and which
screen is displayed.
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).
App
Among other properties, the App object includes a signal that indicates which screen is showing.
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.
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.
As the location changes, dependencies on the location will continuously recalculate, which will consume power
from the device's battery. To conserve battery life, you can use the Enable and Disable functions to turn
location updates on and off. Location is automatically turned off if the displayed screen doesn't depend on
location information.
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 8.2, while the pitcher throws the
front to back. The pitcher initially gives device.
the device a large acceleration when
throwing the device, going from 0 to 0, while the device is in the air.
90 miles per hour (132 feet per
second) in half a second. After the -8.2, as the catcher catches the device.
device is in the air, ignoring air friction,
the device doesn't accelerate further.
The device decelerates when the
catcher catches it, bringing it to a stop.
Acceleration.Z Returns the acceleration of the device 0, before the pitcher throws the device.
top to bottom. While in the air, the
device experiences the effects of 1, while the device is in the air.
gravity.
0, after the catcher catches 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.
The CountRows function counts the number of records in a table.
Each of these functions returns a number.
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:
1. Open the app where you want to use the functions.
2. Select Settings > Upcoming features > Preview .
3. Turn on the Enhanced delegation for Microsoft Dataverse 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 )
SingleColumnTable - Required. Column of records to count.
CountIf ( Table, LogicalFormula )
Table - Required. Table of records to count.
LogicalFormula - Required. Formula to evaluate for each record of the table. Records that return true for this
formula are counted. The formula can reference columns of the table.
CountRows ( Table )
Table - Required. Table of records to count.
Example
1. Import or create a collection named Inventor y , as the first subprocedure in Show images and text in a
gallery describes.
2. Add a label, and set its Text property to this formula:
CountIf(Inventor y, UnitsInStock < 30)
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(Inventor y.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(Inventor y)
The label shows 5 because the collection contains five rows.
Acos, Acot, Asin, Atan, Atan2, Cos, Cot, Degrees, Pi,
Radians, Sin, and Tan functions in Power Apps
11/19/2022 • 4 minutes to read • Edit Online
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.
The Pi function returns the transcendental number π, which begins 3.141592...
The Radians function converts degrees to radians.
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, 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 )
Radians - Required. Angle to operate on.
Cos ( SingleColumnTable )
Cot ( SingleColumnTable )
Sin ( SingleColumnTable )
Tan ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of angles to operate on.
Inverse Functions
Acos ( Number )
Acot ( Number )
Asin ( Number )
Atan ( Number )
Number - Required. Number to operate on.
Acos ( SingleColumnTable )
Acot ( SingleColumnTable )
Asin ( SingleColumnTable )
Atan ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of numbers to operate on.
Atan2 ( X, Y )
X - Required. X-axis coordinate.
Y - Required. Y-axis coordinate.
Helper Functions
Degrees ( Radians )
Radians - Required. Angle in radians to convert to degrees.
Pi ()
Radians ( Degrees )
Degrees - Required. Angle in degrees to convert to radians.
Examples
Single number
F O RM UL A DESC RIP T IO N RESULT
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.
The Pi function returns the transcendental number π, which begins 3.141592...
The Radians function converts degrees to radians.
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, 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 )
Radians - Required. Angle to operate on.
Cos ( SingleColumnTable )
Cot ( SingleColumnTable )
Sin ( SingleColumnTable )
Tan ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of angles to operate on.
Inverse Functions
Acos ( Number )
Acot ( Number )
Asin ( Number )
Atan ( Number )
Number - Required. Number to operate on.
Acos ( SingleColumnTable )
Acot ( SingleColumnTable )
Asin ( SingleColumnTable )
Atan ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of numbers to operate on.
Atan2 ( X, Y )
X - Required. X-axis coordinate.
Y - Required. Y-axis coordinate.
Helper Functions
Degrees ( Radians )
Radians - Required. Angle in radians to convert to degrees.
Pi ()
Radians ( Degrees )
Degrees - Required. Angle in degrees to convert to radians.
Examples
Single number
F O RM UL A DESC RIP T IO N RESULT
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.
The CountRows function counts the number of records in a table.
Each of these functions returns a number.
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:
1. Open the app where you want to use the functions.
2. Select Settings > Upcoming features > Preview .
3. Turn on the Enhanced delegation for Microsoft Dataverse 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 )
SingleColumnTable - Required. Column of records to count.
CountIf ( Table, LogicalFormula )
Table - Required. Table of records to count.
LogicalFormula - Required. Formula to evaluate for each record of the table. Records that return true for this
formula are counted. The formula can reference columns of the table.
CountRows ( Table )
Table - Required. Table of records to count.
Example
1. Import or create a collection named Inventor y , as the first subprocedure in Show images and text in a
gallery describes.
2. Add a label, and set its Text property to this formula:
CountIf(Inventor y, UnitsInStock < 30)
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(Inventor y.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(Inventor y)
The label shows 5 because the collection contains five rows.
Count, CountA, CountIf, and CountRows functions
in Power Apps
11/19/2022 • 2 minutes to read • Edit Online
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.
The CountRows function counts the number of records in a table.
Each of these functions returns a number.
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:
1. Open the app where you want to use the functions.
2. Select Settings > Upcoming features > Preview .
3. Turn on the Enhanced delegation for Microsoft Dataverse 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 )
SingleColumnTable - Required. Column of records to count.
CountIf ( Table, LogicalFormula )
Table - Required. Table of records to count.
LogicalFormula - Required. Formula to evaluate for each record of the table. Records that return true for this
formula are counted. The formula can reference columns of the table.
CountRows ( Table )
Table - Required. Table of records to count.
Example
1. Import or create a collection named Inventor y , as the first subprocedure in Show images and text in a
gallery describes.
2. Add a label, and set its Text property to this formula:
CountIf(Inventor y, UnitsInStock < 30)
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(Inventor y.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(Inventor y)
The label shows 5 because the collection contains five rows.
Count, CountA, CountIf, and CountRows functions
in Power Apps
11/19/2022 • 2 minutes to read • Edit Online
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.
The CountRows function counts the number of records in a table.
Each of these functions returns a number.
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:
1. Open the app where you want to use the functions.
2. Select Settings > Upcoming features > Preview .
3. Turn on the Enhanced delegation for Microsoft Dataverse 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 )
SingleColumnTable - Required. Column of records to count.
CountIf ( Table, LogicalFormula )
Table - Required. Table of records to count.
LogicalFormula - Required. Formula to evaluate for each record of the table. Records that return true for this
formula are counted. The formula can reference columns of the table.
CountRows ( Table )
Table - Required. Table of records to count.
Example
1. Import or create a collection named Inventor y , as the first subprocedure in Show images and text in a
gallery describes.
2. Add a label, and set its Text property to this formula:
CountIf(Inventor y, UnitsInStock < 30)
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(Inventor y.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(Inventor y)
The label shows 5 because the collection contains five rows.
DataSourceInfo function in Power Apps
11/19/2022 • 3 minutes to read • Edit Online
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.
NOTE
Currently, the DataSourceInfo function is not supported in Microsoft Lists.
Description
Column information
You can use DataSourceInfo to obtain information about a particular column of a data source:
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 )
DataSource – Required. The data source to use.
Information – Required. The type of information that you want to retrieve.
ColumnName – Optional. For column-level information, the column name as a string. Column Phone
would be passed as "Phone" , including the double quotes. For information at the data-source level, the
ColumnName argument can't be used.
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 :
DataSourceInfo( IceCream, Returns the display name for the "Quantity on Hand"
DataSourceInfo.DisplayName, "Q Quantity column of the IceCream
uantity" ) data source.
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.
Time ( Hour, Minute, Second )
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 :
Date(Value(HireYear.Text), Value(HireMonth.Text), Value(HireDay.Text))
Time
If a user typed 14 in a text-input control named Bir thHour , 50 in a text-input control named Bir thMinute , and
24 in a text-input control named Bir thSecond , this function would return 02:50:24 p .
Text(Time(Value(Bir thHour.Text), Value(Bir thMinute.Text), Value(Bir thSecond.Text)), "hh:mm:ss a/p")
DateAdd, DateDiff, and TimeZoneOffset functions in
Power Apps
11/19/2022 • 3 minutes to read • Edit Online
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.
For both functions, units can be Milliseconds , Seconds , Minutes , Hours , Days , Months , Quar ters , or Years .
By default, both functions use Days as 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 ] )
DateTime - Required. Date/time value to operate on.
Addition - Required. Number, in Units, to add to the DateTime.
Units - Optional. The type of Units to add: Milliseconds , Seconds , Minutes , Hours , Days , Months ,
Quar ters , or Years . If not specified, Days are used.
DateDiff ( StartDateTime, EndDateTime [, Units ] )
StartDateTime - Required. Starting date/time value.
EndDateTime - Required. Ending date/time value.
Units - Optional. The type of Units to subtract: Milliseconds , Seconds , Minutes , Hours , Days , Months ,
Quar ters , or Years . If not specified, Days are used.
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
F O RM UL A DESC RIP T IO N RESULT
Text( DateAdd( Now(), 3 ), Adds three days (default units) to the "18-07-2013 13:02"
"dd-mm-yyyy hh:mm" ) current date and time.
Text( DateAdd( Now(), 4, Hours ), Add four hours to the current date "15-07-2013 17:02"
"dd-mm-yyyy hh:mm" ) and time.
Text( DateAdd( Today(), 1, Adds one month to the current date, "15-08-2013 00:00"
Months ), without time as Today doesn't return
"dd-mm-yyyy hh:mm" ) a time component.
Text( DateAdd( Now(), 30, Subtracts 30 minutes from the current "15-07-2013 12:32"
Minutes ), date and time.
"dd-mm-yyyy hh:mm" )
Simple DateDiff
F O RM UL A DESC RIP T IO N RESULT
DateDiff( Now(), Today(), Minutes Returns the difference between the -782
) current date/time and the current date
only (no time) in minutes. Since the
Now is later than Today the result will
be negative.
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:
DateAdd( Now(), TimeZoneOffset(), Minutes )
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 .
Converting from UTC
To convert from UTC, subtract the TimeZoneOffset (by adding the negative) for the given time.
For example, imagine the UTC date and time July 15, 2013, 8:02 PM is stored in a variable named Star tTime .
To adjust the time for the user's time zone, use:
DateAdd( Star tTime, −TimeZoneOffset( Star tTime ), Minutes )
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
11/19/2022 • 3 minutes to read • Edit Online
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.
For both functions, units can be Milliseconds , Seconds , Minutes , Hours , Days , Months , Quar ters , or Years .
By default, both functions use Days as 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 ] )
DateTime - Required. Date/time value to operate on.
Addition - Required. Number, in Units, to add to the DateTime.
Units - Optional. The type of Units to add: Milliseconds , Seconds , Minutes , Hours , Days , Months ,
Quar ters , or Years . If not specified, Days are used.
DateDiff ( StartDateTime, EndDateTime [, Units ] )
StartDateTime - Required. Starting date/time value.
EndDateTime - Required. Ending date/time value.
Units - Optional. The type of Units to subtract: Milliseconds , Seconds , Minutes , Hours , Days , Months ,
Quar ters , or Years . If not specified, Days are used.
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
F O RM UL A DESC RIP T IO N RESULT
Text( DateAdd( Now(), 3 ), Adds three days (default units) to the "18-07-2013 13:02"
"dd-mm-yyyy hh:mm" ) current date and time.
Text( DateAdd( Now(), 4, Hours ), Add four hours to the current date "15-07-2013 17:02"
"dd-mm-yyyy hh:mm" ) and time.
Text( DateAdd( Today(), 1, Adds one month to the current date, "15-08-2013 00:00"
Months ), without time as Today doesn't return
"dd-mm-yyyy hh:mm" ) a time component.
Text( DateAdd( Now(), 30, Subtracts 30 minutes from the current "15-07-2013 12:32"
Minutes ), date and time.
"dd-mm-yyyy hh:mm" )
Simple DateDiff
F O RM UL A DESC RIP T IO N RESULT
DateDiff( Now(), Today(), Minutes Returns the difference between the -782
) current date/time and the current date
only (no time) in minutes. Since the
Now is later than Today the result will
be negative.
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:
DateAdd( Now(), TimeZoneOffset(), Minutes )
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 .
Converting from UTC
To convert from UTC, subtract the TimeZoneOffset (by adding the negative) for the given time.
For example, imagine the UTC date and time July 15, 2013, 8:02 PM is stored in a variable named Star tTime .
To adjust the time for the user's time zone, use:
DateAdd( Star tTime, −TimeZoneOffset( Star tTime ), Minutes )
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
11/19/2022 • 4 minutes to read • Edit Online
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.
NOTE
The DateValue, TimeValue, and DateTimeValue functions by default use the language from the current user's settings. You
can override it to ensure that strings are interpreted properly. For example, "10/1/1920" is interpreted as October 1st in
"en" and as January 10th in "fr".
Syntax
DateValue ( String [, Language ])
DateTimeValue ( String [, Language ])
TimeValue ( 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 )
Untyped - Required. Untyped object that represents a date or time. Acceptable values are dependent on the
untyped provider. For JSON , the untyped object is expected to be a JSON string that contains a date and time
in ISO 8601 format. Dates or times in other formats will result in an error. Consider converting such values to
Text first, then to a date or time. Keep in mind that time zones and locale-related formats are important
considerations when communicating with external systems.
Examples
DateValue
If you type 10/11/2014 into a text-input control named Star tdate , 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.
Device set to en locale shows the label as Saturday, October 11, 2014 .
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.
Device set to en locale shows the label as Monday, November 10, 2014 .
If you typed October 20, 2014 instead:
Convert a date from a string in the user's locale and calculate the difference between two days, in days
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 Star t , and then set the Text
property of a label to the following formula:
Convert both a date and time string in the current locale.
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.
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.
Device set to en locale shows the label as Saturday, October 11, 2014 01:50:24.765 PM .
As an alternative, you can specify hh:mm:ss.f or hh:mm:ss.ff to round the time to the nearest 10th or
100th of a second.
TimeValue
Name a text-input control FinishedAt , and set the Text property of a label to this formula:
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
11/19/2022 • 4 minutes to read • Edit Online
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.
NOTE
The DateValue, TimeValue, and DateTimeValue functions by default use the language from the current user's settings. You
can override it to ensure that strings are interpreted properly. For example, "10/1/1920" is interpreted as October 1st in
"en" and as January 10th in "fr".
Syntax
DateValue ( String [, Language ])
DateTimeValue ( String [, Language ])
TimeValue ( 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 )
Untyped - Required. Untyped object that represents a date or time. Acceptable values are dependent on the
untyped provider. For JSON , the untyped object is expected to be a JSON string that contains a date and time
in ISO 8601 format. Dates or times in other formats will result in an error. Consider converting such values to
Text first, then to a date or time. Keep in mind that time zones and locale-related formats are important
considerations when communicating with external systems.
Examples
DateValue
If you type 10/11/2014 into a text-input control named Star tdate , 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.
Device set to en locale shows the label as Saturday, October 11, 2014 .
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.
Device set to en locale shows the label as Monday, November 10, 2014 .
If you typed October 20, 2014 instead:
Convert a date from a string in the user's locale and calculate the difference between two days, in days
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 Star t , and then set the Text
property of a label to the following formula:
Convert both a date and time string in the current locale.
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.
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.
Device set to en locale shows the label as Saturday, October 11, 2014 01:50:24.765 PM .
As an alternative, you can specify hh:mm:ss.f or hh:mm:ss.ff to round the time to the nearest 10th or
100th of a second.
TimeValue
Name a text-input control FinishedAt , and set the Text property of a label to this formula:
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
11/19/2022 • 2 minutes to read • Edit Online
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 )
DateTime - Required. Date/Time value to operate on.
Weekday ( DateTime [, WeekdayFirst ] )
DateTime - Required. Date/Time value to operate on.
WeekdayFirst - Optional. Excel code specifying which day starts the week. If not supplied, 1 (Sunday first) is
used.
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
F O RM UL A DESC RIP T IO N RESULT
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.
The Pi function returns the transcendental number π, which begins 3.141592...
The Radians function converts degrees to radians.
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, 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 )
Radians - Required. Angle to operate on.
Cos ( SingleColumnTable )
Cot ( SingleColumnTable )
Sin ( SingleColumnTable )
Tan ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of angles to operate on.
Inverse Functions
Acos ( Number )
Acot ( Number )
Asin ( Number )
Atan ( Number )
Number - Required. Number to operate on.
Acos ( SingleColumnTable )
Acot ( SingleColumnTable )
Asin ( SingleColumnTable )
Atan ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of numbers to operate on.
Atan2 ( X, Y )
X - Required. X-axis coordinate.
Y - Required. Y-axis coordinate.
Helper Functions
Degrees ( Radians )
Radians - Required. Angle in radians to convert to degrees.
Pi ()
Radians ( Degrees )
Degrees - Required. Angle in degrees to convert to radians.
Examples
Single number
F O RM UL A DESC RIP T IO N RESULT
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.
When a signal isn't being used, it's automatically turned off.
Description
The Enable and Disable functions turn a signal on and off, respectively.
These functions currently only work for the Location signal.
These functions have no return value. You can use them only in behavior formulas.
Syntax
Enable ( Signal )
Disable ( Signal )
Signal - Required. The signal to turn on or off.
Distinct function in Power Apps
11/19/2022 • 2 minutes to read • Edit Online
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 )
Table - Required. Table to evaluate across.
Formula - Required. Formula to evaluate for each record.
Example
1. Insert a Button control, and set its OnSelect property to this formula.
ClearCollect( CityPopulations,
{ City: "London", Country: "United Kingdom", Population: 8615000 },
{ City: "Berlin", Country: "Germany", Population: 3562000 },
{ City: "Madrid", Country: "Spain", Population: 3165000 },
{ City: "Hamburg", Country: "Germany", Population: 1760000 },
{ City: "Barcelona", Country: "Spain", Population: 1602000 },
{ City: "Munich", Country: "Germany", Population: 1494000 }
);
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:
This formula sorts the results from Distinct with the Sor t 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
11/19/2022 • 2 minutes to read • Edit Online
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.
Download can only be used in behavior formulas.
Syntax
Download ( Address )
Address – Required. The URL address of a web resource to download.
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:
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.
2. Select Apps from left navigation pane.
3. Select your app and then select Edit .
4. Select Inser t from the menu and then select Label .
5. Move the label to the bottom right of the screen.
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.
8. From property list on top left, select OnSelect .
9. Enter formula as Download("https://go.microsoft.com/fwlink/?linkid=827480") . You can also use any other
URL of your choice.
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
11/19/2022 • 6 minutes to read • Edit Online
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.
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 formula is evaluated for each record of the table.
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 DropColumns function excludes columns from a table. All other columns remain unmodified.
DropColumns excludes columns, and ShowColumns includes columns.
Use the RenameColumns function to rename one or more columns of a table by providing at least one
argument pair that specifies the name of a column that the table contains (the old name, which you want to
replace) and the name of a column that the table doesn't contain (the new name, which you want to use). The
old name must already exist in the table, and the new name must not exist. Each column name may appear only
once in the argument list as either an old column name or a new column name. To rename a column to an
existing column name, first drop the existing column with DropColumns , or rename the existing column out of
the way by nesting one RenameColumns function within another.
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:
AddColumns( RealEstateAgents,
"Listings",
Filter( '[dbo].[AllListings]', ListingAgentName = AgentName )
)
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 OnStar t 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, ... ] )
Table - Required. Table to operate on.
ColumnName(s) - Required. Name(s) of the column(s) to add. You must specify a string (for example,
"Name" with double quotes included) for this argument.
Formula(s) - Required. Formula(s) to evaluate for each record. The result is added as the value of the
corresponding new column. You can reference other columns of the table in this formula.
DropColumns ( Table, ColumnName1 [, ColumnName2, ... ] )
Table - Required. Table to operate on.
ColumnName(s) - Required. Name(s) of the column(s) to drop. You must specify a string (for example,
"Name" with double quotes included) for this argument.
RenameColumns ( Table, OldColumnName1, NewColumnName1 [, OldColumnName2, NewColumnName2, ... ]
)
Table - Required. Table to operate on.
OldColumnName - Required. Name of a column to rename from the original table. This element appears first
in the argument pair (or first in each argument pair if the formula includes more than one pair). This name
must be a string (for example "Name" with double quotation marks included).
NewColumnName - Required. Replacement name. This element appears last in the argument pair (or last in
each argument pair if the formula includes more than one pair). You must specify a string (for example,
"Customer Name" with double quotation marks included) for this argument.
ShowColumns ( Table, ColumnName1 [, ColumnName2, ... ] )
Table - Required. Table to operate on.
ColumnName(s) - Required. Name(s) of the column(s) to include. You must specify a string (for example,
"Name" with double quotes included) for this argument.
Examples
The examples in this section use the IceCreamSales data source, which contains the data in this table:
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.
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:
ClearCollect( IceCreamSales,
Table(
{ Flavor: "Strawberry", UnitPrice: 1.99, QuantitySold: 20 },
{ Flavor: "Chocolate", UnitPrice: 2.99, QuantitySold: 45 },
{ Flavor: "Vanilla", UnitPrice: 1.50, QuantitySold: 35 }
)
)
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:
ClearCollect( FirstExample,
AddColumns( IceCreamSales, "Revenue", UnitPrice * QuantitySold )
)
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
11/19/2022 • 5 minutes to read • Edit Online
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:
M O DE DESC RIP T IO N
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.
These functions return no values.
You can use these functions only in behavior formulas.
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 validation passes, SubmitForm submits the change to the data source.
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):
Syntax
SubmitForm ( FormName )
FormName - Required. Form control to submit to the data source.
EditForm ( FormName )
FormName - Required. Form control to switch to FormMode.Edit mode.
NewForm ( FormName )
FormName - Required. Form control to switch to FormMode.New mode.
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 )
FormName - Required. Form control to switch to FormMode.View mode.
Examples
See Understand data forms for complete examples.
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:
ResetForm( EditForm ); Back()
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:
NewForm( EditForm ); Navigate( EditScreen, None )
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
11/19/2022 • 2 minutes to read • Edit Online
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.
When a signal isn't being used, it's automatically turned off.
Description
The Enable and Disable functions turn a signal on and off, respectively.
These functions currently only work for the Location signal.
These functions have no return value. You can use them only in behavior formulas.
Syntax
Enable ( Signal )
Disable ( Signal )
Signal - Required. The signal to turn on or off.
EncodeUrl and PlainText functions in Power Apps
11/19/2022 • 2 minutes to read • Edit Online
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 )
String - Required. URL to be encoded.
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:
<p>
We have done an unusually "deep" globalization and
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 Star tsWith 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 Star tsWith 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 )
Text – Required. The text to test.
EndText – Required. The text to search for at the end of Text. If EndText is an empty string, EndsWith returns
true.
Star tsWith ( Text, StartText )
Text – Required. The text to test.
StartText – Required. The text to search for at the beginning of Text. If StartText is an empty string, Star tsWith
returns true.
Examples
F O RM UL A DESC RIP T IO N RESULT
EndsWith( "Hello World", "world" Tests whether "Hello World" ends true
) with "world". The test is case
insensitive.
EndsWith( "Good bye", "good" ) Tests whether "Good bye" ends with false
"good". The EndText argument
("good") appears in the text but not
at the end.
EndsWith( "Always say hello", Tests whether "Always say hello" true
"hello" ) ends with "hello".
F O RM UL A DESC RIP T IO N RESULT
EndsWith( "Bye bye", "" ) Tests whether "Bye bye" ends with an true
empty text string (Len returns 0).
Easing its use in Filter expressions,
EndsWith is defined to return true in
this case.
Star tsWith( "Hello World", "hello" Tests whether "Hello World" begins true
) with "hello". The test is case
insensitive.
Star tsWith( "Good bye", "hello" ) Tests whether "Good bye" begins false
with "hello".
Star tsWith( "Always say hello", Tests whether "Always say hello" false
"hello" ) begins with "hello". Although "hello"
appears in the text, it doesn't appear at
the beginning.
Star tsWith( "Bye bye", "" ) Tests whether "Bye bye" starts with true
an empty text string (Len returns 0).
Easing its use in Filter expressions,
Star tsWith is defined to return true
in this case.
To create this data source as a collection, create a Button control and set its OnSelect property to this formula:
ClearCollect( Customers, Table( { Name: "Fred Garcia", Company: "Nor thwind Traders" }, { Name:
"Cole Miller", Company: "Contoso" }, { Name: "Glenda Johnson", Company: "Contoso" }, { Name:
"Mike Collins", Company: "Adventure Works" }, { Name: "Colleen Jones", Company: "Adventure
Works" } ) )
As in this example, you can show a list of records in a Galler y 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, Star tsWith( Filters the Customers data source for
Name, SearchInput.Text ) ) records in which the search string
appears at the start of the Name
column. The test is case 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.
F O RM UL A DESC RIP T IO N RESULT
You can expand your search to include the Company column as well as the Name column:
Filter( Customers, Star tsWith( Filters the Customers data source for
Name, SearchInput.Text ) || records in which either the Name
Star tsWith( Company, column or the Company column
SearchInput.Text ) ) starts with the search string (for
example, co ). The || operator is true if
either Star tsWith function is true.
NOTE
Error, IfError, IsError, and IsBlankOrError functions are part of an experimental feature and are subject to change. More
information: Understand experimental, preview, and deprecated features in Power Apps.
The behavior that this article describes is available only when the Formula-level error management experimental
feature in Settings > Upcoming features > Experimental is turned on (off by default).
Your feedback is very valuable to us - please let us know what you think in the Power Apps community forums.
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:
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.
Stopping further processing
When chaining formulas together in behavior formulas, such as:
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:
IfError(
Patch( DS1, ... ), Notify( "problem in the first action" ),
Patch( DS2, ... ), Notify( "problem in the second action" )
)
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.
If supplied, the optional DefaultResult argument is returned if no errors are discovered. Without this argument,
the last Value argument is returned.
Building on the last example, the return value from IfError can be checked to determine if there were any
problems:
IfError(
Patch( DS1, ... ), Notify( "problem in the first action" ); false,
Patch( DS2, ... ), Notify( "problem in the second action" ); false,
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 .
NOTE
While the behavior in process for a change, the types of all arguments to IfError must be compatible currently.
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.
Excel will display #DIV/0! when a division by zero occurs.
Consider IfError with the following instead:
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:
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 ) .
Error records include:
F IEL D TYPE DESC RIP T IO N
For example, consider the following formula as a Button control's OnSelect property:
Set( a, 1/0 )
IfError( a, Notify( "Internal error: originated on " & FirstError.Source & ", surfaced on " &
FirstError.Observed ) )
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.
The return value is a Boolean true or false.
Using IsError will prevent any further processing of the error.
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 .
The return value is a boolean true or false.
Using IsBlankOrError will prevent any further processing of the error.
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 )
ErrorRecord – Required. Error information record, including Kind , Message , and other fields. Kind is
required. FirstError can be passed directly.
ErrorTable – Required. Table of error information records. AllErrors can be passed directly.
IfError ( Value1, Replacement1 [, Value2, Replacement2, ... [, DefaultResult ] ] )
Value(s) – Required. Formula(s) to test for an error value.
Replacement(s) – Required. The formulas to evaluate and values to return if matching Value arguments
returned an error.
DefaultResult – Optional. The formulas to evaluate if the formula doesn't find any errors.
IsError ( Value )
IsBlankOrError ( Value )
Value – Required. Formula to test.
Examples
Simple IfError
F O RM UL A DESC RIP T IO N RESULT
IfError( 10, 11, 20, 21, 300 ) The first argument 10 isn't an error, so 300
the function doesn't evaluate that
argument's corresponding replacement
11 . The third argument 20 isn't an
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( 1/0, Notify( "There was The first argument returns an error 1
an internal problem" ) ) value (due to division by zero). The
function evaluates the second
argument and displays a message to
the user. The return value of IfError is
the return value of Notify , coerced to
the same type as the first argument to
IfError (a number).
Simple IsError
F O RM UL A DESC RIP T IO N RESULT
If( IsError( 1/0 ), Notify( "There The argument to IsError returns an true
was an internal problem" ) ) error value (because of division by
zero). This function returns true, which
causes the If to display a message to
the user with the Notify function. The
return value of If is the return value of
Notify , coerced to the same type as
the first argument to If (a boolean).
Simple IsBlankOrError
F O RM UL A DESC RIP T IO N RESULT
Simple Error
In this example, dates are validated relative to one another, resulting in an error if there is a problem.
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.
With( {a: 1, b: 0} )
IfError( a/b, If( FirstError.Kind <> ErrorKind.Div0, Error( FirstError ), -1 ) ) )
// 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:
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.
3. Set the formula for Label1 's Text property to:
IfError( Value( TextInput1.Text ), -1 )
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 Patch function and other data functions don't directly return errors. Instead they return the result of their
operation. After a data function executes, you can use the Errors function to obtain the details of any errors. You
can check for the existence of errors with the [IsEmpty] function in the formula IsEmpty( Errors ( ... ) ) .
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.EditPermission An attempt was made to edit a record, and the current user
doesn't have permission to edit records.
ErrorKind.MissingRequired The value for a required column is missing from the record.
ERRO RK IN D DESC RIP T IO N
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 :
UpdateContext( { EditRecord: First( Filter( IceCream, Flavor = "Chocolate" ) ) } )
To make this change in the data source, the Patch function is used:
Patch( IceCream, EditRecord, Galler y.Updates )
where Galler y.Updates evaluates to { Quantity: 90 } , since only the Quantity property has been modified.
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:
IsEmpty( Errors( IceCream, EditRecord ) )
which returns false , because the Errors function returned the following table:
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:
Label.Text = First(Errors( IceCream, EditRecord )).Message
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:
!IsEmpty( Lookup( Errors( IceCream, EditRecord ), Error = ErrorKind.Conflict ) )
To revert the change which the user selects the button, set its OnSelect property to this formula:
ReloadButton.OnSelect = Rever t( IceCream, EditRecord )
Operators and Identifiers in Power Apps
11/19/2022 • 12 minutes to read • Edit Online
Some of these operators are dependent on the language of the author. For more information about language
support in canvas apps, see Global apps.
* 2*3 Multiplication
& String concatenation "hello" & " " & "world" Makes multiple strings
operator appear continuous
&& or And Logical operators Price < 100 && Logical conjunction,
Slider1.Value = 20 equivalent to the And
or Price < 100 And function
Slider1.Value = 20
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')
ThisRecord ForAll, Filter , With , Sum and other The default name for the current
record scope functions record in ForAll and other record
scope functions.
ThisItem operator
For example, in the following Galler y control, the Items property is set to the Employees data source (such as
the Employees table included with the Northwind Traders sample):
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:
ThisItem.Picture
Likewise, the formula for the name also uses ThisItem :
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:
ThisRecord is optional and implied by using the fields directly, for example, in this case, we could have written:
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:
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:
Employees As Employee
The formulas for the picture and name are adjusted to use this name for the current record:
Employee.Picture
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:
Concat(
ForAll( Sequence(8) As Rank,
Concat(
ForAll( Sequence(8) As File,
If( Mod(Rank.Value + File.Value, 2) = 1, " X ", " . " )
),
Value
) & Char(10)
),
Value
)
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:
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:
M ET H O D DESC RIP T IO N
M ET H O D DESC RIP T IO N
Parent operator Some controls host other controls, such as the Screen and
Galler y controls. The 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.
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
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 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.
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).
For more information and examples, see record scopes.
Exit function in Power Apps
11/19/2022 • 2 minutes to read • Edit Online
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.
Exit can only be used in behavior formulas.
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
F O RM UL A DESC RIP T IO N
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
11/19/2022 • 2 minutes to read • Edit Online
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 Ln function returns the natural logarithm (base e) of its argument.
The Power function returns a number raised to a power. It is 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 Sqr t 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, 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. This can happen, for example, with
square roots and logarithms of negative numbers.
Syntax
Abs ( Number )
Exp ( Number )
Ln ( Number )
Sqr t ( Number )
Number - Required. Number to operate on.
Power ( Base, Exponent )
Base - Required. Base number to raise.
Exponent - Required. The exponent to which the base number is raised.
Log ( Number, Base )
Number - Required. Number to calculate the logarithm.
Base - Optional. The base of the logarithm to calculate. By default, 10 (when not specified).
Abs ( SingleColumnTable )
Exp ( SingleColumnTable )
Ln ( SingleColumnTable )
Sqr t ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of numbers to operate on.
Examples
Single number
F O RM UL A DESC RIP T IO N RESULT
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:
Sqr t( Value( Source.Text ) )
3. Type a number into Source , and confirm that the Label control shows the square root of the number that
you typed.
Filter, Search, and LookUp functions in Power Apps
11/19/2022 • 9 minutes to read • Edit Online
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 Galler y 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 Galler y may not be the
complete story, which could be confusing to users.
See the delegation overview for more information.
Syntax
Filter (Table*, Formula1 [, *Formula2*, ... ] )
Table - Required. Table to search.
Formula(s) - Required. The formula by which each record of the table is evaluated. The function returns all
records that result in true . You can reference columns within the table. If you supply more than one formula,
the results of all formulas are combined with the And function.
Search (Table*, SearchString, Column1 [, *Column2*, ... ] )
Table - Required. Table to search.
SearchString - Required. The string to search for. If blank or an empty string, all records are returned.
Column(s) - Required. The names of columns within Table to search. Columns to search must contain text.
Column names must be strings and enclosed in double quotes. However, the column names must be static
and cannot be calculated with a formula. If SearchString is found within the data of any of these columns as a
partial match, the full record will be returned.
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 following examples use the IceCream data source:
LookUp(IceCream, Flavor = Searches for a record with Flavor { Flavor: "Vanilla", Quantity: 200,
"Vanilla") equal to "Vanilla", of which there is OnOrder: 75 }
one. Since no reduction formula was
supplied, the entire record is returned.
8. Now select Galler y control and set the Items property to the following formula:
Filter(Accounts,
'Industry' = ComboBox3.Selected.Industry||IsBlank(ComboBox3.Selected.Industry),
'Relationship Type' = ComboBox2.Selected.'Relationship Type'||
IsBlank(ComboBox2.Selected.'Relationship Type'),
'Preferred Method of Contact' = ComboBox1.Selected.'Preferred Method of Contact'||
IsBlank(ComboBox1.Selected.'Preferred Method of Contact'))
To create this data source as a collection, create a Button control and set its OnSelect property to this formula:
ClearCollect(Customers, Table({ Name: "Fred Garcia", Company: "Nor thwind Traders" }, { Name:
"Cole Miller", Company: "Contoso" }, { Name: "Glenda Johnson", Company: "Contoso" }, { Name:
"Mike Collins", Company: "Adventure Works" }, { Name: "Colleen Jones", Company: "Adventure
Works" }) )
As in this example, you can show a list of records in a Galler y 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:
You can expand your search to include the Company column and the Name column:
F O RM UL A DESC RIP T IO N RESULT
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 ] )
FindString - Required. The string to find.
WithinString - Required. The string to search within.
StartingPosition - Optional. The starting position to start searching. Position 1 is the first character.
First, FirstN, Index, Last, and LastN functions in
Power Apps
11/19/2022 • 2 minutes to read • Edit Online
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 Last function returns the last record of a table.
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 )
Table - Required. Table to operate on.
FirstN ( Table [, NumberOfRecords ] )
LastN ( Table [, NumberOfRecords ] )
Table - Required. Table to operate on.
NumberOfRecords - Optional. Number of records to return. If you don't specify this argument, the function
returns one record.
Index ( Table, RecordIndex )
Table - Required. Table to operate on.
RecordIndex - Required. The index of the record to return. Record numbering begins with 1.
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):
First( IceCream ) Returns the first record of IceCream . { Flavor: "Chocolate", Quantity: 100 }
Last( IceCream ) Returns the last record of IceCream . { Flavor: "Pistachio", Quantity: 200 }
Index( IceCream, 3 ) Returns the third record of IceCream . { Flavor: "Strawberry", Quantity: 300 }
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 Last function returns the last record of a table.
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 )
Table - Required. Table to operate on.
FirstN ( Table [, NumberOfRecords ] )
LastN ( Table [, NumberOfRecords ] )
Table - Required. Table to operate on.
NumberOfRecords - Optional. Number of records to return. If you don't specify this argument, the function
returns one record.
Index ( Table, RecordIndex )
Table - Required. Table to operate on.
RecordIndex - Required. The index of the record to return. Record numbering begins with 1.
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):
First( IceCream ) Returns the first record of IceCream . { Flavor: "Chocolate", Quantity: 100 }
Last( IceCream ) Returns the last record of IceCream . { Flavor: "Pistachio", Quantity: 200 }
Index( IceCream, 3 ) Returns the third record of IceCream . { Flavor: "Strawberry", Quantity: 300 }
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:
ClearCollect( Squares, [ "1", "4", "9" ] )
ForAll( Squares, Sqr t( Value ) ) For all the records of the input table,
calculates the square root of the Value
Sqr t( Squares ) column. The Sqr t function can also be
used with a single-column table,
making it possible perform this
example without using ForAll.
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 Sor t . 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.
The following examples use the Products 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( Products,
Table(
{ Product: "Widget", 'Quantity Requested': 6, 'Quantity Available': 3 },
{ Product: "Gadget", 'Quantity Requested': 10, 'Quantity Available': 20 },
{ Product: "Gizmo", 'Quantity Requested': 4, 'Quantity Available': 11 },
{ Product: "Apparatus", 'Quantity Requested': 7, 'Quantity Available': 6 }
)
)
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.
Table shaping on demand
Don't make that copy! We can use the following formula anywhere we need:
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:
ForAll( Products,
If( 'Quantity Requested' > 'Quantity Available',
{
Product: Product,
'Quantity To Order': 'Quantity Requested' - 'Quantity Available'
}
)
)
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.
Collect the result
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:
ClearCollect( NewOrder,
ShowColumns(
AddColumns(
Filter( Products, 'Quantity Requested' > 'Quantity Available' ),
"Quantity To Order", 'Quantity Requested' - 'Quantity Available'
),
"Product",
"Quantity To Order"
)
)
ClearCollect( NewOrder,
ForAll( Products,
If( 'Quantity Requested' > 'Quantity Available',
{
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.
Collect within ForAll
Finally, we can perform the Collect directly within the ForAll :
Clear( ProductsToOrder );
ForAll( Products,
If( 'Quantity Requested' > 'Quantity Available',
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.
Map table in a component
See Map tables.
GroupBy and Ungroup functions in Power Apps
11/19/2022 • 4 minutes to read • Edit Online
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:
Use the GroupBy function.
Use the Filter function to remove the entire group of records.
Use the Ungroup function.
You can also aggregate results based on a grouping:
Use the GroupBy function.
Use the AddColumns function with Sum , Average , and other aggregate functions to add a new column
which is an aggregate of the group tables.
Use the DropColumns function to drop the group table.
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.
ColumnName(s) - Required. The column names in Table by which to group records. These columns
become columns in the resulting table.
GroupColumnName - Required. The column name for the storage of record data not in the
ColumnName(s).
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".
Ungroup ( Table, GroupColumnName )
Table - Required. Table to be ungrouped.
GroupColumnName - Required. The column that contains the record data setup with the GroupBy
function.
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:
ClearCollect( CityPopulations,
{ City: "London", Country: "United Kingdom", Population: 8615000},
{ City: "Berlin", Country: "Germany", Population: 3562000},
{ City: "Madrid", Country: "Spain", Population: 3165000},
{ City: "Rome", Country: "Italy", Population: 2874000},
{ City: "Paris", Country: "France", Population: 2273000},
{ City: "Hamburg", Country: "Germany", Population: 1760000},
{ City: "Barcelona", Country: "Spain", Population: 1602000},
{ City: "Munich", Country: "Germany", Population: 1494000},
{ City: "Milan", Country: "Italy", Population: 1344000}
)
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:
ClearCollect( CitiesByCountr y, GroupBy( CityPopulations, "Countr y", "Cities" ) )
3. While holding down the Alt key, select the Group button.
You just created a collection, named CitiesByCountr y , in which the records of the previous collection are
grouped by the Countr y 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):
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" .
2. Set the OnSelect property of the "Sum" button to this formula:
ClearCollect( CityPopulationsSum, AddColumns( CitiesByCountr y, "Sum of City Populations",
Sum( Cities, Population ) ) )
Which results in:
AddColumns starts with the base CitiesByCountr y collection and adds a new column Sum of City
Populations . This column's values are calculated row-by-row, based on the formula Sum( Cities,
Population ) . AddColumns provides the value of the Cities column (a table) for each row, and Sum
adds up the Population for each row of this sub table.
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" .
4. Set the OnSelect property of the "SumOnly" button to this formula:
ClearCollect( CityPopulationsSumOnly, DropColumns( CityPopulationsSum, "Cities" ) )
Which results in:
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:
"123e4567-e89b-12d3-a456-426655440000" (hyphens in standard locations)
"123e4567e89b12d3a456426655440000" (no hyphens)
If you don't specify an argument, this function creates a new GUID.
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:
TextInput1.Text & " " & GUID()
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 ] )
GUIDString – Optional. A text string that contains the hexadecimal representation of a GUID. If no string is
supplied, a new GUID is created.
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:
GUID( "0f8fad5b-d9cb-469f-a165-70867728950e" )
You can also provide the GUID string without hyphens. This formula returns the same GUID value:
GUID( "0f8fad5bd9cb469fa16570867728950e" )
Used in context, to set the Status field of a new database record to a well-established value:
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:
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.
The data table shows a list of GUIDs:
4. Select the button again to show a different list of GUIDs:
Description
The HashTags function scans a string for hashtags. Hashtags start with a pound character (#), which is followed
by any combination of:
uppercase and lowercase letters
numerals
underscores
currency symbols (such as $)
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 )
String - Required. String to scan for hashtags.
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)
3. Add a Label control to the gallery template.
The gallery shows these hashtags:
#app
#AMAZING
#coUnt123
#123abc
#1
Day, Month, Year, Hour, Minute, Second, and
Weekday functions in Power Apps
11/19/2022 • 2 minutes to read • Edit Online
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 )
DateTime - Required. Date/Time value to operate on.
Weekday ( DateTime [, WeekdayFirst ] )
DateTime - Required. Date/Time value to operate on.
WeekdayFirst - Optional. Excel code specifying which day starts the week. If not supplied, 1 (Sunday first) is
used.
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.
* 2*3 Multiplication
& String concatenation "hello" & " " & "world" Makes multiple strings
operator appear continuous
&& or And Logical operators Price < 100 && Logical conjunction,
Slider1.Value = 20 equivalent to the And
or Price < 100 And function
Slider1.Value = 20
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')
ThisRecord ForAll, Filter , With , Sum and other The default name for the current
record scope functions record in ForAll and other record
scope functions.
ThisItem operator
For example, in the following Galler y control, the Items property is set to the Employees data source (such as
the Employees table included with the Northwind Traders sample):
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:
ThisItem.Picture
Likewise, the formula for the name also uses ThisItem :
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:
ThisRecord is optional and implied by using the fields directly, for example, in this case, we could have written:
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:
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:
Employees As Employee
The formulas for the picture and name are adjusted to use this name for the current record:
Employee.Picture
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:
Concat(
ForAll( Sequence(8) As Rank,
Concat(
ForAll( Sequence(8) As File,
If( Mod(Rank.Value + File.Value, 2) = 1, " X ", " . " )
),
Value
) & Char(10)
),
Value
)
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:
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:
M ET H O D DESC RIP T IO N
M ET H O D DESC RIP T IO N
Parent operator Some controls host other controls, such as the Screen and
Galler y controls. The 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.
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
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 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.
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).
For more information and examples, see record scopes.
If and Switch functions in Power Apps
11/19/2022 • 4 minutes to read • Edit Online
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 ] )
If ( Condition1, ThenResult1 [, Condition2, ThenResult2, ... [ , DefaultResult ] ] )
Condition(s) - Required. Formula(s) to test for true . Such formulas commonly contain comparison operators
(such as < , > , and = ) and test functions such as IsBlank and IsEmpty .
ThenResult(s) - Required. The corresponding value to return for a condition that evaluates to true .
DefaultResult - Optional. The value to return if no condition evaluates to true . If you don't specify this
argument, blank is returned.
Switch ( Formula, Match1, Result1 [, Match2, Result2, ... [, DefaultResult ] ] )
Formula - Required. Formula to evaluate for matches. This formula is evaluated only once.
Match(s) - Required. Values to compare with the result from Formula. If an exact match is found, the
corresponding Result is returned.
Result(s) - Required. The corresponding value to return when an exact match is found.
DefaultResult - Optional. If an exact match isn't found, this value is returned. If you don't specify this
argument, blank is returned.
Examples
Values in formulas
In the following examples, a Slider control (named Slider1 ) has a value of 25 .
If( Slider1.Value = 25, "Result1" ) The condition is true , and the "Result1"
corresponding result is returned.
If( Slider1.Value = 25, "Result1", The condition is true , and the "Result1"
"Result2" ) corresponding result is returned.
If( Slider1.Value = 25, "Result1", The first condition is true , and the "Result1"
Slider1.Value > 0, "Result2" ) corresponding result is returned. The
second condition is also true , but it
isn't evaluated because it appears later
in the argument list than a condition
that evaluates to true .
If( IsBlank( Slider1.Value ), The first condition is false because the "Result2"
"Result1", slider isn't blank. The second condition
IsNumeric( Slider1.Value ), is true because the slider's value is a
"Result2" ) number, and the corresponding result
is returned.
If( Slider1.Value > 1000, Both the first and second conditions "Result3"
"Result1", Slider1.Value > 50, are false , a DefaultResult was
"Result2", "Result3") provided, and it's returned.
Switch( Slider1.Value, 25, The slider's value matches the first "Result1"
"Result1" ) value to be checked, and the
corresponding result is returned.
Switch( Slider1.Value, 20, The slider's value matches the second "Result2"
"Result1", 25, "Result2", 30, value to be checked, and the
"Result3" ) corresponding result is returned.
Switch( Slider1.Value, 20, The slider's value doesn't match any "DefaultResult"
"Result1", 10, "Result2", 0, value to be checked. A DefaultResult
"Result3", "DefaultResult" ) was provided, so it's returned.
Step by step
1. Add a Text input control, and name it Text1 if it doesn't have that name by default.
2. In Text1 , type 30 .
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.
4. In Text1 , type 15 .
The Label control shows Order MANY more! because the value of Text1 is less than 20.
5. In Text1 , type 50 .
The Label control shows the value that you typed because it's more than 40.
Error, IfError, IsError, IsBlankOrError functions in
Power Apps
11/19/2022 • 10 minutes to read • Edit Online
NOTE
Error, IfError, IsError, and IsBlankOrError functions are part of an experimental feature and are subject to change. More
information: Understand experimental, preview, and deprecated features in Power Apps.
The behavior that this article describes is available only when the Formula-level error management experimental
feature in Settings > Upcoming features > Experimental is turned on (off by default).
Your feedback is very valuable to us - please let us know what you think in the Power Apps community forums.
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:
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.
Stopping further processing
When chaining formulas together in behavior formulas, such as:
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:
IfError(
Patch( DS1, ... ), Notify( "problem in the first action" ),
Patch( DS2, ... ), Notify( "problem in the second action" )
)
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.
If supplied, the optional DefaultResult argument is returned if no errors are discovered. Without this argument,
the last Value argument is returned.
Building on the last example, the return value from IfError can be checked to determine if there were any
problems:
IfError(
Patch( DS1, ... ), Notify( "problem in the first action" ); false,
Patch( DS2, ... ), Notify( "problem in the second action" ); false,
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 .
NOTE
While the behavior in process for a change, the types of all arguments to IfError must be compatible currently.
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.
Excel will display #DIV/0! when a division by zero occurs.
Consider IfError with the following instead:
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:
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 ) .
Error records include:
F IEL D TYPE DESC RIP T IO N
For example, consider the following formula as a Button control's OnSelect property:
Set( a, 1/0 )
IfError( a, Notify( "Internal error: originated on " & FirstError.Source & ", surfaced on " &
FirstError.Observed ) )
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.
The return value is a Boolean true or false.
Using IsError will prevent any further processing of the error.
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 .
The return value is a boolean true or false.
Using IsBlankOrError will prevent any further processing of the error.
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 )
ErrorRecord – Required. Error information record, including Kind , Message , and other fields. Kind is
required. FirstError can be passed directly.
ErrorTable – Required. Table of error information records. AllErrors can be passed directly.
IfError ( Value1, Replacement1 [, Value2, Replacement2, ... [, DefaultResult ] ] )
Value(s) – Required. Formula(s) to test for an error value.
Replacement(s) – Required. The formulas to evaluate and values to return if matching Value arguments
returned an error.
DefaultResult – Optional. The formulas to evaluate if the formula doesn't find any errors.
IsError ( Value )
IsBlankOrError ( Value )
Value – Required. Formula to test.
Examples
Simple IfError
F O RM UL A DESC RIP T IO N RESULT
IfError( 10, 11, 20, 21, 300 ) The first argument 10 isn't an error, so 300
the function doesn't evaluate that
argument's corresponding replacement
11 . The third argument 20 isn't an
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( 1/0, Notify( "There was The first argument returns an error 1
an internal problem" ) ) value (due to division by zero). The
function evaluates the second
argument and displays a message to
the user. The return value of IfError is
the return value of Notify , coerced to
the same type as the first argument to
IfError (a number).
Simple IsError
F O RM UL A DESC RIP T IO N RESULT
If( IsError( 1/0 ), Notify( "There The argument to IsError returns an true
was an internal problem" ) ) error value (because of division by
zero). This function returns true, which
causes the If to display a message to
the user with the Notify function. The
return value of If is the return value of
Notify , coerced to the same type as
the first argument to If (a boolean).
Simple IsBlankOrError
F O RM UL A DESC RIP T IO N RESULT
Simple Error
In this example, dates are validated relative to one another, resulting in an error if there is a problem.
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.
With( {a: 1, b: 0} )
IfError( a/b, If( FirstError.Kind <> ErrorKind.Div0, Error( FirstError ), -1 ) ) )
// 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:
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.
3. Set the formula for Label1 's Text property to:
IfError( Value( TextInput1.Text ), -1 )
Some of these operators are dependent on the language of the author. For more information about language
support in canvas apps, see Global apps.
* 2*3 Multiplication
& String concatenation "hello" & " " & "world" Makes multiple strings
operator appear continuous
&& or And Logical operators Price < 100 && Logical conjunction,
Slider1.Value = 20 equivalent to the And
or Price < 100 And function
Slider1.Value = 20
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')
ThisRecord ForAll, Filter , With , Sum and other The default name for the current
record scope functions record in ForAll and other record
scope functions.
ThisItem operator
For example, in the following Galler y control, the Items property is set to the Employees data source (such as
the Employees table included with the Northwind Traders sample):
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:
ThisItem.Picture
Likewise, the formula for the name also uses ThisItem :
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:
ThisRecord is optional and implied by using the fields directly, for example, in this case, we could have written:
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:
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:
Employees As Employee
The formulas for the picture and name are adjusted to use this name for the current record:
Employee.Picture
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:
Concat(
ForAll( Sequence(8) As Rank,
Concat(
ForAll( Sequence(8) As File,
If( Mod(Rank.Value + File.Value, 2) = 1, " X ", " . " )
),
Value
) & Char(10)
),
Value
)
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:
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:
M ET H O D DESC RIP T IO N
M ET H O D DESC RIP T IO N
Parent operator Some controls host other controls, such as the Screen and
Galler y controls. The 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.
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
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 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.
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).
For more information and examples, see record scopes.
First, FirstN, Index, Last, and LastN functions in
Power Apps
11/19/2022 • 2 minutes to read • Edit Online
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 Last function returns the last record of a table.
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 )
Table - Required. Table to operate on.
FirstN ( Table [, NumberOfRecords ] )
LastN ( Table [, NumberOfRecords ] )
Table - Required. Table to operate on.
NumberOfRecords - Optional. Number of records to return. If you don't specify this argument, the function
returns one record.
Index ( Table, RecordIndex )
Table - Required. Table to operate on.
RecordIndex - Required. The index of the record to return. Record numbering begins with 1.
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):
First( IceCream ) Returns the first record of IceCream . { Flavor: "Chocolate", Quantity: 100 }
Last( IceCream ) Returns the last record of IceCream . { Flavor: "Pistachio", Quantity: 200 }
Index( IceCream, 3 ) Returns the third record of IceCream . { Flavor: "Strawberry", Quantity: 300 }
Rounds a number.
Greater than 0 The number is rounded to the right of Round( 12.37, 1 ) returns 12.4.
the decimal separator.
Less than 0 The number is rounded to the left of Round( 12.37, -1 ) returns 10.
the decimal separator.
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)
Number - Required. The number to round.
DecimalPlaces - Required. Number of decimal places to round to. Use a positive value to indicate decimal
places right of the decimal separator, a negative value to the left, and zero for a whole number.
Int (Number)
Trunc (Number)
Number - Required. The number to be rounded to an integer.
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).
ROUNDDOWN( X, [ 0, 1, 2
X INT( X ) ROUND( X, 2 ) ] ) ROUNDUP( X, [ 2 ] )
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.
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 .
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 .
The return value for IsBlank is a boolean true or false .
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.
The return value for IsEmpty is a Boolean true or false .
Syntax
Blank ()
Coalesce ( Value1 [, Value2, ... ] )
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 )
Value – Required. Value to test for a blank value or empty string.
IsEmpty ( Table )
Table - Required. Table to test for records.
Examples
Blank
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.
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:
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
F O RM UL A DESC RIP T IO N RESULT
F O RM UL A DESC RIP T IO N RESULT
IsBlank
1. Create an app from scratch, add a text-input control, and name it FirstName .
2. Add a label, and set its Text property to this formula:
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 true
function, which always returns a blank
value.
IsBlank( Mid( "Hello", 17, 2 ) ) The starting character for Mid is true
beyond the end of the string. The
result is an empty string.
IsEmpty
1. Create an app from scratch, and add a Button control.
2. Set the button's OnSelect property to this formula:
Collect( IceCream, { Flavor : "Strawberr y", Quantity: 300 }, { Flavor : "Chocolate", Quantity:
100 } )
3. Preview your app, click or tap the button that you added, and then close Preview.
A collection named IceCream is created and contains this data:
This collection has two records and isn't empty. IsEmpty( IceCream ) returns false , and CountRows(
IceCream ) returns 2 .
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 collection is now empty:
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:
F O RM UL A DESC RIP T IO N RESULT
NOTE
Error, IfError, IsError, and IsBlankOrError functions are part of an experimental feature and are subject to change. More
information: Understand experimental, preview, and deprecated features in Power Apps.
The behavior that this article describes is available only when the Formula-level error management experimental
feature in Settings > Upcoming features > Experimental is turned on (off by default).
Your feedback is very valuable to us - please let us know what you think in the Power Apps community forums.
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:
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.
Stopping further processing
When chaining formulas together in behavior formulas, such as:
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:
IfError(
Patch( DS1, ... ), Notify( "problem in the first action" ),
Patch( DS2, ... ), Notify( "problem in the second action" )
)
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.
If supplied, the optional DefaultResult argument is returned if no errors are discovered. Without this argument,
the last Value argument is returned.
Building on the last example, the return value from IfError can be checked to determine if there were any
problems:
IfError(
Patch( DS1, ... ), Notify( "problem in the first action" ); false,
Patch( DS2, ... ), Notify( "problem in the second action" ); false,
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 .
NOTE
While the behavior in process for a change, the types of all arguments to IfError must be compatible currently.
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.
Excel will display #DIV/0! when a division by zero occurs.
Consider IfError with the following instead:
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:
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 ) .
Error records include:
F IEL D TYPE DESC RIP T IO N
For example, consider the following formula as a Button control's OnSelect property:
Set( a, 1/0 )
IfError( a, Notify( "Internal error: originated on " & FirstError.Source & ", surfaced on " &
FirstError.Observed ) )
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.
The return value is a Boolean true or false.
Using IsError will prevent any further processing of the error.
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 .
The return value is a boolean true or false.
Using IsBlankOrError will prevent any further processing of the error.
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 )
ErrorRecord – Required. Error information record, including Kind , Message , and other fields. Kind is
required. FirstError can be passed directly.
ErrorTable – Required. Table of error information records. AllErrors can be passed directly.
IfError ( Value1, Replacement1 [, Value2, Replacement2, ... [, DefaultResult ] ] )
Value(s) – Required. Formula(s) to test for an error value.
Replacement(s) – Required. The formulas to evaluate and values to return if matching Value arguments
returned an error.
DefaultResult – Optional. The formulas to evaluate if the formula doesn't find any errors.
IsError ( Value )
IsBlankOrError ( Value )
Value – Required. Formula to test.
Examples
Simple IfError
F O RM UL A DESC RIP T IO N RESULT
IfError( 10, 11, 20, 21, 300 ) The first argument 10 isn't an error, so 300
the function doesn't evaluate that
argument's corresponding replacement
11 . The third argument 20 isn't an
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( 1/0, Notify( "There was The first argument returns an error 1
an internal problem" ) ) value (due to division by zero). The
function evaluates the second
argument and displays a message to
the user. The return value of IfError is
the return value of Notify , coerced to
the same type as the first argument to
IfError (a number).
Simple IsError
F O RM UL A DESC RIP T IO N RESULT
If( IsError( 1/0 ), Notify( "There The argument to IsError returns an true
was an internal problem" ) ) error value (because of division by
zero). This function returns true, which
causes the If to display a message to
the user with the Notify function. The
return value of If is the return value of
Notify , coerced to the same type as
the first argument to If (a boolean).
Simple IsBlankOrError
F O RM UL A DESC RIP T IO N RESULT
Simple Error
In this example, dates are validated relative to one another, resulting in an error if there is a problem.
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.
With( {a: 1, b: 0} )
IfError( a/b, If( FirstError.Kind <> ErrorKind.Div0, Error( FirstError ), -1 ) ) )
// 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:
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.
3. Set the formula for Label1 's Text property to:
IfError( Value( TextInput1.Text ), -1 )
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.
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 .
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 .
The return value for IsBlank is a boolean true or false .
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.
The return value for IsEmpty is a Boolean true or false .
Syntax
Blank ()
Coalesce ( Value1 [, Value2, ... ] )
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 )
Value – Required. Value to test for a blank value or empty string.
IsEmpty ( Table )
Table - Required. Table to test for records.
Examples
Blank
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.
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:
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
F O RM UL A DESC RIP T IO N RESULT
F O RM UL A DESC RIP T IO N RESULT
IsBlank
1. Create an app from scratch, add a text-input control, and name it FirstName .
2. Add a label, and set its Text property to this formula:
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 true
function, which always returns a blank
value.
IsBlank( Mid( "Hello", 17, 2 ) ) The starting character for Mid is true
beyond the end of the string. The
result is an empty string.
IsEmpty
1. Create an app from scratch, and add a Button control.
2. Set the button's OnSelect property to this formula:
Collect( IceCream, { Flavor : "Strawberr y", Quantity: 300 }, { Flavor : "Chocolate", Quantity:
100 } )
3. Preview your app, click or tap the button that you added, and then close Preview.
A collection named IceCream is created and contains this data:
This collection has two records and isn't empty. IsEmpty( IceCream ) returns false , and CountRows(
IceCream ) returns 2 .
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 collection is now empty:
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:
F O RM UL A DESC RIP T IO N RESULT
NOTE
Error, IfError, IsError, and IsBlankOrError functions are part of an experimental feature and are subject to change. More
information: Understand experimental, preview, and deprecated features in Power Apps.
The behavior that this article describes is available only when the Formula-level error management experimental
feature in Settings > Upcoming features > Experimental is turned on (off by default).
Your feedback is very valuable to us - please let us know what you think in the Power Apps community forums.
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:
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.
Stopping further processing
When chaining formulas together in behavior formulas, such as:
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:
IfError(
Patch( DS1, ... ), Notify( "problem in the first action" ),
Patch( DS2, ... ), Notify( "problem in the second action" )
)
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.
If supplied, the optional DefaultResult argument is returned if no errors are discovered. Without this argument,
the last Value argument is returned.
Building on the last example, the return value from IfError can be checked to determine if there were any
problems:
IfError(
Patch( DS1, ... ), Notify( "problem in the first action" ); false,
Patch( DS2, ... ), Notify( "problem in the second action" ); false,
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 .
NOTE
While the behavior in process for a change, the types of all arguments to IfError must be compatible currently.
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.
Excel will display #DIV/0! when a division by zero occurs.
Consider IfError with the following instead:
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:
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 ) .
Error records include:
F IEL D TYPE DESC RIP T IO N
For example, consider the following formula as a Button control's OnSelect property:
Set( a, 1/0 )
IfError( a, Notify( "Internal error: originated on " & FirstError.Source & ", surfaced on " &
FirstError.Observed ) )
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.
The return value is a Boolean true or false.
Using IsError will prevent any further processing of the error.
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 .
The return value is a boolean true or false.
Using IsBlankOrError will prevent any further processing of the error.
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 )
ErrorRecord – Required. Error information record, including Kind , Message , and other fields. Kind is
required. FirstError can be passed directly.
ErrorTable – Required. Table of error information records. AllErrors can be passed directly.
IfError ( Value1, Replacement1 [, Value2, Replacement2, ... [, DefaultResult ] ] )
Value(s) – Required. Formula(s) to test for an error value.
Replacement(s) – Required. The formulas to evaluate and values to return if matching Value arguments
returned an error.
DefaultResult – Optional. The formulas to evaluate if the formula doesn't find any errors.
IsError ( Value )
IsBlankOrError ( Value )
Value – Required. Formula to test.
Examples
Simple IfError
F O RM UL A DESC RIP T IO N RESULT
IfError( 10, 11, 20, 21, 300 ) The first argument 10 isn't an error, so 300
the function doesn't evaluate that
argument's corresponding replacement
11 . The third argument 20 isn't an
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( 1/0, Notify( "There was The first argument returns an error 1
an internal problem" ) ) value (due to division by zero). The
function evaluates the second
argument and displays a message to
the user. The return value of IfError is
the return value of Notify , coerced to
the same type as the first argument to
IfError (a number).
Simple IsError
F O RM UL A DESC RIP T IO N RESULT
If( IsError( 1/0 ), Notify( "There The argument to IsError returns an true
was an internal problem" ) ) error value (because of division by
zero). This function returns true, which
causes the If to display a message to
the user with the Notify function. The
return value of If is the return value of
Notify , coerced to the same type as
the first argument to If (a boolean).
Simple IsBlankOrError
F O RM UL A DESC RIP T IO N RESULT
Simple Error
In this example, dates are validated relative to one another, resulting in an error if there is a problem.
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.
With( {a: 1, b: 0} )
IfError( a/b, If( FirstError.Kind <> ErrorKind.Div0, Error( FirstError ), -1 ) ) )
// 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:
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.
3. Set the formula for Label1 's Text property to:
IfError( Value( TextInput1.Text ), -1 )
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 sub match or sub matches Text Each named sub-match will have its
own column. Create a named sub-
match by using (?< name > ...) in the
regular expression. If a named sub-
match has the same name as one of
the predefined columns (below), the
sub-match takes precedence, and a
warning is generated. To avoid this
warning, rename the sub-match.
SubMatches Single-column table of Text (column The table of named and unnamed sub-
Value ) matches in the order in which they
appear in the regular expression.
Generally, named sub-matches are
easier to work with and are
encouraged. Use the ForAll function
or Last ( FirstN( ... ) ) functions to
work with an individual sub-match. If
no sub-matches are defined in the
regular expression, this table will be
present but empty.
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:
Ordinary characters, such as "abc" or "123" .
Predefined patterns, such as Letter , MultipleDigits , or Email . (The Match enum defines these patterns.)
Regular-expression codes, such as "\d+\s+\d+" or "[a-z]+" .
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:
SP EC IA L C H A RA C T ER DESC RIP T IO N
. dot or period
? question mark
* asterisk
+ plus
() parentheses
[] square brackets
{} curly braces
^ caret
SP EC IA L C H A RA C T ER DESC RIP T IO N
$ 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:
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:
Named sub-matches: (?< name > ...)
Named backreferences: \k< name >
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 (& ).
BeginsWith The pattern must match from the Adds a ^ to the start of the regular
beginning of the text. expression.
Complete Default for IsMatch . The pattern must Adds a ^ to the start and a $ to the
match the entire string of text, from end of the regular expression.
beginning to end.
Contains Default for Match and MatchAll. The Doesn't modify the regular expression.
pattern must appear somewhere in the
text but doesn't need to begin or end
it.
M ATC H O P T IO N S EN UM DESC RIP T IO N IM PA C T O N A REGUL A R EXP RESSIO N
EndsWith The pattern must match the end of the Adds a $ to the end of the regular
string of text. expression.
IgnoreCase Treats uppercase and lowercase letters Doesn't modify the regular expression.
as identical. By default, matching is This option is the equivalent of the
case sensitive. standard "i" modifier for regular
expressions.
Multiline Matches across multiple lines. Doesn't modify the regular expression.
This option is the equivalent of the
standard "m" modifier for regular
expressions.
Using MatchAll is equivalent to using the standard "g" modifier for regular expressions.
Syntax
IsMatch ( Text, Pattern [, Options ] )
Text – Required. The text string to test.
Pattern – Required. The pattern to test as a text string. Concatenate predefined patterns that the Match enum
defines, or provide a regular expression. Pattern must be a constant formula without any variables, data
sources, or other dynamic references that change as the app runs.
Options – Optional. A text-string combination of MatchOptions enum values. By default,
MatchOptions.Complete is used.
Match ( Text, Pattern [, Options ] )
Text – Required. The text string to match.
Pattern – Required. The pattern to match as a text string. Concatenate predefined patterns that the Match
enum defines, or provide a regular expression. Pattern must be a constant formula without any variables,
data sources, or other dynamic references that change as the app runs.
Options – Optional. A text-string combination of MatchOptions enum values. By default,
MatchOptions.Contains is used.
MatchAll ( Text, Pattern [, Options ] )
Text – Required. The text string to match.
Pattern – Required. The pattern to match as a text string. Concatenate predefined patterns that the Match
enum defines, or provide a regular expression. Pattern must be a constant formula without any variables,
data sources, or other dynamic references that change as the app runs.
Options – Optional. A text-string combination of MatchOptions enum values. By default,
MatchOptions.Contains is used.
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.
The user types Hello world into TextInput1 .
F O RM UL A DESC RIP T IO N RESULT
IsMatch( TextInput1.Text, "Hello Tests whether the user's input matches, true
world" ) exactly, the string "Hello world".
IsMatch( TextInput1.Text, "Good Tests whether the user's input matches, false
bye" ) exactly, the string "Good bye".
Predefined patterns
F O RM UL A DESC RIP T IO N RESULT
IsMatch( "123-45-7890", Digit & Matches a United States Social Security true
Digit & Digit & Hyphen & Digit & Number
Digit & Hyphen & Digit & Digit &
Digit & Digit )
Regular expressions
F O RM UL A DESC RIP T IO N RESULT
IsMatch( "111-111-111", "\d{3}- Same as the previous example, but one false
\d{2}-\d{4}" ) of the hyphens is out of place in the
input.
Match( "Bob Jones Extracts only the email portion of the blank
<InvalidEmailAddress>", "<(? contact information. No legal address
<email>" & Match.Email & ")>"
is found (there is no @ sign), so the
function returns blank.
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:
With(
Match( "PT2H1M39S", "PT(?:(?<hours>\d+)H)?(?:(?<minutes>\d+)M)?(?:(?<seconds>\d+)S)?" ),
Time( Value( hours ), Value( minutes ), Value( seconds ) )
)
For these examples, add a Button control, set its OnSelect property to this formula, and then select the button:
Set( pangram, "The quick brown fox jumps over the lazy dog." )
Description
The IsNumeric function tests whether a value is numeric. Other kinds of values include Boolean, string, table,
and record.
The return value is a Boolean true or false .
Syntax
IsNumeric ( Value )
Value – Required. Value to test.
WeekNum and ISOWeekNum functions in Power
Apps
11/19/2022 • 2 minutes to read • Edit Online
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 ])
DateTime - Required. Date/Time value to operate on.
StartOfWeek - Optional. Excel code or StartOfWeek enumeration that determines which day the week begins.
ISOWeekNum (DateTime)
DateTime - Required. Date/Time value to operate on. The week always begins on Monday.
Examples
First and last calendar weeks of 2021
W EEK N UM ( DAT E,
STA RTO F W EEK . W EDN ESDAY
DAT E W EEK N UM ( DAT E ) ISO W EEK N UM ( DAT E ) )
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).
NOTE
UTCNow , UTCToday , and IsUTCToday are only available in Microsoft Dataverse for Teams formula columns, and
only for time-independent fields and values.
Now , Today , and IsToday are not available in Dataverse for Teams formula columns as evaluations are done without
the knowledge of the current user's local time zone.
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
Using the user's local time
Now ()
Today ()
IsToday ( DateTime )
DateTime - Required. The date/time value to test.
Using Coodinated Universal Time (UTC)
UTCNow ()
UTCToday ()
IsUTCToday ( TimeZoneIndependentTime )
TimeZoneIndependentDateTime - Required. The time zone indepdenent date/time value to test.
Examples
For the examples in this section, the current time is 8:58 PM on July 11, 2021 in the Pacific Time Zone (UTC-8)
and the language is en-us .
Text( Now(), "mm/dd/yyyy Retrieves the current date and time in "07/11/2021 20:58:00"
hh:mm:ss" ) the user's time zone, and displays it as
a string.
Text( Today(), "mm/dd/yyyy Retrieves the current date only, leaving "07/12/2021 00:00:00"
hh:mm:ss" ) the time portion as midnight, and
displays it as a string.
Text( DateAdd( Now(), 12 ), Retrieves the current date and time, "07/23/2021 20:58:00"
"mm/dd/yyyy hh:mm:ss" ) adds 12 days to the result, and
displays it as a string.
Text( DateAdd( Today(), 12 ), Retrieves the current date, adds 12 "07/23/2021 00:00:00"
"mm/dd/yyyy hh:mm:ss" ) days to the result, and displays it as a
string.
IsToday( DateAdd( Now(), 12 ) ) Tests whether the current date and false
time, plus 12 days, is between
midnight today and midnight
tomorrow.
IsToday( DateAdd( Today(), 12 ) ) Tests whether the current date, plus 12 false
days, is between midnight today and
midnight tomorrow.
F O RM UL A DESC RIP T IO N RESULT
3. Add a Label control, and set its Text property to this formula:
Text( CurrentTime, LongTime24 )
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 AutoStar t property to true and its Visible property to false .
The timer is invisible and starts automatically.
6. Set the screen's OnStar t 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
11/19/2022 • 4 minutes to read • Edit Online
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 ).'Primar y
Contact'.'Full Name' walks from the Accounts table to the Primar y 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.
LO O K UP F IEL D C A N REF ER TO
In canvas-app formulas, use record references to work with polymorphic lookups. Because a record reference
can refer to different tables, you don't know which fields will be available when you write a formula. The
Record.Field notation isn't available. Those formulas must adapt to the records that the app encounters when it
runs.
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:
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 :
Similarly, you can use record references with the Patch function:
Patch( Accounts, First( Accounts ), { Owner: First( Teams ) } )
If used in a record context, such as within a Galler y 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:
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.
IsType ( 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 for which to test.
Example
Understand record references and polymorphic lookups contains extensive examples.
1. Create a blank canvas app for tablets.
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 ver tical galler y .
4. Select Connect to data , and then select Contacts as the data source.
5. Set the gallery's layout to Title and subtitle .
6. In the Data pane, open the Title1 list, and then select Full Name .
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).
NOTE
UTCNow , UTCToday , and IsUTCToday are only available in Microsoft Dataverse for Teams formula columns, and
only for time-independent fields and values.
Now , Today , and IsToday are not available in Dataverse for Teams formula columns as evaluations are done without
the knowledge of the current user's local time zone.
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
Using the user's local time
Now ()
Today ()
IsToday ( DateTime )
DateTime - Required. The date/time value to test.
Using Coodinated Universal Time (UTC)
UTCNow ()
UTCToday ()
IsUTCToday ( TimeZoneIndependentTime )
TimeZoneIndependentDateTime - Required. The time zone indepdenent date/time value to test.
Examples
For the examples in this section, the current time is 8:58 PM on July 11, 2021 in the Pacific Time Zone (UTC-8)
and the language is en-us .
Text( Now(), "mm/dd/yyyy Retrieves the current date and time in "07/11/2021 20:58:00"
hh:mm:ss" ) the user's time zone, and displays it as
a string.
Text( Today(), "mm/dd/yyyy Retrieves the current date only, leaving "07/12/2021 00:00:00"
hh:mm:ss" ) the time portion as midnight, and
displays it as a string.
Text( DateAdd( Now(), 12 ), Retrieves the current date and time, "07/23/2021 20:58:00"
"mm/dd/yyyy hh:mm:ss" ) adds 12 days to the result, and
displays it as a string.
Text( DateAdd( Today(), 12 ), Retrieves the current date, adds 12 "07/23/2021 00:00:00"
"mm/dd/yyyy hh:mm:ss" ) days to the result, and displays it as a
string.
IsToday( DateAdd( Now(), 12 ) ) Tests whether the current date and false
time, plus 12 days, is between
midnight today and midnight
tomorrow.
IsToday( DateAdd( Today(), 12 ) ) Tests whether the current date, plus 12 false
days, is between midnight today and
midnight tomorrow.
F O RM UL A DESC RIP T IO N RESULT
3. Add a Label control, and set its Text property to this formula:
Text( CurrentTime, LongTime24 )
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 AutoStar t property to true and its Visible property to false .
The timer is invisible and starts automatically.
6. Set the screen's OnStar t 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
11/19/2022 • 6 minutes to read • Edit Online
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:
Specify the optional Format argument to control how readable the result is and how unsupported and binary
data types are handled. By default, the output is as compact as possible with no unnecessary spaces or newlines,
and unsupported data types and binary data aren't allowed. You can combine multiple formats if you specify the
& operator.
IncludeBinar yData The result includes image, video, and audio-clip columns.
This format can dramatically increase the result's size and
degrade your app's performance.
JSO N F O RM AT EN UM DESC RIP T IO N
IgnoreUnsuppor tedTypes Unsupported data types are allowed, but the result won't
include them. By default, unsupported data types produce
an error.
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 ] )
DataStructure – Required. The data structure to convert to JSON. Tables, records, and primitive values are
supported, arbitrarily nested.
Format - Optional. JSONFormat enum value. The default value is Compact , which doesn't add newlines or
spaces and blocks binary data and unsupported columns.
Examples
Hierarchical data
1. Insert a Button control, and set its OnSelect property to this formula.
ClearCollect( CityPopulations,
{ City: "London", Country: "United Kingdom", Population: 8615000 },
{ City: "Berlin", Country: "Germany", Population: 3562000 },
{ City: "Madrid", Country: "Spain", Population: 3165000 },
{ City: "Hamburg", Country: "Germany", Population: 1760000 },
{ City: "Barcelona", Country: "Spain", Population: 1602000 },
{ City: "Munich", Country: "Germany", Population: 1494000 }
);
ClearCollect( CitiesByCountry, GroupBy( CityPopulations, "Country", "Cities" ) )
3. Insert another button, and set its OnSelect property to this formula:
This formula sets the global variable CitiesByCountr yJSON to the JSON representation for
CitiesByCountr y .
4. Select the button while holding down the Alt key.
5. Insert a Label control, and set its Text property to this variable.
CitiesByCountryJSON
The label shows this result, all on a single line with no spaces, suitable for transmission across a network:
[
{
"Cities": [{ "City": "London", "Population": 8615000 }],
"Country": "United Kingdom"
},
{
"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"
}
]
6. Change the second button's formula to make the output more readable.
7. Select the second button while holding down the Alt key.
The label shows the more readable result.
[
{
"Cities": [
{
"City": "London",
"Population": 8615000
}
],
"Country": "United Kingdom"
},
{
"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"
}
]
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.
"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjxzdmcgdmVyc2lvbj0iMS
4xIg0KCSB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk
5L3hsaW5rIiB4bWxuczphPSJodHRwOi8vbnMuYWRvYmUuY29tL0Fkb2JlU1ZHVmlld2VyRXh0ZW5zaW9ucy8zLjAvIg0KCSB4PSIw
cHgiIHk9IjBweCIgd2lkdGg9IjI3MHB4IiBoZWlnaHQ9IjI3MHB4IiBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDAgMCAyNzAgMjcwI
iB4bWw6c3BhY2U9InByZXNlcnZlIj4NCgk8ZyBjbGFzcz0ic3QwIj4NCgkJPHJlY3QgeT0iMC43IiBmaWxsPSIjRTlFOUU5IiB3aW
R0aD0iMjY5IiBoZWlnaHQ9IjI2OS4zIi8+DQoJCTxwb2x5Z29uIGZpbGw9IiNDQkNCQ0EiIHBvaW50cz0iMjc3LjksMTg3LjEgMjQ
1LDE0My40IDE4OC42LDIwMi44IDc1LDgwLjUgLTQuMSwxNjUuMyAtNC4xLDI3MiAyNzcuOSwyNzIiLz4NCgkJPGVsbGlwc2UgZmls
bD0iI0NCQ0JDQSIgY3g9IjIwMi40IiBjeT0iODQuMSIgcng9IjI0LjQiIHJ5PSIyNC4zIi8+DQoJPC9nPg0KPC9zdmc+"
Language function in Power Apps
11/19/2022 • 4 minutes to read • Edit Online
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:
"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.
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.
F O RM UL A LO C AT IO N RET URN VA L UE
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.
1. Create the following table in Excel:
The entry with blank for the Language column will be used as the default if there is no specific text
string found for a given language. This entry must appear after all other entries for a given TextID .
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 Inser t 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.
3. Save the Excel file to your local file system.
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:
LookUp( Table1, TextID = "Hello" && (LanguageTag = Left( Language(), 2 ) || IsBlank(
LanguageTag ))).LocalizedText
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:
MicrosoftTranslator.Translate( "Hello", Language() )
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
11/19/2022 • 2 minutes to read • Edit Online
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 Last function returns the last record of a table.
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 )
Table - Required. Table to operate on.
FirstN ( Table [, NumberOfRecords ] )
LastN ( Table [, NumberOfRecords ] )
Table - Required. Table to operate on.
NumberOfRecords - Optional. Number of records to return. If you don't specify this argument, the function
returns one record.
Index ( Table, RecordIndex )
Table - Required. Table to operate on.
RecordIndex - Required. The index of the record to return. Record numbering begins with 1.
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):
First( IceCream ) Returns the first record of IceCream . { Flavor: "Chocolate", Quantity: 100 }
Last( IceCream ) Returns the last record of IceCream . { Flavor: "Pistachio", Quantity: 200 }
Index( IceCream, 3 ) Returns the third record of IceCream . { Flavor: "Strawberry", Quantity: 300 }
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 Last function returns the last record of a table.
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 )
Table - Required. Table to operate on.
FirstN ( Table [, NumberOfRecords ] )
LastN ( Table [, NumberOfRecords ] )
Table - Required. Table to operate on.
NumberOfRecords - Optional. Number of records to return. If you don't specify this argument, the function
returns one record.
Index ( Table, RecordIndex )
Table - Required. Table to operate on.
RecordIndex - Required. The index of the record to return. Record numbering begins with 1.
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):
First( IceCream ) Returns the first record of IceCream . { Flavor: "Chocolate", Quantity: 100 }
Last( IceCream ) Returns the last record of IceCream . { Flavor: "Pistachio", Quantity: 200 }
Index( IceCream, 3 ) Returns the third record of IceCream . { Flavor: "Strawberry", Quantity: 300 }
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.
Launch can only be used in behavior formulas.
Address
Webpages are launched via a URL address. For example:
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.
2. Select Apps from left navigation pane.
3. Select your app.
4. Select Details from top menu.
You can also select ... (More Commands ) and then select Details from the drop-down menu.
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:
An argument list of name value pairs. For example:
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.
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.
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, ... ] )
Address – Required. The address of a webpage or the ID of an app to launch.
ParameterName(s) – Optional. Parameter name.
ParameterValue(s) – Optional. Corresponding parameter values to pass to the app or the webpage.
Launch ( Address, { [ ParameterName1: ParameterValue1, ... ] } [, LaunchTarget ] )
Address – Required. The address of a webpage or the ID of an app to launch.
ParameterName(s) – Optional. Parameter name.
ParameterValue(s) – Optional. Corresponding parameter values to pass to the app or the webpage.
LaunchTarget – Optional. A LaunchTarget enum value or a custom name.
Param ( ParameterName )
ParameterName - Required. The name of the parameter passed to the app.
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:
F O RM UL A DESC RIP T IO N
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 )
F O RM UL A DESC RIP T IO N
Launch( "http://bing.com/search", The same as the previous example, creating or replacing the
{ q: "Power Apps", count: 1 }, contents of the window or tab named Search Results .
"Search Results" )
Launch( "/providers/Microsoft.PowerApps/apps/YOUR-APP-ID",
{ Navigate: "Second Screen", Record: 34 }
)
<html>
<body>
<a
href="https://apps.powerapps.com/play/YOUR-APP-ID?tenantId=YOUR-TENANT-
ID&Navigate=Second%20Screen&Record=34"
>
Launch canvas app
</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:
TIP
For scalability, you can replace the manually entered keywords in Launch function with variables.
Example - Param
1. Go to Power Apps.
2. Select Apps from left navigation pane.
3. Select your app and then select Edit .
4. Select Inser t from the menu and then select Label .
5. Move the label to the bottom right of the screen.
6. Select Text property for the label from top left.
7. Enter formula as Param("browser") . You can also use a different parameter of your choice.
8. Save and publish the app.
9. Copy web link for your app from Power Apps.
10. Open a new browser.
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.
If function in OnStart property checks if parameter equals a certain value, in this case the value techspecs.
And if it matches, the app navigates to TechSpecs screen.
NOTE
Replace TechSpecs screen name in the Navigate function with name of a screen in your own app if you're not
using the Product Showcase app template.
20. The app directly launches with TechSpecs or a screen you entered in Navigate function.
See also
Canvas app formula reference
Left, Mid, and Right functions in Power Apps
11/19/2022 • 2 minutes to read • Edit Online
Description
The Left , Mid , and Right functions return a portion of a string.
Left returns the beginning characters of a string.
Mid returns the middle characters of a string.
Right returns the ending characters 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 of 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 )
Mid ( String, StartingPosition [, NumberOfCharacters ] )
Right ( String, NumberOfCharacters )
String - Required. The string to from which to extract the result.
StartingPosition - Required (Mid only). The starting position. The first character of the string is position 1.
NumberOfCharacters - Required (Left and Right only). The number of characters to return. If omitted for the
Mid function, the function returns the portion from the starting position until the end of the string.
Left ( SingleColumnTable, NumberOfCharacters )
Mid ( SingleColumnTable, StartingPosition [, NumberOfCharacters ] )
Right ( SingleColumnTable, NumberOfCharacters )
SingleColumnTable - Required. A single-column table of strings from which to extract the results.
StartingPosition - Required (Mid only). The starting position. The first character of the string is position 1.
NumberOfCharacters - Required (Left and Right only). The number of characters to return. If omitted for the
Mid function, the function returns the portion from the starting position until the end of the string.
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".
F O RM UL A DESC RIP T IO N RESULT
Step-by-step example
1. Import or create a collection named Inventor y , 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
11/19/2022 • 2 minutes to read • Edit Online
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 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.
If you specify a blank string, Len returns 0.
Syntax
Len ( String )
String - Required. The string to measure.
Len ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of strings to measure.
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( [ "Hello", "to the", "World", In the Value column of the inline
"" ] ) table:
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
11/19/2022 • 2 minutes to read • Edit Online
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 Ln function returns the natural logarithm (base e) of its argument.
The Power function returns a number raised to a power. It is 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 Sqr t 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, 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. This can happen, for example, with
square roots and logarithms of negative numbers.
Syntax
Abs ( Number )
Exp ( Number )
Ln ( Number )
Sqr t ( Number )
Number - Required. Number to operate on.
Power ( Base, Exponent )
Base - Required. Base number to raise.
Exponent - Required. The exponent to which the base number is raised.
Log ( Number, Base )
Number - Required. Number to calculate the logarithm.
Base - Optional. The base of the logarithm to calculate. By default, 10 (when not specified).
Abs ( SingleColumnTable )
Exp ( SingleColumnTable )
Ln ( SingleColumnTable )
Sqr t ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of numbers to operate on.
Examples
Single number
F O RM UL A DESC RIP T IO N RESULT
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:
Sqr t( Value( Source.Text ) )
3. Type a number into Source , and confirm that the Label control shows the square root of the number that
you typed.
SaveData, LoadData, and ClearData functions in
Power Apps
11/19/2022 • 7 minutes to read • Edit Online
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.
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.
Syntax
SaveData ( Collection, Name )
LoadData ( Collection, Name [, IgnoreNonexistentFile ])
Collection - Required. Collection to be stored or loaded.
Name - Required. Name of the storage. The name must be same to save and load same set of data. The name
space isn't shared with other apps or users. Names must not contain any of these characters: *".?:\<>|/ .
IgnoreNonexistentFile - Optional. A Boolean value indicating what to do if the file doesn't already exist. Use
false (default) to return an error and true to suppress the error.
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
F O RM UL A DESC RIP T IO N RESULT
SaveData( LocalCache, "MyCache" Save the LocalCache collection to the Data is saved to the app host under
) user's device under the name the name "MyCache".
"MyCache", suitable for LoadData to
retrieve later.
LoadData( LocalCache, Loads the LocalCache collection from Data is loaded from the app host
"MyCache" ) the user's device under the name under the name "MyCache".
"MyCache", previously stored with a
call to SaveData .
ClearData( "MyCache" ) Clears the storage under the name Data is removed from the app host
"MyCache". Any data stored under this under the name "MyCache".
name will no longer be available
through LoadData .
ClearData() Clear all storage associated with this All data is removed from the app host.
app. Data stored by other apps is not
affected.
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:
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:
9. Add a third Button control.
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:
12. Add a Galler y 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 Galler y 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.
14. Position the control to the right of the other controls:
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.
More advanced offline example
For a detailed example, see the article on simple offline capabilities.
Acceleration, App, Compass, Connection, and
Location signals in Power Apps
11/19/2022 • 4 minutes to read • Edit Online
Returns information about the app's environment, such as where the user is located in the world and which
screen is displayed.
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).
App
Among other properties, the App object includes a signal that indicates which screen is showing.
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.
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.
As the location changes, dependencies on the location will continuously recalculate, which will consume power
from the device's battery. To conserve battery life, you can use the Enable and Disable functions to turn
location updates on and off. Location is automatically turned off if the displayed screen doesn't depend on
location information.
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 8.2, while the pitcher throws the
front to back. The pitcher initially gives device.
the device a large acceleration when
throwing the device, going from 0 to 0, while the device is in the air.
90 miles per hour (132 feet per
second) in half a second. After the -8.2, as the catcher catches the device.
device is in the air, ignoring air friction,
the device doesn't accelerate further.
The device decelerates when the
catcher catches it, bringing it to a stop.
Acceleration.Z Returns the acceleration of the device 0, before the pitcher throws the device.
top to bottom. While in the air, the
device experiences the effects of 1, while the device is in the air.
gravity.
0, after the catcher catches the device.
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 Galler y 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 Galler y may not be the
complete story, which could be confusing to users.
See the delegation overview for more information.
Syntax
Filter (Table*, Formula1 [, *Formula2*, ... ] )
Table - Required. Table to search.
Formula(s) - Required. The formula by which each record of the table is evaluated. The function returns all
records that result in true . You can reference columns within the table. If you supply more than one formula,
the results of all formulas are combined with the And function.
Search (Table*, SearchString, Column1 [, *Column2*, ... ] )
Table - Required. Table to search.
SearchString - Required. The string to search for. If blank or an empty string, all records are returned.
Column(s) - Required. The names of columns within Table to search. Columns to search must contain text.
Column names must be strings and enclosed in double quotes. However, the column names must be static
and cannot be calculated with a formula. If SearchString is found within the data of any of these columns as a
partial match, the full record will be returned.
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 following examples use the IceCream data source:
LookUp(IceCream, Flavor = Searches for a record with Flavor { Flavor: "Vanilla", Quantity: 200,
"Vanilla") equal to "Vanilla", of which there is OnOrder: 75 }
one. Since no reduction formula was
supplied, the entire record is returned.
8. Now select Galler y control and set the Items property to the following formula:
Filter(Accounts,
'Industry' = ComboBox3.Selected.Industry||IsBlank(ComboBox3.Selected.Industry),
'Relationship Type' = ComboBox2.Selected.'Relationship Type'||
IsBlank(ComboBox2.Selected.'Relationship Type'),
'Preferred Method of Contact' = ComboBox1.Selected.'Preferred Method of Contact'||
IsBlank(ComboBox1.Selected.'Preferred Method of Contact'))
To create this data source as a collection, create a Button control and set its OnSelect property to this formula:
ClearCollect(Customers, Table({ Name: "Fred Garcia", Company: "Nor thwind Traders" }, { Name:
"Cole Miller", Company: "Contoso" }, { Name: "Glenda Johnson", Company: "Contoso" }, { Name:
"Mike Collins", Company: "Adventure Works" }, { Name: "Colleen Jones", Company: "Adventure
Works" }) )
As in this example, you can show a list of records in a Galler y 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:
You can expand your search to include the Company column and the Name column:
F O RM UL A DESC RIP T IO N RESULT
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.
Lower converts any uppercase letters to lowercase.
Upper converts any lowercase letters to uppercase.
Proper converts the first letter in each word to uppercase if it's lowercase and converts any other uppercase
letters to lowercase.
All three functions ignore characters that aren't letters.
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 )
String - Required. The string to convert.
Lower ( SingleColumnTable )
Upper ( SingleColumnTable )
Proper ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of strings to convert.
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 "E. E. Cummings"
to uppercase if it's lowercase, and
converts any other uppercase letters
to lowercase.
Single -column table
The examples in this section convert strings from the Address column of the People data source, which
contains this data:
Each formula returns a single-column table that contains the converted strings.
Step-by-step example
1. Add a Text input control, and name it Source .
2. Add a label, and set its Text property to this function:
Proper(Source.Text)
3. Press F5, and then type WE ARE THE BEST! into the Source box.
The label shows We Are The Best!
IsMatch, Match, and MatchAll functions in Power
Apps
11/19/2022 • 12 minutes to read • Edit Online
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 sub match or sub matches Text Each named sub-match will have its
own column. Create a named sub-
match by using (?< name > ...) in the
regular expression. If a named sub-
match has the same name as one of
the predefined columns (below), the
sub-match takes precedence, and a
warning is generated. To avoid this
warning, rename the sub-match.
SubMatches Single-column table of Text (column The table of named and unnamed sub-
Value ) matches in the order in which they
appear in the regular expression.
Generally, named sub-matches are
easier to work with and are
encouraged. Use the ForAll function
or Last ( FirstN( ... ) ) functions to
work with an individual sub-match. If
no sub-matches are defined in the
regular expression, this table will be
present but empty.
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:
Ordinary characters, such as "abc" or "123" .
Predefined patterns, such as Letter , MultipleDigits , or Email . (The Match enum defines these patterns.)
Regular-expression codes, such as "\d+\s+\d+" or "[a-z]+" .
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:
SP EC IA L C H A RA C T ER DESC RIP T IO N
. dot or period
? question mark
* asterisk
+ plus
() parentheses
[] square brackets
{} curly braces
^ caret
SP EC IA L C H A RA C T ER DESC RIP T IO N
$ 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:
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:
Named sub-matches: (?< name > ...)
Named backreferences: \k< name >
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 (& ).
BeginsWith The pattern must match from the Adds a ^ to the start of the regular
beginning of the text. expression.
Complete Default for IsMatch . The pattern must Adds a ^ to the start and a $ to the
match the entire string of text, from end of the regular expression.
beginning to end.
Contains Default for Match and MatchAll. The Doesn't modify the regular expression.
pattern must appear somewhere in the
text but doesn't need to begin or end
it.
M ATC H O P T IO N S EN UM DESC RIP T IO N IM PA C T O N A REGUL A R EXP RESSIO N
EndsWith The pattern must match the end of the Adds a $ to the end of the regular
string of text. expression.
IgnoreCase Treats uppercase and lowercase letters Doesn't modify the regular expression.
as identical. By default, matching is This option is the equivalent of the
case sensitive. standard "i" modifier for regular
expressions.
Multiline Matches across multiple lines. Doesn't modify the regular expression.
This option is the equivalent of the
standard "m" modifier for regular
expressions.
Using MatchAll is equivalent to using the standard "g" modifier for regular expressions.
Syntax
IsMatch ( Text, Pattern [, Options ] )
Text – Required. The text string to test.
Pattern – Required. The pattern to test as a text string. Concatenate predefined patterns that the Match enum
defines, or provide a regular expression. Pattern must be a constant formula without any variables, data
sources, or other dynamic references that change as the app runs.
Options – Optional. A text-string combination of MatchOptions enum values. By default,
MatchOptions.Complete is used.
Match ( Text, Pattern [, Options ] )
Text – Required. The text string to match.
Pattern – Required. The pattern to match as a text string. Concatenate predefined patterns that the Match
enum defines, or provide a regular expression. Pattern must be a constant formula without any variables,
data sources, or other dynamic references that change as the app runs.
Options – Optional. A text-string combination of MatchOptions enum values. By default,
MatchOptions.Contains is used.
MatchAll ( Text, Pattern [, Options ] )
Text – Required. The text string to match.
Pattern – Required. The pattern to match as a text string. Concatenate predefined patterns that the Match
enum defines, or provide a regular expression. Pattern must be a constant formula without any variables,
data sources, or other dynamic references that change as the app runs.
Options – Optional. A text-string combination of MatchOptions enum values. By default,
MatchOptions.Contains is used.
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.
The user types Hello world into TextInput1 .
F O RM UL A DESC RIP T IO N RESULT
IsMatch( TextInput1.Text, "Hello Tests whether the user's input matches, true
world" ) exactly, the string "Hello world".
IsMatch( TextInput1.Text, "Good Tests whether the user's input matches, false
bye" ) exactly, the string "Good bye".
Predefined patterns
F O RM UL A DESC RIP T IO N RESULT
IsMatch( "123-45-7890", Digit & Matches a United States Social Security true
Digit & Digit & Hyphen & Digit & Number
Digit & Hyphen & Digit & Digit &
Digit & Digit )
Regular expressions
F O RM UL A DESC RIP T IO N RESULT
IsMatch( "111-111-111", "\d{3}- Same as the previous example, but one false
\d{2}-\d{4}" ) of the hyphens is out of place in the
input.
Match( "Bob Jones Extracts only the email portion of the blank
<InvalidEmailAddress>", "<(? contact information. No legal address
<email>" & Match.Email & ")>"
is found (there is no @ sign), so the
function returns blank.
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:
With(
Match( "PT2H1M39S", "PT(?:(?<hours>\d+)H)?(?:(?<minutes>\d+)M)?(?:(?<seconds>\d+)S)?" ),
Time( Value( hours ), Value( minutes ), Value( seconds ) )
)
For these examples, add a Button control, set its OnSelect property to this formula, and then select the button:
Set( pangram, "The quick brown fox jumps over the lazy dog." )
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 sub match or sub matches Text Each named sub-match will have its
own column. Create a named sub-
match by using (?< name > ...) in the
regular expression. If a named sub-
match has the same name as one of
the predefined columns (below), the
sub-match takes precedence, and a
warning is generated. To avoid this
warning, rename the sub-match.
SubMatches Single-column table of Text (column The table of named and unnamed sub-
Value ) matches in the order in which they
appear in the regular expression.
Generally, named sub-matches are
easier to work with and are
encouraged. Use the ForAll function
or Last ( FirstN( ... ) ) functions to
work with an individual sub-match. If
no sub-matches are defined in the
regular expression, this table will be
present but empty.
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:
Ordinary characters, such as "abc" or "123" .
Predefined patterns, such as Letter , MultipleDigits , or Email . (The Match enum defines these patterns.)
Regular-expression codes, such as "\d+\s+\d+" or "[a-z]+" .
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:
SP EC IA L C H A RA C T ER DESC RIP T IO N
. dot or period
? question mark
* asterisk
+ plus
() parentheses
[] square brackets
{} curly braces
^ caret
SP EC IA L C H A RA C T ER DESC RIP T IO N
$ 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:
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:
Named sub-matches: (?< name > ...)
Named backreferences: \k< name >
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 (& ).
BeginsWith The pattern must match from the Adds a ^ to the start of the regular
beginning of the text. expression.
Complete Default for IsMatch . The pattern must Adds a ^ to the start and a $ to the
match the entire string of text, from end of the regular expression.
beginning to end.
Contains Default for Match and MatchAll. The Doesn't modify the regular expression.
pattern must appear somewhere in the
text but doesn't need to begin or end
it.
M ATC H O P T IO N S EN UM DESC RIP T IO N IM PA C T O N A REGUL A R EXP RESSIO N
EndsWith The pattern must match the end of the Adds a $ to the end of the regular
string of text. expression.
IgnoreCase Treats uppercase and lowercase letters Doesn't modify the regular expression.
as identical. By default, matching is This option is the equivalent of the
case sensitive. standard "i" modifier for regular
expressions.
Multiline Matches across multiple lines. Doesn't modify the regular expression.
This option is the equivalent of the
standard "m" modifier for regular
expressions.
Using MatchAll is equivalent to using the standard "g" modifier for regular expressions.
Syntax
IsMatch ( Text, Pattern [, Options ] )
Text – Required. The text string to test.
Pattern – Required. The pattern to test as a text string. Concatenate predefined patterns that the Match enum
defines, or provide a regular expression. Pattern must be a constant formula without any variables, data
sources, or other dynamic references that change as the app runs.
Options – Optional. A text-string combination of MatchOptions enum values. By default,
MatchOptions.Complete is used.
Match ( Text, Pattern [, Options ] )
Text – Required. The text string to match.
Pattern – Required. The pattern to match as a text string. Concatenate predefined patterns that the Match
enum defines, or provide a regular expression. Pattern must be a constant formula without any variables,
data sources, or other dynamic references that change as the app runs.
Options – Optional. A text-string combination of MatchOptions enum values. By default,
MatchOptions.Contains is used.
MatchAll ( Text, Pattern [, Options ] )
Text – Required. The text string to match.
Pattern – Required. The pattern to match as a text string. Concatenate predefined patterns that the Match
enum defines, or provide a regular expression. Pattern must be a constant formula without any variables,
data sources, or other dynamic references that change as the app runs.
Options – Optional. A text-string combination of MatchOptions enum values. By default,
MatchOptions.Contains is used.
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.
The user types Hello world into TextInput1 .
F O RM UL A DESC RIP T IO N RESULT
IsMatch( TextInput1.Text, "Hello Tests whether the user's input matches, true
world" ) exactly, the string "Hello world".
IsMatch( TextInput1.Text, "Good Tests whether the user's input matches, false
bye" ) exactly, the string "Good bye".
Predefined patterns
F O RM UL A DESC RIP T IO N RESULT
IsMatch( "123-45-7890", Digit & Matches a United States Social Security true
Digit & Digit & Hyphen & Digit & Number
Digit & Hyphen & Digit & Digit &
Digit & Digit )
Regular expressions
F O RM UL A DESC RIP T IO N RESULT
IsMatch( "111-111-111", "\d{3}- Same as the previous example, but one false
\d{2}-\d{4}" ) of the hyphens is out of place in the
input.
Match( "Bob Jones Extracts only the email portion of the blank
<InvalidEmailAddress>", "<(? contact information. No legal address
<email>" & Match.Email & ")>"
is found (there is no @ sign), so the
function returns blank.
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:
With(
Match( "PT2H1M39S", "PT(?:(?<hours>\d+)H)?(?:(?<minutes>\d+)M)?(?:(?<seconds>\d+)S)?" ),
Time( Value( hours ), Value( minutes ), Value( seconds ) )
)
For these examples, add a Button control, set its OnSelect property to this formula, and then select the button:
Set( pangram, "The quick brown fox jumps over the lazy dog." )
Description
The Average function calculates the average, or arithmetic mean, of its arguments.
The Max function finds the maximum value.
The Min function finds the minimum value.
The Sum function calculates the sum of its arguments.
The StdevP function calculates the standard deviation of its arguments.
The VarP function calculates the variance of its arguments.
You can supply the values for these functions as:
Separate arguments. For example, Sum( 1, 2, 3 ) returns 6.
A table and a formula to operate over that table. The aggregate will be calculated on the values of the
formula for each 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.
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, ... ] )
Max ( NumericalFormula1, [ NumericalFormula2, ... ] )
Min ( NumericalFormula1, [ NumericalFormula2, ... ] )
Sum ( NumericalFormula1, [ NumericalFormula2, ... ] )
StdevP ( NumericalFormula1, [ NumericalFormula2, ... ] )
VarP ( NumericalFormula1, [ NumericalFormula2, ... ] )
NumericalFormula(s) - Required. Numeric values to operate on.
Average ( Table, NumericalFormula )
Max ( Table, NumericalFormula )
Min ( Table, NumericalFormula )
Sum ( Table, NumericalFormula )
StdevP ( Table, NumericalFormula )
VarP ( Table, NumericalFormula )
Table - Required. Table to operate on.
NumericalFormula - Required. Formula to evaluate for each record. The result of this formula is used for the
aggregation. You can use columns of the table in the formula.
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:
Sum(Sales, CostPerUnit * UnitsSold)
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.
Average(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the average of all values to
which the sliders were set.
Max(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the maximum of all values to
which the sliders were set.
Min(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the minimum of all values to which
the sliders were set.
StdevP(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the standard deviation of all
values to which the sliders were set.
VarP(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the variance of all values to which
the sliders were set.
Left, Mid, and Right functions in Power Apps
11/19/2022 • 2 minutes to read • Edit Online
Description
The Left , Mid , and Right functions return a portion of a string.
Left returns the beginning characters of a string.
Mid returns the middle characters of a string.
Right returns the ending characters 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 of 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 )
Mid ( String, StartingPosition [, NumberOfCharacters ] )
Right ( String, NumberOfCharacters )
String - Required. The string to from which to extract the result.
StartingPosition - Required (Mid only). The starting position. The first character of the string is position 1.
NumberOfCharacters - Required (Left and Right only). The number of characters to return. If omitted for the
Mid function, the function returns the portion from the starting position until the end of the string.
Left ( SingleColumnTable, NumberOfCharacters )
Mid ( SingleColumnTable, StartingPosition [, NumberOfCharacters ] )
Right ( SingleColumnTable, NumberOfCharacters )
SingleColumnTable - Required. A single-column table of strings from which to extract the results.
StartingPosition - Required (Mid only). The starting position. The first character of the string is position 1.
NumberOfCharacters - Required (Left and Right only). The number of characters to return. If omitted for the
Mid function, the function returns the portion from the starting position until the end of the string.
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".
F O RM UL A DESC RIP T IO N RESULT
Step-by-step example
1. Import or create a collection named Inventor y , 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
11/19/2022 • 2 minutes to read • Edit Online
Description
The Average function calculates the average, or arithmetic mean, of its arguments.
The Max function finds the maximum value.
The Min function finds the minimum value.
The Sum function calculates the sum of its arguments.
The StdevP function calculates the standard deviation of its arguments.
The VarP function calculates the variance of its arguments.
You can supply the values for these functions as:
Separate arguments. For example, Sum( 1, 2, 3 ) returns 6.
A table and a formula to operate over that table. The aggregate will be calculated on the values of the
formula for each 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.
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, ... ] )
Max ( NumericalFormula1, [ NumericalFormula2, ... ] )
Min ( NumericalFormula1, [ NumericalFormula2, ... ] )
Sum ( NumericalFormula1, [ NumericalFormula2, ... ] )
StdevP ( NumericalFormula1, [ NumericalFormula2, ... ] )
VarP ( NumericalFormula1, [ NumericalFormula2, ... ] )
NumericalFormula(s) - Required. Numeric values to operate on.
Average ( Table, NumericalFormula )
Max ( Table, NumericalFormula )
Min ( Table, NumericalFormula )
Sum ( Table, NumericalFormula )
StdevP ( Table, NumericalFormula )
VarP ( Table, NumericalFormula )
Table - Required. Table to operate on.
NumericalFormula - Required. Formula to evaluate for each record. The result of this formula is used for the
aggregation. You can use columns of the table in the formula.
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:
Sum(Sales, CostPerUnit * UnitsSold)
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.
Average(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the average of all values to
which the sliders were set.
Max(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the maximum of all values to
which the sliders were set.
Min(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the minimum of all values to which
the sliders were set.
StdevP(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the standard deviation of all
values to which the sliders were set.
VarP(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the variance of all values to which
the sliders were set.
Day, Month, Year, Hour, Minute, Second, and
Weekday functions in Power Apps
11/19/2022 • 2 minutes to read • Edit Online
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 )
DateTime - Required. Date/Time value to operate on.
Weekday ( DateTime [, WeekdayFirst ] )
DateTime - Required. Date/Time value to operate on.
WeekdayFirst - Optional. Excel code specifying which day starts the week. If not supplied, 1 (Sunday first) is
used.
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.
The result has the same sign as the divisor.
Syntax
Mod ( Number, Divisor )
Number - Required. Number to divide.
Divisor - Required. Number to divide by.
Day, Month, Year, Hour, Minute, Second, and
Weekday functions in Power Apps
11/19/2022 • 2 minutes to read • Edit Online
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 )
DateTime - Required. Date/Time value to operate on.
Weekday ( DateTime [, WeekdayFirst ] )
DateTime - Required. Date/Time value to operate on.
WeekdayFirst - Optional. Excel code specifying which day starts the week. If not supplied, 1 (Sunday first) is
used.
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 Star tScreen property to control the first screen to be displayed.
You can use either function only within a behavior formula.
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.
Navigate ( Screen [, Transition [, UpdateContextRecord ] ] )
Screen - Required. The screen to display.
Transition - Optional. The visual transition to use between the current screen and the next screen. See the list
of valid values for this argument earlier in this article. The default value is None .
UpdateContextRecord - Optional. A record that contains the name of at least one column and a value for each
column. This record updates the context variables of the new screen as if passed to the UpdateContext
function.
Examples
F O RM UL A DESC RIP T IO N RESULT
Navigate( Details ) Displays the Details screen with no The Details screen appears quickly.
transition or change in value for a
context variable.
Navigate( Details, Displays the Details screen with a The current screen fades away to show
ScreenTransition.Fade ) Fade transition. No value of a context the Details screen.
variable is changed.
Navigate( Details, Displays the Details screen with a The current screen fades away to show
ScreenTransition.Fade, { ID: 12 } ) Fade transition, and updates the value the Details screen, and the context
of the ID context variable to 12 . variable ID on that screen is set to 12 .
Navigate( Details, Displays the Details screen with a The current screen fades away to show
ScreenTransition.Fade, Fade transition. Updates the value of the Details screen. The context
{ ID: 12 , Shade: Color.Red } ) the ID context variable to 12 , and variable ID on the Details screen is
updates the value of the Shade set to 12 , and the context variable
context variable to Color.Red . Shade is set to Color.Red . If you set
the Fill property of a control on the
Details screen to Shade , that control
would display as red.
Back() Displays the previous screen with the Displays the previous screen through
default return transition. the inverse transition of the transition
through which the current screen
appeared.
Back( ScreenTransition.Cover ) Displays the previous screen with the Displays the previous screen through
Cover transition. the Cover transition, regardless of the
transition through which the current
screen appeared.
Step-by-step
1. Create a blank app.
2. Add a second screen to it.
The app contains two blank screens: Screen1 and Screen2 .
3. Set the Fill property of Screen2 to the value Gray .
4. On Screen2 , add a button, and set its OnSelect property to this formula:
Back()
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:
M O DE DESC RIP T IO N
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.
These functions return no values.
You can use these functions only in behavior formulas.
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 validation passes, SubmitForm submits the change to the data source.
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):
Syntax
SubmitForm ( FormName )
FormName - Required. Form control to submit to the data source.
EditForm ( FormName )
FormName - Required. Form control to switch to FormMode.Edit mode.
NewForm ( FormName )
FormName - Required. Form control to switch to FormMode.New mode.
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 )
FormName - Required. Form control to switch to FormMode.View mode.
Examples
See Understand data forms for complete examples.
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:
ResetForm( EditForm ); Back()
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:
NewForm( EditForm ); Navigate( EditScreen, None )
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
11/19/2022 • 2 minutes to read • Edit Online
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 Or function returns true if any 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, ... ] )
Or ( LogicalFormula1, LogicalFormula2 [, LogicalFormula3, ... ] )
Not ( LogicalFormula )
LogicalFormula(s) - Required. Logical formulas to evaluate and operate on.
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:
Set( a, false ); Set( b, true ); Set( x, 10 ); Set( y, 100 ); Set( s, "Hello World" )
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.
Len( s ) < 20 And Not IsBlank( s ) Tests whether the length of s is less true
than 20 and whether it isn't a blank
value. The length is less than 20, and
the value isn't blank. Therefore, the
result is true.
Or( Len( s ) < 10, x < 100, Tests whether the length of s is less true
y < 100 ) than 10, whether x is less than 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.
Description
The Notify function displays a banner message to the user at the top of the screen, overlaying what is currently
displayed. The notification will remain until the user dismisses it, another notification replaces 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:
NOTE
The character limit for Notify function is 500 characters.
Messages are shown both when authoring your app and when end users are using your app.
Notify can only be used in behavior formulas.
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.
Notify always returns true.
Note: This function was previously named ShowError when it could only display error messages.
Syntax
Notify ( Message [, NotificationType [ , Timeout ] ] )
Message – Required. Message to display to the user.
NotificationType – Optional. Type of the message to display from the table above. The default is
NotificationType.Information .
Timeout – Optional. Number of milliseconds to wait before automatically dismissing the notification. The
default is 10 seconds (or 10,000 milliseconds). The notification will be displayed indefinitely with a Timeout
of 0.
Examples
Step by step
1. Add a Button control to your screen.
2. Set the OnSelect property of the Button to the formula:
4. Change the type of message to indicate an error. Add a second argument to our formula:
6. Change the type of message to indicate a warning. Change the second argument in our formula:
8. Change the type of message to indicate success. Change the second argument in our formula:
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).
NOTE
UTCNow , UTCToday , and IsUTCToday are only available in Microsoft Dataverse for Teams formula columns, and
only for time-independent fields and values.
Now , Today , and IsToday are not available in Dataverse for Teams formula columns as evaluations are done without
the knowledge of the current user's local time zone.
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
Using the user's local time
Now ()
Today ()
IsToday ( DateTime )
DateTime - Required. The date/time value to test.
Using Coodinated Universal Time (UTC)
UTCNow ()
UTCToday ()
IsUTCToday ( TimeZoneIndependentTime )
TimeZoneIndependentDateTime - Required. The time zone indepdenent date/time value to test.
Examples
For the examples in this section, the current time is 8:58 PM on July 11, 2021 in the Pacific Time Zone (UTC-8)
and the language is en-us .
Text( Now(), "mm/dd/yyyy Retrieves the current date and time in "07/11/2021 20:58:00"
hh:mm:ss" ) the user's time zone, and displays it as
a string.
Text( Today(), "mm/dd/yyyy Retrieves the current date only, leaving "07/12/2021 00:00:00"
hh:mm:ss" ) the time portion as midnight, and
displays it as a string.
Text( DateAdd( Now(), 12 ), Retrieves the current date and time, "07/23/2021 20:58:00"
"mm/dd/yyyy hh:mm:ss" ) adds 12 days to the result, and
displays it as a string.
Text( DateAdd( Today(), 12 ), Retrieves the current date, adds 12 "07/23/2021 00:00:00"
"mm/dd/yyyy hh:mm:ss" ) days to the result, and displays it as a
string.
IsToday( DateAdd( Now(), 12 ) ) Tests whether the current date and false
time, plus 12 days, is between
midnight today and midnight
tomorrow.
IsToday( DateAdd( Today(), 12 ) ) Tests whether the current date, plus 12 false
days, is between midnight today and
midnight tomorrow.
F O RM UL A DESC RIP T IO N RESULT
3. Add a Label control, and set its Text property to this formula:
Text( CurrentTime, LongTime24 )
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 AutoStar t property to true and its Visible property to false .
The timer is invisible and starts automatically.
6. Set the screen's OnStar t 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
11/19/2022 • 12 minutes to read • Edit Online
Some of these operators are dependent on the language of the author. For more information about language
support in canvas apps, see Global apps.
* 2*3 Multiplication
& String concatenation "hello" & " " & "world" Makes multiple strings
operator appear continuous
&& or And Logical operators Price < 100 && Logical conjunction,
Slider1.Value = 20 equivalent to the And
or Price < 100 And function
Slider1.Value = 20
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')
ThisRecord ForAll, Filter , With , Sum and other The default name for the current
record scope functions record in ForAll and other record
scope functions.
ThisItem operator
For example, in the following Galler y control, the Items property is set to the Employees data source (such as
the Employees table included with the Northwind Traders sample):
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:
ThisItem.Picture
Likewise, the formula for the name also uses ThisItem :
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:
ThisRecord is optional and implied by using the fields directly, for example, in this case, we could have written:
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:
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:
Employees As Employee
The formulas for the picture and name are adjusted to use this name for the current record:
Employee.Picture
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:
Concat(
ForAll( Sequence(8) As Rank,
Concat(
ForAll( Sequence(8) As File,
If( Mod(Rank.Value + File.Value, 2) = 1, " X ", " . " )
),
Value
) & Char(10)
),
Value
)
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:
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:
M ET H O D DESC RIP T IO N
M ET H O D DESC RIP T IO N
Parent operator Some controls host other controls, such as the Screen and
Galler y controls. The 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.
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
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 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.
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).
For more information and examples, see record scopes.
And, Or, and Not functions in Power Apps
11/19/2022 • 2 minutes to read • Edit Online
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 Or function returns true if any 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, ... ] )
Or ( LogicalFormula1, LogicalFormula2 [, LogicalFormula3, ... ] )
Not ( LogicalFormula )
LogicalFormula(s) - Required. Logical formulas to evaluate and operate on.
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:
Set( a, false ); Set( b, true ); Set( x, 10 ); Set( y, 100 ); Set( s, "Hello World" )
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.
Len( s ) < 20 And Not IsBlank( s ) Tests whether the length of s is less true
than 20 and whether it isn't a blank
value. The length is less than 20, and
the value isn't blank. Therefore, the
result is true.
Or( Len( s ) < 10, x < 100, Tests whether the length of s is less true
y < 100 ) than 10, whether x is less than 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.
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.
Launch can only be used in behavior formulas.
Address
Webpages are launched via a URL address. For example:
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.
2. Select Apps from left navigation pane.
3. Select your app.
4. Select Details from top menu.
You can also select ... (More Commands ) and then select Details from the drop-down menu.
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:
An argument list of name value pairs. For example:
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.
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.
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, ... ] )
Address – Required. The address of a webpage or the ID of an app to launch.
ParameterName(s) – Optional. Parameter name.
ParameterValue(s) – Optional. Corresponding parameter values to pass to the app or the webpage.
Launch ( Address, { [ ParameterName1: ParameterValue1, ... ] } [, LaunchTarget ] )
Address – Required. The address of a webpage or the ID of an app to launch.
ParameterName(s) – Optional. Parameter name.
ParameterValue(s) – Optional. Corresponding parameter values to pass to the app or the webpage.
LaunchTarget – Optional. A LaunchTarget enum value or a custom name.
Param ( ParameterName )
ParameterName - Required. The name of the parameter passed to the app.
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:
F O RM UL A DESC RIP T IO N
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 )
F O RM UL A DESC RIP T IO N
Launch( "http://bing.com/search", The same as the previous example, creating or replacing the
{ q: "Power Apps", count: 1 }, contents of the window or tab named Search Results .
"Search Results" )
Launch( "/providers/Microsoft.PowerApps/apps/YOUR-APP-ID",
{ Navigate: "Second Screen", Record: 34 }
)
<html>
<body>
<a
href="https://apps.powerapps.com/play/YOUR-APP-ID?tenantId=YOUR-TENANT-
ID&Navigate=Second%20Screen&Record=34"
>
Launch canvas app
</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:
TIP
For scalability, you can replace the manually entered keywords in Launch function with variables.
Example - Param
1. Go to Power Apps.
2. Select Apps from left navigation pane.
3. Select your app and then select Edit .
4. Select Inser t from the menu and then select Label .
5. Move the label to the bottom right of the screen.
6. Select Text property for the label from top left.
7. Enter formula as Param("browser") . You can also use a different parameter of your choice.
8. Save and publish the app.
9. Copy web link for your app from Power Apps.
10. Open a new browser.
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.
If function in OnStart property checks if parameter equals a certain value, in this case the value techspecs.
And if it matches, the app navigates to TechSpecs screen.
NOTE
Replace TechSpecs screen name in the Navigate function with name of a screen in your own app if you're not
using the Product Showcase app template.
20. The app directly launches with TechSpecs or a screen you entered in Navigate function.
See also
Canvas app formula reference
Operators and Identifiers in Power Apps
11/19/2022 • 12 minutes to read • Edit Online
Some of these operators are dependent on the language of the author. For more information about language
support in canvas apps, see Global apps.
* 2*3 Multiplication
& String concatenation "hello" & " " & "world" Makes multiple strings
operator appear continuous
&& or And Logical operators Price < 100 && Logical conjunction,
Slider1.Value = 20 equivalent to the And
or Price < 100 And function
Slider1.Value = 20
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')
ThisRecord ForAll, Filter , With , Sum and other The default name for the current
record scope functions record in ForAll and other record
scope functions.
ThisItem operator
For example, in the following Galler y control, the Items property is set to the Employees data source (such as
the Employees table included with the Northwind Traders sample):
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:
ThisItem.Picture
Likewise, the formula for the name also uses ThisItem :
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:
ThisRecord is optional and implied by using the fields directly, for example, in this case, we could have written:
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:
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:
Employees As Employee
The formulas for the picture and name are adjusted to use this name for the current record:
Employee.Picture
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:
Concat(
ForAll( Sequence(8) As Rank,
Concat(
ForAll( Sequence(8) As File,
If( Mod(Rank.Value + File.Value, 2) = 1, " X ", " . " )
),
Value
) & Char(10)
),
Value
)
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:
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:
M ET H O D DESC RIP T IO N
M ET H O D DESC RIP T IO N
Parent operator Some controls host other controls, such as the Screen and
Galler y controls. The 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.
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
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 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.
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).
For more information and examples, see record scopes.
ParseJSON function in Power Apps (experimental)
11/19/2022 • 6 minutes to read • Edit Online
IMPORTANT
This is an experimental feature.
Experimental features aren’t meant for production use and may have restricted functionality. These features are
available before an official release so that customers can get early access and provide feedback. More information:
Understand experimental, preview, and deprecated features in Power Apps
The behavior that this article describes is available only when the ParseJSON function and untyped objects
experimental feature in Settings > Upcoming features > Experimental is turned on (off by default).
Your feedback is very valuable to us - please let us know what you think in the Power Apps experimental features
community forum.
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 )
JSONString – Required. The JSON structure represented as text.
Date, DateTime, Time { "start": "2022-05- JSON doesn't have a date DateValue( ParseJSON("{
10" } or time type so can only ""appointment"":
{ "start": represent dates and times ""2022-05-10""
"23:12:49.000" }
as strings. An untyped }").appointment )
object can be directly DateValue( Text(
converted from a string in ParseJSON("{
ISO 8601 format to a date, ""appointment"": ""May
time or datetime. For other 5, 2022""
formats, first convert the }").appointment ) )
JSON field to text using the
Text() function and then use
the DateValue(), TimeValue()
or DateTimeValue() function
that by default will use the
language of the current
user's settings.
HyperLink, Image, Media { "URI": These data types are text Text( ParseJSON("{
"https://northwindtraders.com/logo.jpg"
data types, and can be ""URI"":
}
converted to text and then ""https://nor thwindtrad
used in Power Apps. ers.com/logo.jpg""
}").URI )
Two options { "available": true } Two options are presented Switch( Boolean(
{ "available": "Yes" } as localized strings, backed ParseJSON( "{
by a boolean. The JSON() ""available"": true }"
function serializes a two ).available ), false,
options to its boolean Availability.No, true,
value. There's no direct Availability.Yes )
conversion from boolean,
number or string to a two
options, but the Switch() or
If() functions can be used
on the text, number or
boolean value.
Examples
Accessing field values
Given the following JSON string in a variable named JsonString
Blanks
Given the following JSON string in a variable named JsonString
1. Attempting to access non-existing fields returns Blank() . The following formula returns true :
2. JSON null values are considered Blank() . The following formula returns true :
Simple Arrays
Given the following JSON string in a variable named JsonString
{ "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 :
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 } :
Arrays of Records
Given the following JSON string in a variable named JsonString
{ "array": [
{ "id": 1, "name": "One"},
{ "id": 2, "name": "Two"}
] }
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:
ForAll( ParseJSON( JsonString ).array, { id: Value(ThisRecord.id), name: Text(ThisRecord.name) })
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.
Given the following JSON string in a variable named JsonString
{ "array": [1, 2, 3] }
Table() returns a single-column table of untyped objects with a single-column Value for number in the array...
Table() returns a single-column table of untyped objects that represents each json object in the array.
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.
Watch this video to learn how to use the Patch function:
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:
Patch( Customers, First( Filter( Customers, Name = "Contoso" ) ), { Phone: "1-212-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:
Patch( Customers, Defaults( Customers ), { Name: "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:
Patch( { Name: "Contoso", Phone: "1-212-555-1234" }, { Name: "Contoso", Location: "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.
For example, you use Set(MyAccount, Patch(Accounts, First(Account), 'Account Name': "Example name")); and
then MyAccount.'Primary Contact'.'Full Name' . You can't yield a full name in this case. Instead, to access the
fields of a related table, use a separate lookup such as:
When you update a data source, one or more issues may arise. 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.
Modify or create a set of records in a data source
Patch can also be used to create or modify multiple records with a single call.
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.
Merge records outside of a data source
Specify two or more records that you want to merge. Records are processed in the order from the beginning of
the argument list to the end, with later property values overriding earlier ones.
Patch returns the merged record and doesn't modify its arguments or records in any data sources.
Syntax
Modify or create a record in a data source
Patch ( DataSource, BaseRecord, ChangeRecord1 [, ChangeRecord2, … ])
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.
Modify or create a set of records in a data source
Patch ( DataSource, BaseRecordsTable, ChangeRecordTable1 [, ChangeRecordTable2, … ] )
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
Patch ( Record1, Record2 [, …] )
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
Modify or create a record (in a data source)
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, Creates a record in the IceCream data { ID: 3, Flavor: "Strawberry",
Defaults( IceCream ), source: Quantity: 0 }
{ Flavor : "Strawberr y" } ) The ID column contains the
value 3 , which the data source The Strawberr y entry in the
generates automatically. IceCream data source has been
The Quantity column contains created.
0 , which is the default value for
that column in the IceCream
data source, as the Defaults
function specifies.
The Flavor column contains
the value of Strawberr y .
After the previous formulas have been evaluated, the data source ends with these values:
Patch( { Name: "James", Score: 90 Merges two records outside of a data { Name: "Jim", Score: 90, Passed: true }
}, { Name: "Jim", Passed: true } ) source:
The values in the Name
column of each record don't
match. The result contains the
value (Jim ) in the record that's
closer to the end of the
argument list instead of the
value (James ) in the record
that's closer to the start.
The first record contains a
column (Score ) that doesn't
exist in the second record. The
result contains that column
with its value (90 ).
The second record contains a
column (Passed ) that doesn't
exist in the first record. The
result contains that column
with its value (true ).
Use of As or ThisRecord
Using the As or ThisRecord keyword in the formula avoids ambiguous evaluation context.
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.)
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.
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"
}
)
)
)
To learn more about the usage of As operator and ThisRecord see Operators article.
PDF function in Power Apps (experimental)
11/19/2022 • 3 minutes to read • Edit Online
IMPORTANT
This is an experimental feature.
Experimental features aren't meant for production use and may have restricted functionality. These features are
available before an official release so that customers can get early access and provide feedback. More
information: Understand experimental, preview, and retired features in canvas apps
The behavior that this article describes is available only when the PDF function experimental feature in Settings >
Upcoming features > Experimental is turned on (it's off by default).
Your feedback is valuable to us. Please let us know what you think in the Power Apps experimental features
community forum .
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.
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.
DPI – Optional. Controls the scaling/resolution of the generated PDF. Must be a value greater than 0.
Content exceeding the space allowed by the specified margins may result in a higher effective DPI. The
default value is 96.
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).
ExpandContainers – Optional. Boolean. Controls whether certain containers with contents that exceed
their allocated size expand to display all content in the generated PDF. Impacted controls include screens,
containers, vertical and horizontal containers, vertical fixed-height galleries (not nested), forms, and
scrollable canvas controls. The default value is false.
Examples
F O RM UL A DESC RIP T IO N RESULT
PDF(Screen1) Generates a PDF object with the A PDF object is created from the visible
default settings. contents of Screen1.
PDF(Container1, {Size: A3}) Generates a PDF object with the paper An A3-sized PDF object is created from
size set to A3. the visible contents of Container1.
PDF(Screen1, {DPI: 72, Margin: Generates a PDF object with the A PDF with the specified DPI, margin,
"25mm", Orientation: resolution (DPI) set to 72, the margin and orientation is created in the
"Landscape"}) set to 25 millimeters, and the default size (dependent on locale) from
orientation set to landscape the visible content on Screen1.
(horizontal).
PDF(Screen1, {ExpandContainers: Generates a PDF object with applicable A PDF is created where any
true}) controls expanded. containers/galleries with more content
than is visible are expanded to show all
content in the generated PDF.
Known limitations
Certain controls aren't currently supported. These include charts, Power BI tile, Map, and some
configurations of third-party PCF controls.
Nested Galleries aren't supported.
Non-Latin script types and font weights and styles such as bold and italic may not appear in the
generated PDF for some fonts.
Creation of fillable PDFs isn't supported.
Acos, Acot, Asin, Atan, Atan2, Cos, Cot, Degrees, Pi,
Radians, Sin, and Tan functions in Power Apps
11/19/2022 • 4 minutes to read • Edit Online
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.
The Pi function returns the transcendental number π, which begins 3.141592...
The Radians function converts degrees to radians.
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, 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 )
Radians - Required. Angle to operate on.
Cos ( SingleColumnTable )
Cot ( SingleColumnTable )
Sin ( SingleColumnTable )
Tan ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of angles to operate on.
Inverse Functions
Acos ( Number )
Acot ( Number )
Asin ( Number )
Atan ( Number )
Number - Required. Number to operate on.
Acos ( SingleColumnTable )
Acot ( SingleColumnTable )
Asin ( SingleColumnTable )
Atan ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of numbers to operate on.
Atan2 ( X, Y )
X - Required. X-axis coordinate.
Y - Required. Y-axis coordinate.
Helper Functions
Degrees ( Radians )
Radians - Required. Angle in radians to convert to degrees.
Pi ()
Radians ( Degrees )
Degrees - Required. Angle in degrees to convert to radians.
Examples
Single number
F O RM UL A DESC RIP T IO N RESULT
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 )
String - Required. URL to be encoded.
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:
<p>
We have done an unusually "deep" globalization and
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 Ln function returns the natural logarithm (base e) of its argument.
The Power function returns a number raised to a power. It is 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 Sqr t 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, 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. This can happen, for example, with
square roots and logarithms of negative numbers.
Syntax
Abs ( Number )
Exp ( Number )
Ln ( Number )
Sqr t ( Number )
Number - Required. Number to operate on.
Power ( Base, Exponent )
Base - Required. Base number to raise.
Exponent - Required. The exponent to which the base number is raised.
Log ( Number, Base )
Number - Required. Number to calculate the logarithm.
Base - Optional. The base of the logarithm to calculate. By default, 10 (when not specified).
Abs ( SingleColumnTable )
Exp ( SingleColumnTable )
Ln ( SingleColumnTable )
Sqr t ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of numbers to operate on.
Examples
Single number
F O RM UL A DESC RIP T IO N RESULT
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:
Sqr t( Value( Source.Text ) )
3. Type a number into Source , and confirm that the Label control shows the square root of the number that
you typed.
Print function in Power Apps
11/19/2022 • 2 minutes to read • Edit Online
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.
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.
2. Select Apps from the left navigation pane.
3. Select your app or create an app from scratch.
4. Select Inser t from the menu and then select Button .
5. From the property list on the top left, select OnSelect .
6. Enter the formula Print() .
7. Save and publish the app.
8. Play the app.
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.
Hide controls while printing
To enable more customizable content, you can access the screen when the screen is printing to the change
properties of the canvas app. For example, hiding buttons, or changing a form to view mode.
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.
Use a screen template
An easy way to get started is to use a screen template to size your print to the letter size.
Open or create a new canvas app.
Select New Screen and select Por trait print option.
Observe that the screen is sized differently from other screens with the print button on the top-right
corner.
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
11/19/2022 • 2 minutes to read • Edit Online
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.
Lower converts any uppercase letters to lowercase.
Upper converts any lowercase letters to uppercase.
Proper converts the first letter in each word to uppercase if it's lowercase and converts any other uppercase
letters to lowercase.
All three functions ignore characters that aren't letters.
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 )
String - Required. The string to convert.
Lower ( SingleColumnTable )
Upper ( SingleColumnTable )
Proper ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of strings to convert.
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 "E. E. Cummings"
to uppercase if it's lowercase, and
converts any other uppercase letters
to lowercase.
Single -column table
The examples in this section convert strings from the Address column of the People data source, which
contains this data:
Each formula returns a single-column table that contains the converted strings.
Step-by-step example
1. Add a Text input control, and name it Source .
2. Add a label, and set its Text property to this function:
Proper(Source.Text)
3. Press F5, and then type WE ARE THE BEST! into the Source box.
The label shows We Are The Best!
Acos, Acot, Asin, Atan, Atan2, Cos, Cot, Degrees, Pi,
Radians, Sin, and Tan functions in Power Apps
11/19/2022 • 4 minutes to read • Edit Online
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.
The Pi function returns the transcendental number π, which begins 3.141592...
The Radians function converts degrees to radians.
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, 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 )
Radians - Required. Angle to operate on.
Cos ( SingleColumnTable )
Cot ( SingleColumnTable )
Sin ( SingleColumnTable )
Tan ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of angles to operate on.
Inverse Functions
Acos ( Number )
Acot ( Number )
Asin ( Number )
Atan ( Number )
Number - Required. Number to operate on.
Acos ( SingleColumnTable )
Acot ( SingleColumnTable )
Asin ( SingleColumnTable )
Atan ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of numbers to operate on.
Atan2 ( X, Y )
X - Required. X-axis coordinate.
Y - Required. Y-axis coordinate.
Helper Functions
Degrees ( Radians )
Radians - Required. Angle in radians to convert to degrees.
Pi ()
Radians ( Degrees )
Degrees - Required. Angle in degrees to convert to radians.
Examples
Single number
F O RM UL A DESC RIP T IO N RESULT
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 .
The RandBetween function returns a pseudo-random integer (whole number with no decimal portion) that is
between two numbers, inclusive. For example, RandBetween( 1, 3 ) may return 1 , 2 , or 3 .
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() * 100 Building on the previous example, uses Varies with each evaluation, for
multiplication to extend the range to example 78.42521 .
greater than or equal to 0 and less
than 100.
Int( Rand() * 100 ) Building on the previous example, uses Varies with each evaluation, for
the Int function to remove the decimal example 84 .
portion, resulting in an integer greater
than or equal to 0 and less than 100
RandBetween( 0, 99 ) Building on the previous example, Varies with each evaluation, for
performs the same operation using the example 21 .
RandBetween function
RandBetween( -1, 1 ) Returns a pseudo-random number Varies with each evaluation, for
that is between -1 and 1 inclusive: -1 , example -1 .
0 , or 1 .
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:
Create a table of random numbers with RandBetween
1. Add a Button control, and set its OnSelect property to this formula:
ClearCollect( RandomNumbers, ForAll( Sequence( 100 ), RandBetween( 1, 20 ) ))
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:
4. Select the button again to show a different list of random numbers:
To generate a single random number instead of a table, use Set( RandomNumber, Rand() ) or Set(
RandNumber, RandBetween( 1, 20 ) ) .
Rand and RandBetween functions in Power Apps
11/19/2022 • 3 minutes to read • Edit Online
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 .
The RandBetween function returns a pseudo-random integer (whole number with no decimal portion) that is
between two numbers, inclusive. For example, RandBetween( 1, 3 ) may return 1 , 2 , or 3 .
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() * 100 Building on the previous example, uses Varies with each evaluation, for
multiplication to extend the range to example 78.42521 .
greater than or equal to 0 and less
than 100.
Int( Rand() * 100 ) Building on the previous example, uses Varies with each evaluation, for
the Int function to remove the decimal example 84 .
portion, resulting in an integer greater
than or equal to 0 and less than 100
RandBetween( 0, 99 ) Building on the previous example, Varies with each evaluation, for
performs the same operation using the example 21 .
RandBetween function
RandBetween( -1, 1 ) Returns a pseudo-random number Varies with each evaluation, for
that is between -1 and 1 inclusive: -1 , example -1 .
0 , or 1 .
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:
Create a table of random numbers with RandBetween
1. Add a Button control, and set its OnSelect property to this formula:
ClearCollect( RandomNumbers, ForAll( Sequence( 100 ), RandBetween( 1, 20 ) ))
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:
4. Select the button again to show a different list of random numbers:
To generate a single random number instead of a table, use Set( RandomNumber, Rand() ) or Set(
RandNumber, RandBetween( 1, 20 ) ) .
ReadNFC function in Power Apps
11/19/2022 • 3 minutes to read • Edit Online
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.
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.
Additional RTD and TNF values may be supported in the future. If more values are supported, additional
payload columns will also be added. The raw RTD and TNF values are provided for informational purposes and
don't need to be consulted if the payload column is checked for blank. More information about these values and
their use is available through the NFC Forum.
ReadNFC doesn't require a tag containing NDEF records to be used, but you may still get the tag identifier if
one is available.
ReadNFC can only be used in behavior formulas.
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
F O RM UL A DESC RIP T IO N RESULT
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:
With(ReadNFC(),
Set(id, Coalesce(Identifier, "No ID"));
ForAll(NDEFRecords, Collect(tagRecords, {ID: id, Value: Coalesce(Text, URI)})))
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.
5. Add a Galler y control with a vertical layout.
6. When prompted, select the tagRecords collection as the data source for this gallery. This action will set
the Items property of the Galler y 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.
9. Save and publish the app.
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
11/19/2022 • 2 minutes to read • Edit Online
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?
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 )
Record – Required. The record to test.
Information – Required. The desired information for the record.
Examples
RecordInfo( First(Accounts), RecordInfo.EditPermission )
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.
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.
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.
Collect( MyCollection, [ 1, 2, 3 ] );
RecordInfo( First(MyCollection), RecordInfo.DeletePermission )
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
11/19/2022 • 2 minutes to read • Edit Online
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 )
DataSource – Required. The data source that you want to refresh.
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 Strawberr y 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 Strawberr y :
Relate and Unrelate functions in Power Apps
11/19/2022 • 9 minutes to read • Edit Online
Relate and unrelate records of two tables through a one-to-many or many-to-many relationship.
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.
You can use these functions only in behavior formulas.
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 )
Table1RelatedTable - Required. For a record of Table1, the table of Table2 records related through a one-to-
many or many-to-many relationship.
Table2Record - Required. The Table2 record to add to the relationship.
Unrelate ( Table1RelatedTable, Table2Record )
Table1RelatedTable - Required. For a record of Table1, the table of Table2 records related through a one-to-
many or many-to-many relationship.
Table2Record - Required. The Table2 record to remove from the relationship.
Examples
Consider a Products table with the following relationships as seen in the Power Apps portal's table viewer:
REL AT IO N SH IP DISP L AY N A M E REL AT ED TA B L E REL AT IO N SH IP T Y P E
Products and Reser vations are related through a One-to-Many relationship. To relate the first record of the
Reser vations table with the first record of the Products table:
Relate( First( Products ).Reservations, First( Reservations ) )
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:
Relate( First( Products ).Contacts, First( Contacts ) )
As Many-to-Many relationships are symmetric, we could also have done this in the opposite direction:
Relate( First( Contacts ).Products, First( Products ) )
or:
Unrelate( First( Contacts ).Products, First( Products ) )
The walk through that follows does exactly these operations on these tables using an app with Galler y 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.
1. Create a tablet app from blank.
2. On the View tab, select Data sources .
3. In the Data pane, select Add data > select Products .
The Products table is part of the sample data loaded above.
4. On the Inser t tab, add a blank vertical Galler y control.
5. Ensure that the control that you just added is named Galler y1 , and then move and resize it to fill the left-
hand side of the screen.
6. On the Proper ties tab, set Galler y1 's Items property to Products and its Layout to Image and title .
7. In Galler y1 , 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 Galler y1 . Add a second blank vertical Galler y
control, and ensure that it's named Galler y2 .
Galler y2 will show the reservations for whatever product the user selects in Galler y1 .
9. Move and resize Galler y2 to fill the upper-right quadrant of the screen.
10. (optional) Add the blue Label control above Galler y2 , as the next graphic shows.
11. In the formula bar, set the Items property of Galler y2 to Galler y1.Selected.Reser vations .
15. Scroll down in the Proper ties tab and set ComboBox1 's Allow multiple selection property to Off .
16. In the formula bar, set ComboBox1 's DefaultSelectedItems property to ThisItem.'Product
Reser vation' .
17. In Galler y2 , set NextArrow2 's OnSelect property to this formula:
When the user selects this icon, the current reservation changes to the product that the user selected in
ComboBox1 .
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 Galler y2_1 where users can assign each contact to
a product.
Many-to -many
Create a many-to-many relationship
The sample data doesn't include a many-to-many relationship, but you'll create one between the Products table
and the Contacts table. Users can relate each product to more than one contact and each contact to more than
one product.
1. From this page, select Data in the left navigation bar, and then select Tables .
2. Change the table filter to include all tables.
By default, sample tables don't appear.
5. In Galler y2 , 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 .
7. Set the Cancel icon's OnSelect property to this formula:
11. On the Proper ties tab, set Allow multiple selection to Off .
12. Insert an Add icon, and set its OnSelect property to this formula:
3. To create the reverse view, change these formulas on the controls of Screen1_1 :
Screen1_1.OnVisible = Refresh( Contacts )
Gallery1_1.Items = Contacts
Title1_1.Text = ThisItem.'Full Name'
Label1_1.Text = "Selected Contact Products"
Gallery2_1.Items = Gallery1_1.Selected.Products
Title2_1.Text = ThisItem.Name
Icon1_1.OnSelect = Unrelate( Gallery1_1.Selected.Products, ThisItem )
ComboBox1_1.Items = Products
Icon2_1.OnSelect = Relate( Gallery1_1.Selected.Products, ComboBox1_1.Selected )
The result will look very similar to the previous screen but comes at the relationship from the Contacts
side.
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
11/19/2022 • 6 minutes to read • Edit Online
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 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, ... ] [, 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.
All – Optional. In a collection, the same record may appear more than once. You can add the All argument to
remove all copies of the record.
Remove ( DataSource, Table [, All ] )
DataSource – Required. The data source that contains the records that you want to remove.
Table – Required. A table of records to remove.
All – Optional. In a collection, the same record may appear more than once. You can add the All argument to
remove all copies of the record.
RemoveIf ( DataSource, Condition [, ... ] )
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.
Examples - single formulas
In these examples, you'll remove a record or records in a data source that's named IceCream and that starts
with the data in this table:
ClearCollect( IceCream,
{ ID: 1, Flavor: "Chocolate", Quantity: 100 },
{ ID: 2, Flavor: "Vanilla", Quantity: 200 },
{ ID: 3, Flavor: "Strawberry", Quantity: 300 }
)
8. Set the OnSelect property for this button control to the following formula:
Selecting the button removes the selected record (in this example, Nancy's record).
12. Close the app preview.
TIP
You can also use alternate behavior with Alt key instead of using the app preview with Play button or F5.
ClearCollect( SampleContacts,
{ 'Full Name': "Yvonne McKay (sample)", 'Primary Email': "[email protected]" },
{ 'Full Name': "Susanna Stubberod (sample)", 'Primary Email': "[email protected]" },
{ 'Full Name': "Nancy Anderson (sample)", 'Primary Email': "[email protected]" },
{ 'Full Name': "Maria Campbell (sample)", 'Primary Email': "[email protected]" },
{ 'Full Name': "Robert Lyon (sample)", 'Primary Email': "[email protected]" },
{ 'Full Name': "Paul Cannon (sample)", 'Primary Email': "[email protected]" },
{ 'Full Name': "Rene Valdes (sample)", 'Primary Email': "[email protected]" }
)
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:
Icon.Trash
NOTE
The Icon. prefix is only shown when you're actively editing the formula.
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:
The record is deleted:
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 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, ... ] [, 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.
All – Optional. In a collection, the same record may appear more than once. You can add the All argument to
remove all copies of the record.
Remove ( DataSource, Table [, All ] )
DataSource – Required. The data source that contains the records that you want to remove.
Table – Required. A table of records to remove.
All – Optional. In a collection, the same record may appear more than once. You can add the All argument to
remove all copies of the record.
RemoveIf ( DataSource, Condition [, ... ] )
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.
Examples - single formulas
In these examples, you'll remove a record or records in a data source that's named IceCream and that starts
with the data in this table:
ClearCollect( IceCream,
{ ID: 1, Flavor: "Chocolate", Quantity: 100 },
{ ID: 2, Flavor: "Vanilla", Quantity: 200 },
{ ID: 3, Flavor: "Strawberry", Quantity: 300 }
)
8. Set the OnSelect property for this button control to the following formula:
Selecting the button removes the selected record (in this example, Nancy's record).
12. Close the app preview.
TIP
You can also use alternate behavior with Alt key instead of using the app preview with Play button or F5.
ClearCollect( SampleContacts,
{ 'Full Name': "Yvonne McKay (sample)", 'Primary Email': "[email protected]" },
{ 'Full Name': "Susanna Stubberod (sample)", 'Primary Email': "[email protected]" },
{ 'Full Name': "Nancy Anderson (sample)", 'Primary Email': "[email protected]" },
{ 'Full Name': "Maria Campbell (sample)", 'Primary Email': "[email protected]" },
{ 'Full Name': "Robert Lyon (sample)", 'Primary Email': "[email protected]" },
{ 'Full Name': "Paul Cannon (sample)", 'Primary Email': "[email protected]" },
{ 'Full Name': "Rene Valdes (sample)", 'Primary Email': "[email protected]" }
)
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:
Icon.Trash
NOTE
The Icon. prefix is only shown when you're actively editing the formula.
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:
The record is deleted:
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.
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 formula is evaluated for each record of the table.
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 DropColumns function excludes columns from a table. All other columns remain unmodified.
DropColumns excludes columns, and ShowColumns includes columns.
Use the RenameColumns function to rename one or more columns of a table by providing at least one
argument pair that specifies the name of a column that the table contains (the old name, which you want to
replace) and the name of a column that the table doesn't contain (the new name, which you want to use). The
old name must already exist in the table, and the new name must not exist. Each column name may appear only
once in the argument list as either an old column name or a new column name. To rename a column to an
existing column name, first drop the existing column with DropColumns , or rename the existing column out of
the way by nesting one RenameColumns function within another.
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:
AddColumns( RealEstateAgents,
"Listings",
Filter( '[dbo].[AllListings]', ListingAgentName = AgentName )
)
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 OnStar t 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, ... ] )
Table - Required. Table to operate on.
ColumnName(s) - Required. Name(s) of the column(s) to add. You must specify a string (for example,
"Name" with double quotes included) for this argument.
Formula(s) - Required. Formula(s) to evaluate for each record. The result is added as the value of the
corresponding new column. You can reference other columns of the table in this formula.
DropColumns ( Table, ColumnName1 [, ColumnName2, ... ] )
Table - Required. Table to operate on.
ColumnName(s) - Required. Name(s) of the column(s) to drop. You must specify a string (for example,
"Name" with double quotes included) for this argument.
RenameColumns ( Table, OldColumnName1, NewColumnName1 [, OldColumnName2, NewColumnName2, ... ]
)
Table - Required. Table to operate on.
OldColumnName - Required. Name of a column to rename from the original table. This element appears first
in the argument pair (or first in each argument pair if the formula includes more than one pair). This name
must be a string (for example "Name" with double quotation marks included).
NewColumnName - Required. Replacement name. This element appears last in the argument pair (or last in
each argument pair if the formula includes more than one pair). You must specify a string (for example,
"Customer Name" with double quotation marks included) for this argument.
ShowColumns ( Table, ColumnName1 [, ColumnName2, ... ] )
Table - Required. Table to operate on.
ColumnName(s) - Required. Name(s) of the column(s) to include. You must specify a string (for example,
"Name" with double quotes included) for this argument.
Examples
The examples in this section use the IceCreamSales data source, which contains the data in this table:
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.
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:
ClearCollect( IceCreamSales,
Table(
{ Flavor: "Strawberry", UnitPrice: 1.99, QuantitySold: 20 },
{ Flavor: "Chocolate", UnitPrice: 2.99, QuantitySold: 45 },
{ Flavor: "Vanilla", UnitPrice: 1.50, QuantitySold: 35 }
)
)
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:
ClearCollect( FirstExample,
AddColumns( IceCreamSales, "Revenue", UnitPrice * QuantitySold )
)
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
11/19/2022 • 2 minutes to read • Edit Online
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 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 )
String - Required. The string to operate on.
StartingPosition - Required. Character position to start the replacement. The first character of String is at
position 1.
NumberOfCharacters - Required. The number of characters to replace in String.
NewString - Required. The replacement string. The number of characters in this argument can differ from the
NumberOfCharacters argument.
Substitute ( String, OldString, NewString [, InstanceNumber ] )
String - Required. The string to operate on.
OldString - Required. The string to replace.
NewString - Required. The replacement string. OldString and NewString can have different lengths.
InstanceNumber - Optional. Use this argument to specify which instance of OldString to replace if String
contains more than one instance. If you don't specify this argument, all instances will be replaced.
Replace ( SingleColumnTable, StartingPosition, NumberOfCharacters, NewString )
SingleColumnTable - Required. A single-column table of strings to operate on.
StartingPosition - Required. Character position to start the replacement. The first character of each string in
the table is at position 1.
NumberOfCharacters - Required. The number of characters to replace in each string.
NewString - Required. The replacement string. The number of characters in this argument can differ from the
NumberOfCharacters argument.
Substitute ( SingleColumnTable, OldString, NewString [, InstanceNumber ] )
SingleColumnTable - Required. A single-column table of strings to operate on.
OldString - Required. The string to replace.
NewString - Required. The replacement string. OldString and NewString can have different lengths.
InstanceNumber - Optional. Use this argument to specify which instance of OldString to replace if String
contains more than one instance. If you don't specify this argument, all instances will be replaced.
Examples
F O RM UL A DESC RIP T IO N RESULT
Substitute( "Sales Data", "Sales", " Substitutes the string "Cost" for "Cost Data"
Cost" ) "Sales".
Substitute( "Quar ter 1, 2018", Substitutes only the first instance of "Quarter 2, 2018"
"1", "2", 1 ) "1" with "2" because the fourth
argument (InstanceNumber) is
provided with a 1.
Substitute( "Quar ter 1, 2011", Substitutes only the third instance of "Quarter 1, 2012"
"1", "2", 3 ) "1" with "2" because the fourth
argument (InstanceNumber) is
provided with a 3.
Substitute( "Quar ter 1, 2011", Substitutes all instances of "1" with "2" "Quarter 2, 2022"
"1", "2" ) because the fourth argument
(InstanceNumber) isn't provided.
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 Galler y 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 )
Control – Required. The control to reset.
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
11/19/2022 • 5 minutes to read • Edit Online
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:
M O DE DESC RIP T IO N
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.
These functions return no values.
You can use these functions only in behavior formulas.
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 validation passes, SubmitForm submits the change to the data source.
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):
Syntax
SubmitForm ( FormName )
FormName - Required. Form control to submit to the data source.
EditForm ( FormName )
FormName - Required. Form control to switch to FormMode.Edit mode.
NewForm ( FormName )
FormName - Required. Form control to switch to FormMode.New mode.
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 )
FormName - Required. Form control to switch to FormMode.View mode.
Examples
See Understand data forms for complete examples.
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:
ResetForm( EditForm ); Back()
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:
NewForm( EditForm ); Navigate( EditScreen, None )
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
11/19/2022 • 2 minutes to read • Edit Online
Description
The Rever t 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, Rever t 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, Rever t the record to start with the
conflicting version and reapply the change.
Rever t has no return value. You can use it only in a behavior formula.
Syntax
Rever t ( DataSource [, Record ] )
DataSource – Required. The data source that you want to revert.
Record - Optional. The record that you want to revert. If you don't specify a record, the entire data source is
reverted.
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 Strawberr y 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:
Patch( IceCream, LookUp( IceCream, Flavor = "Strawberr y" ), { Quantity: 500 } )
You check the Errors table and find an error:
Based on the Error column, you have a Reload button for which the OnSelect property to set to this formula:
Rever t( IceCream, LookUp( IceCream, Flavor = "Strawberr y" ) )
After you select the Reload button, the Errors table is empty, and the new value for Strawberr y 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
11/19/2022 • 2 minutes to read • Edit Online
NOTE
Only works with SharePoint forms.
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
F O RM UL A DESC RIP T IO N
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 )
Untyped - Required. An Untyped object containing a string that represents a Cascading Style Sheet (CSS)
color definition.
RGBA ( Red, Green, Blue, Alpha )
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%.
ColorFade ( Color, FadeAmount )
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
C O LO R EN UM ERAT IO N C O LO RVA L UE RGB A C O LO R SWATC H
Description
The Left , Mid , and Right functions return a portion of a string.
Left returns the beginning characters of a string.
Mid returns the middle characters of a string.
Right returns the ending characters 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 of 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 )
Mid ( String, StartingPosition [, NumberOfCharacters ] )
Right ( String, NumberOfCharacters )
String - Required. The string to from which to extract the result.
StartingPosition - Required (Mid only). The starting position. The first character of the string is position 1.
NumberOfCharacters - Required (Left and Right only). The number of characters to return. If omitted for the
Mid function, the function returns the portion from the starting position until the end of the string.
Left ( SingleColumnTable, NumberOfCharacters )
Mid ( SingleColumnTable, StartingPosition [, NumberOfCharacters ] )
Right ( SingleColumnTable, NumberOfCharacters )
SingleColumnTable - Required. A single-column table of strings from which to extract the results.
StartingPosition - Required (Mid only). The starting position. The first character of the string is position 1.
NumberOfCharacters - Required (Left and Right only). The number of characters to return. If omitted for the
Mid function, the function returns the portion from the starting position until the end of the string.
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".
F O RM UL A DESC RIP T IO N RESULT
Step-by-step example
1. Import or create a collection named Inventor y , 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
11/19/2022 • 2 minutes to read • Edit Online
Rounds a number.
Greater than 0 The number is rounded to the right of Round( 12.37, 1 ) returns 12.4.
the decimal separator.
Less than 0 The number is rounded to the left of Round( 12.37, -1 ) returns 10.
the decimal separator.
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)
Number - Required. The number to round.
DecimalPlaces - Required. Number of decimal places to round to. Use a positive value to indicate decimal
places right of the decimal separator, a negative value to the left, and zero for a whole number.
Int (Number)
Trunc (Number)
Number - Required. The number to be rounded to an integer.
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).
ROUNDDOWN( X, [ 0, 1, 2
X INT( X ) ROUND( X, 2 ) ] ) ROUNDUP( X, [ 2 ] )
Rounds a number.
Greater than 0 The number is rounded to the right of Round( 12.37, 1 ) returns 12.4.
the decimal separator.
Less than 0 The number is rounded to the left of Round( 12.37, -1 ) returns 10.
the decimal separator.
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)
Number - Required. The number to round.
DecimalPlaces - Required. Number of decimal places to round to. Use a positive value to indicate decimal
places right of the decimal separator, a negative value to the left, and zero for a whole number.
Int (Number)
Trunc (Number)
Number - Required. The number to be rounded to an integer.
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).
ROUNDDOWN( X, [ 0, 1, 2
X INT( X ) ROUND( X, 2 ) ] ) ROUNDUP( X, [ 2 ] )
Rounds a number.
Greater than 0 The number is rounded to the right of Round( 12.37, 1 ) returns 12.4.
the decimal separator.
Less than 0 The number is rounded to the left of Round( 12.37, -1 ) returns 10.
the decimal separator.
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)
Number - Required. The number to round.
DecimalPlaces - Required. Number of decimal places to round to. Use a positive value to indicate decimal
places right of the decimal separator, a negative value to the left, and zero for a whole number.
Int (Number)
Trunc (Number)
Number - Required. The number to be rounded to an integer.
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).
ROUNDDOWN( X, [ 0, 1, 2
X INT( X ) ROUND( X, 2 ) ] ) ROUNDUP( X, [ 2 ] )
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.
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.
Syntax
SaveData ( Collection, Name )
LoadData ( Collection, Name [, IgnoreNonexistentFile ])
Collection - Required. Collection to be stored or loaded.
Name - Required. Name of the storage. The name must be same to save and load same set of data. The name
space isn't shared with other apps or users. Names must not contain any of these characters: *".?:\<>|/ .
IgnoreNonexistentFile - Optional. A Boolean value indicating what to do if the file doesn't already exist. Use
false (default) to return an error and true to suppress the error.
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
F O RM UL A DESC RIP T IO N RESULT
SaveData( LocalCache, "MyCache" Save the LocalCache collection to the Data is saved to the app host under
) user's device under the name the name "MyCache".
"MyCache", suitable for LoadData to
retrieve later.
LoadData( LocalCache, Loads the LocalCache collection from Data is loaded from the app host
"MyCache" ) the user's device under the name under the name "MyCache".
"MyCache", previously stored with a
call to SaveData .
ClearData( "MyCache" ) Clears the storage under the name Data is removed from the app host
"MyCache". Any data stored under this under the name "MyCache".
name will no longer be available
through LoadData .
ClearData() Clear all storage associated with this All data is removed from the app host.
app. Data stored by other apps is not
affected.
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:
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:
9. Add a third Button control.
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:
12. Add a Galler y 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 Galler y 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.
14. Position the control to the right of the other controls:
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.
More advanced offline example
For a detailed example, see the article on simple offline capabilities.
Filter, Search, and LookUp functions in Power Apps
11/19/2022 • 9 minutes to read • Edit Online
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 Galler y 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 Galler y may not be the
complete story, which could be confusing to users.
See the delegation overview for more information.
Syntax
Filter (Table*, Formula1 [, *Formula2*, ... ] )
Table - Required. Table to search.
Formula(s) - Required. The formula by which each record of the table is evaluated. The function returns all
records that result in true . You can reference columns within the table. If you supply more than one formula,
the results of all formulas are combined with the And function.
Search (Table*, SearchString, Column1 [, *Column2*, ... ] )
Table - Required. Table to search.
SearchString - Required. The string to search for. If blank or an empty string, all records are returned.
Column(s) - Required. The names of columns within Table to search. Columns to search must contain text.
Column names must be strings and enclosed in double quotes. However, the column names must be static
and cannot be calculated with a formula. If SearchString is found within the data of any of these columns as a
partial match, the full record will be returned.
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 following examples use the IceCream data source:
LookUp(IceCream, Flavor = Searches for a record with Flavor { Flavor: "Vanilla", Quantity: 200,
"Vanilla") equal to "Vanilla", of which there is OnOrder: 75 }
one. Since no reduction formula was
supplied, the entire record is returned.
8. Now select Galler y control and set the Items property to the following formula:
Filter(Accounts,
'Industry' = ComboBox3.Selected.Industry||IsBlank(ComboBox3.Selected.Industry),
'Relationship Type' = ComboBox2.Selected.'Relationship Type'||
IsBlank(ComboBox2.Selected.'Relationship Type'),
'Preferred Method of Contact' = ComboBox1.Selected.'Preferred Method of Contact'||
IsBlank(ComboBox1.Selected.'Preferred Method of Contact'))
To create this data source as a collection, create a Button control and set its OnSelect property to this formula:
ClearCollect(Customers, Table({ Name: "Fred Garcia", Company: "Nor thwind Traders" }, { Name:
"Cole Miller", Company: "Contoso" }, { Name: "Glenda Johnson", Company: "Contoso" }, { Name:
"Mike Collins", Company: "Adventure Works" }, { Name: "Colleen Jones", Company: "Adventure
Works" }) )
As in this example, you can show a list of records in a Galler y 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:
You can expand your search to include the Company column and the Name column:
F O RM UL A DESC RIP T IO N RESULT
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 )
DateTime - Required. Date/Time value to operate on.
Weekday ( DateTime [, WeekdayFirst ] )
DateTime - Required. Date/Time value to operate on.
WeekdayFirst - Optional. Excel code specifying which day starts the week. If not supplied, 1 (Sunday first) is
used.
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 Galler y 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't use Select across screens.
You can use Select only with controls that have an OnSelect property.
You can use Select only in behavior formulas.
A control can't Select itself directly or indirectly through other controls.
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 )
Control – Required. The control to select on behalf of the user.
Select ( Control, Row or column, Child Control )
Control – Required. The control to select on behalf of the user.
Row or column – Not required. The number of row or column (starting with 1) in a gallery control to select
on behalf of the user.
Child Control - Not required. The child control of the control identified in the 'control' parameter to select.
Examples
Button
Select(button1)
Gallery
Select(Gallery1, 1)
Gallery control
1. Add a vertical Galler y control that contains other controls.
2. Set the OnSelect property of the gallery to this formula:
Notify( "Galler y Selected" )
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 Galler y 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:
Notify( "Image Selected", Success )
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, Galler y 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( Galler y1,2,Image1 )
7. While holding down the Alt key, select the button.
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
11/19/2022 • 12 minutes to read • Edit Online
Some of these operators are dependent on the language of the author. For more information about language
support in canvas apps, see Global apps.
* 2*3 Multiplication
& String concatenation "hello" & " " & "world" Makes multiple strings
operator appear continuous
&& or And Logical operators Price < 100 && Logical conjunction,
Slider1.Value = 20 equivalent to the And
or Price < 100 And function
Slider1.Value = 20
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')
ThisRecord ForAll, Filter , With , Sum and other The default name for the current
record scope functions record in ForAll and other record
scope functions.
ThisItem operator
For example, in the following Galler y control, the Items property is set to the Employees data source (such as
the Employees table included with the Northwind Traders sample):
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:
ThisItem.Picture
Likewise, the formula for the name also uses ThisItem :
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:
ThisRecord is optional and implied by using the fields directly, for example, in this case, we could have written:
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:
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:
Employees As Employee
The formulas for the picture and name are adjusted to use this name for the current record:
Employee.Picture
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:
Concat(
ForAll( Sequence(8) As Rank,
Concat(
ForAll( Sequence(8) As File,
If( Mod(Rank.Value + File.Value, 2) = 1, " X ", " . " )
),
Value
) & Char(10)
),
Value
)
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:
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:
M ET H O D DESC RIP T IO N
M ET H O D DESC RIP T IO N
Parent operator Some controls host other controls, such as the Screen and
Galler y controls. The 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.
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
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 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.
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).
For more information and examples, see record scopes.
Set function in Power Apps
11/19/2022 • 2 minutes to read • Edit Online
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 )
VariableName - Required. The name of a global variable to create or update.
Value - Required. The value to assign to the context variable.
Examples
F O RM UL A DESC RIP T IO N RESULT
Set( Counter, 1 ) Creates or modifies the global variable Counter has the value 1 . You can
Counter , setting its value to 1 . reference that variable by using the
name Counter in a formula on any
screen.
Set( Counter, 2 ) Sets the value of the Counter global Counter has the value 2 .
variable from the previous example to
2.
Set( Counter, Counter + 1 ) Increments the value of the Counter Counter has the value 3 .
global variable from the previous
example to 3 .
Set( Name, "Lily" ) Creates or modifies the global variable Name has the value Lily .
Name setting its value to Lily .
Set( Person, { Name: "Milton", Creates or modifies the global variable Person has the value of record
Address: "1 Main St" } ) Person , setting its value to a record. { Name: "Milton",
The record contains two columns, Address: "1 Main St" } .
named Name and Address . The value
of the Name column is Milton , and Reference this record as a whole with
the value of the Address column is 1 the name Person , or reference an
Main St . individual column of this record with
Person.Name or Person.Address .
Set( Person, Works with the Patch function to Person now has the value of record
Patch( Person, {Address: "2 Main update the Person global variable by { Name: "Milton",
St" } ) ) setting the value of the Address Address: "2 Main St" } .
column to 2 Main St .
SetFocus function in Power Apps
11/19/2022 • 6 minutes to read • Edit Online
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 Galler y 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.
You can use SetFocus only in behavior formulas.
Syntax
SetFocus ( Control )
Control – Required. The control to give the input focus.
Examples
Focus on a newly exposed or enabled input control
Many shopping carts allow the customer to use the shipping address as the billing address, alleviating the need
to enter the same information twice. If a different billing address is desired, the billing address text input boxes
are enabled, and it is helpful to guide the customer to the these newly enabled controls for faster data entry.
There are many formulas in play here, but the one that moves the focus is on the OnUncheck property of the
Check box control:
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.
To create this example:
1. Create a new app.
2. Add Label controls with the text "Shipping address", "Name:", "Address:", "Billing Address", "Name:", and
"Address:" and position them as shown in the animation.
3. Add a Text Input control and rename it ShippingName .
4. Add a Text Input control and rename it ShippingAddress .
5. Add a Check box control and rename it SyncAddresses .
6. Set the Text property of this control to the formula "Use Shipping address as Billing address" .
7. Add a Text Input control and rename it BillingName .
8. Set the Default property on this control to the formula ShippingName .
9. Set the DisplayMode property on this control to the formula
If( SyncAddresses.Value, DisplayMode.View, DisplayMode.Edit ) . This will automatically enable or disable this
control based on the state of the check box control.
10. Add a Text Input control and rename it BillingAddress .
11. Set the Default property on this control to the formula ShippingAddress .
12. Set the DisplayMode property on this control to the formula
If( SyncAddresses.Value, DisplayMode.View, DisplayMode.Edit ) . This will 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.
Focus on validation issues
NOTE
Although this example appears to be an Edit form control, unfortunately SetFocus is not yet supported by that control.
Instead, this example uses a scrollable screen to host the input controls.
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:
NOTE
Although this example appears to be an Edit form control, unforutnatley SetFocus is not yet supported by that control.
Instead, this example uses a scrollable screen to host the input controls.
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:
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.
To create this example:
1. Create the "Focus on validation issues" app above.
2. On this screen, set the OnVisible property to the formula SetFocus( Name ) .
3. Add a second screen.
4. Add a Button control.
5. Set the OnSelect property of this control to the formula Navigate( Screen1 ) .
6. Preview the app from this screen. Press the button. The OnVisible formula will be evaluated and the Name
field will automatically be in focus.
SetProperty function in Power Apps Test Studio
11/19/2022 • 2 minutes to read • Edit Online
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
C O N T RO L P RO P ERT Y EXA M P L E EXP RESSIO N
See Also
Test Studio Overview
Working with Test Studio
Sequence function in Power Apps
11/19/2022 • 2 minutes to read • Edit Online
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 :
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:
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.
NOTE
Sequence is limited to 50,000 records.
Syntax
Sequence ( Records [, Start [, Step ] ] )
Records – Required. The number of records to create. Must be in the range 0 to 50,000.
Start – Optional. The starting number for the sequence. Default is 1.
Step – Optional. The increment for each successive number in the sequence. Step can be negative to count
down from the Start. Default is 1.
Examples
Basic usage
F O RM UL A DESC RIP T IO N RESULT
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
11/19/2022 • 6 minutes to read • Edit Online
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.
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 formula is evaluated for each record of the table.
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 DropColumns function excludes columns from a table. All other columns remain unmodified.
DropColumns excludes columns, and ShowColumns includes columns.
Use the RenameColumns function to rename one or more columns of a table by providing at least one
argument pair that specifies the name of a column that the table contains (the old name, which you want to
replace) and the name of a column that the table doesn't contain (the new name, which you want to use). The
old name must already exist in the table, and the new name must not exist. Each column name may appear only
once in the argument list as either an old column name or a new column name. To rename a column to an
existing column name, first drop the existing column with DropColumns , or rename the existing column out of
the way by nesting one RenameColumns function within another.
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:
AddColumns( RealEstateAgents,
"Listings",
Filter( '[dbo].[AllListings]', ListingAgentName = AgentName )
)
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 OnStar t 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, ... ] )
Table - Required. Table to operate on.
ColumnName(s) - Required. Name(s) of the column(s) to add. You must specify a string (for example,
"Name" with double quotes included) for this argument.
Formula(s) - Required. Formula(s) to evaluate for each record. The result is added as the value of the
corresponding new column. You can reference other columns of the table in this formula.
DropColumns ( Table, ColumnName1 [, ColumnName2, ... ] )
Table - Required. Table to operate on.
ColumnName(s) - Required. Name(s) of the column(s) to drop. You must specify a string (for example,
"Name" with double quotes included) for this argument.
RenameColumns ( Table, OldColumnName1, NewColumnName1 [, OldColumnName2, NewColumnName2, ... ]
)
Table - Required. Table to operate on.
OldColumnName - Required. Name of a column to rename from the original table. This element appears first
in the argument pair (or first in each argument pair if the formula includes more than one pair). This name
must be a string (for example "Name" with double quotation marks included).
NewColumnName - Required. Replacement name. This element appears last in the argument pair (or last in
each argument pair if the formula includes more than one pair). You must specify a string (for example,
"Customer Name" with double quotation marks included) for this argument.
ShowColumns ( Table, ColumnName1 [, ColumnName2, ... ] )
Table - Required. Table to operate on.
ColumnName(s) - Required. Name(s) of the column(s) to include. You must specify a string (for example,
"Name" with double quotes included) for this argument.
Examples
The examples in this section use the IceCreamSales data source, which contains the data in this table:
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.
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:
ClearCollect( IceCreamSales,
Table(
{ Flavor: "Strawberry", UnitPrice: 1.99, QuantitySold: 20 },
{ Flavor: "Chocolate", UnitPrice: 2.99, QuantitySold: 45 },
{ Flavor: "Vanilla", UnitPrice: 1.50, QuantitySold: 35 }
)
)
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:
ClearCollect( FirstExample,
AddColumns( IceCreamSales, "Revenue", UnitPrice * QuantitySold )
)
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
11/19/2022 • 2 minutes to read • Edit Online
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 )
Table - Required. Table to shuffle.
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
11/19/2022 • 4 minutes to read • Edit Online
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.
The Pi function returns the transcendental number π, which begins 3.141592...
The Radians function converts degrees to radians.
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, 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 )
Radians - Required. Angle to operate on.
Cos ( SingleColumnTable )
Cot ( SingleColumnTable )
Sin ( SingleColumnTable )
Tan ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of angles to operate on.
Inverse Functions
Acos ( Number )
Acot ( Number )
Asin ( Number )
Atan ( Number )
Number - Required. Number to operate on.
Acos ( SingleColumnTable )
Acot ( SingleColumnTable )
Asin ( SingleColumnTable )
Atan ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of numbers to operate on.
Atan2 ( X, Y )
X - Required. X-axis coordinate.
Y - Required. Y-axis coordinate.
Helper Functions
Degrees ( Radians )
Radians - Required. Angle in radians to convert to degrees.
Pi ()
Radians ( Degrees )
Degrees - Required. Angle in degrees to convert to radians.
Examples
Single number
F O RM UL A DESC RIP T IO N RESULT
Sorts a table.
Description
The Sor t 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 Sor t 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:
Sor t( Sor t( Contacts, LastName ), FirstName )
The Sor tByColumns function can also be used to sort a table based on one or more columns.
The parameter list for Sor tByColumns 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, Sor tByColumns( CustomerTable, "LastName" ) .
You can combine Sor tByColumns with a Drop down or List box control to enable users to select which
column to sort by.
In addition to sorting ascending or descending, Sor tByColumns can sort based on a single column table of
values. For example, you can sort record based on the name of a day of the week by supplying [ "Monday",
"Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ] as the sort order. All records
which have Monday" will come first, followed by Tuesday , and so on. Records found that do not appear in the
sort table are put at the end of the list.
Tables are a value in Power Apps, just like a string or number. They can be passed to and returned from
functions. Sor t and Sor tByColumn 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 Galler y 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 Galler y may not be the
complete story, which could be confusing to users.
See the delegation overview for more information.
Syntax
Sor t ( Table, Formula [, SortOrder ] )
Table - Required. Table to sort.
Formula - Required. This formula is evaluated for each record of the table, and the results are used to sort the
table. You can reference columns within the table.
SortOrder - Optional. Specify Sor tOrder.Descending to sort the table in descending order.
Sor tOrder.Ascending is the default value.
Sor tByColumns ( Table, ColumnName1 [, SortOrder1, ColumnName2, SortOrder2, ... ] )
Table - Required. Table to sort.
ColumnName(s) - Required. The column names to sort on, as strings.
SortOrder(s) - Optional. Sor tOrder.Ascending or Sor tOrder.Descending . Sor tOrder.Ascending is
the default. If multiple ColumnNames are supplied, all but the last column must include a SortOrder.
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".
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:
F O RM UL A DESC RIP T IO N RESULT
Step by step
To run these examples yourself, create the IceCream data source as a collection:
1. Add a button, and set its OnSelect property to this formula:
ClearCollect( IceCream, { Flavor : "Chocolate", Quantity: 100, OnOrder : 150 }, { Flavor : "Vanilla",
Quantity: 200, OnOrder : 20 }, { Flavor : "Strawberr y", Quantity: 300, OnOrder : 0 }, { Flavor : "Mint
Chocolate", Quantity: 60, OnOrder : 100 }, { Flavor : "Pistachio", Quantity: 200, OnOrder : 10 } )
2. Preview the app, select the button, and then press Esc to return to the default workspace.
3. Select Collections on the File menu to display the collection that you just created, and then press Esc to
return to the default workspace.
Sort
1. Add another button, and set its OnSelect property to this formula:
ClearCollect( Sor tByFlavor, Sor t( IceCream, Flavor ) )
The previous formula creates a second collection, named Sor tByFlavor , that contains the same data as
Ice Cream . However, the new collection contains the data sorted alphabetically by the Flavor column in
ascending order.
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
Sor t formula with a different formula from the table of examples earlier in this section that uses Sor t .
SortByColumns
1. Add another button, and set its OnSelect property to this formula:
ClearCollect( Sor tByQuantity, Sor tByColumns( IceCream, "Quantity", Ascending, "Flavor",
Descending ) )
The previous formula creates a third collection, named Sor tByQuantity , that contains the same data as
Ice Cream . However, the new collection contains the data sorted numerically by the Quantity column in
ascending order, and then by the Flavor column in descending order.
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
Sor tByColumns formula with a different formula from the table of examples earlier in this section that
uses Sor tByColumns .
Sort and SortByColumns functions in Power Apps
11/19/2022 • 7 minutes to read • Edit Online
Sorts a table.
Description
The Sor t 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 Sor t 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:
Sor t( Sor t( Contacts, LastName ), FirstName )
The Sor tByColumns function can also be used to sort a table based on one or more columns.
The parameter list for Sor tByColumns 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, Sor tByColumns( CustomerTable, "LastName" ) .
You can combine Sor tByColumns with a Drop down or List box control to enable users to select which
column to sort by.
In addition to sorting ascending or descending, Sor tByColumns can sort based on a single column table of
values. For example, you can sort record based on the name of a day of the week by supplying [ "Monday",
"Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ] as the sort order. All records
which have Monday" will come first, followed by Tuesday , and so on. Records found that do not appear in the
sort table are put at the end of the list.
Tables are a value in Power Apps, just like a string or number. They can be passed to and returned from
functions. Sor t and Sor tByColumn 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 Galler y 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 Galler y may not be the
complete story, which could be confusing to users.
See the delegation overview for more information.
Syntax
Sor t ( Table, Formula [, SortOrder ] )
Table - Required. Table to sort.
Formula - Required. This formula is evaluated for each record of the table, and the results are used to sort the
table. You can reference columns within the table.
SortOrder - Optional. Specify Sor tOrder.Descending to sort the table in descending order.
Sor tOrder.Ascending is the default value.
Sor tByColumns ( Table, ColumnName1 [, SortOrder1, ColumnName2, SortOrder2, ... ] )
Table - Required. Table to sort.
ColumnName(s) - Required. The column names to sort on, as strings.
SortOrder(s) - Optional. Sor tOrder.Ascending or Sor tOrder.Descending . Sor tOrder.Ascending is
the default. If multiple ColumnNames are supplied, all but the last column must include a SortOrder.
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".
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:
F O RM UL A DESC RIP T IO N RESULT
Step by step
To run these examples yourself, create the IceCream data source as a collection:
1. Add a button, and set its OnSelect property to this formula:
ClearCollect( IceCream, { Flavor : "Chocolate", Quantity: 100, OnOrder : 150 }, { Flavor : "Vanilla",
Quantity: 200, OnOrder : 20 }, { Flavor : "Strawberr y", Quantity: 300, OnOrder : 0 }, { Flavor : "Mint
Chocolate", Quantity: 60, OnOrder : 100 }, { Flavor : "Pistachio", Quantity: 200, OnOrder : 10 } )
2. Preview the app, select the button, and then press Esc to return to the default workspace.
3. Select Collections on the File menu to display the collection that you just created, and then press Esc to
return to the default workspace.
Sort
1. Add another button, and set its OnSelect property to this formula:
ClearCollect( Sor tByFlavor, Sor t( IceCream, Flavor ) )
The previous formula creates a second collection, named Sor tByFlavor , that contains the same data as
Ice Cream . However, the new collection contains the data sorted alphabetically by the Flavor column in
ascending order.
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
Sor t formula with a different formula from the table of examples earlier in this section that uses Sor t .
SortByColumns
1. Add another button, and set its OnSelect property to this formula:
ClearCollect( Sor tByQuantity, Sor tByColumns( IceCream, "Quantity", Ascending, "Flavor",
Descending ) )
The previous formula creates a third collection, named Sor tByQuantity , that contains the same data as
Ice Cream . However, the new collection contains the data sorted numerically by the Quantity column in
ascending order, and then by the Flavor column in descending order.
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
Sor tByColumns formula with a different formula from the table of examples earlier in this section that
uses Sor tByColumns .
Split function in Power Apps
11/19/2022 • 2 minutes to read • Edit Online
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.
Use the MatchAll function to split a string using a regular expression.
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 those familiar with regular
expressions.
Syntax
Split ( Text, Separator )
Text - Required. Text to split.
Separator - Required. Separator to use in splitting the string. Can be zero, one, or more characters.
Examples
Basic usage
F O RM UL A DESC RIP T IO N RESULT
Different delimiters
F O RM UL A DESC RIP T IO N RESULT
Split( "Hello, World", "," ) Splits the words apart, using a comma
as the separator. The second result
starts with a space since this was the
character immediately following the
comma.
Split( "Hello, World", "o" ) Splits the string apart, using the
character "o" as the separator.
Split( "Hello, World", "l" ) Splits the string apart, using the single
character "l" as the separator. Since
there were no characters between the
two l's in Hello , a blank value was
returned.
Split( "Hello, World", "ll" ) Splits the string apart, using the
double character "ll" as the separator.
Split( "Hello, World", "%" ) Splits the string apart, using the
percent sign as the separator. Since
this separator does not appear in the
string, the entire string is returned as
one result.
F O RM UL A DESC RIP T IO N RESULT
Split( "Hello, World", "" ) Splits the string apart, using an empty
string as the separator (zero
characters). This will break the string
on each character.
Substring extraction
F O RM UL A DESC RIP T IO N RESULT
First( Split( Last( Split( "Bob Splits the string apart based on an "[email protected]"
Jones <[email protected]>", opening delimiter (<) and extracts the
"<" ) ).Result, ">" ) ).Result
string to the right of the delimiter with
Last . The formula then splits that
result based on the closing delimiter
(>) and extracts the string the left of
the delimiter with Right .
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 Ln function returns the natural logarithm (base e) of its argument.
The Power function returns a number raised to a power. It is 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 Sqr t 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, 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. This can happen, for example, with
square roots and logarithms of negative numbers.
Syntax
Abs ( Number )
Exp ( Number )
Ln ( Number )
Sqr t ( Number )
Number - Required. Number to operate on.
Power ( Base, Exponent )
Base - Required. Base number to raise.
Exponent - Required. The exponent to which the base number is raised.
Log ( Number, Base )
Number - Required. Number to calculate the logarithm.
Base - Optional. The base of the logarithm to calculate. By default, 10 (when not specified).
Abs ( SingleColumnTable )
Exp ( SingleColumnTable )
Ln ( SingleColumnTable )
Sqr t ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of numbers to operate on.
Examples
Single number
F O RM UL A DESC RIP T IO N RESULT
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:
Sqr t( Value( Source.Text ) )
3. Type a number into Source , and confirm that the Label control shows the square root of the number that
you typed.
EndsWith and StartsWith functions in Power Apps
11/19/2022 • 4 minutes to read • Edit Online
Description
The EndsWith function tests whether one text string ends with another.
The Star tsWith 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 Star tsWith 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 )
Text – Required. The text to test.
EndText – Required. The text to search for at the end of Text. If EndText is an empty string, EndsWith returns
true.
Star tsWith ( Text, StartText )
Text – Required. The text to test.
StartText – Required. The text to search for at the beginning of Text. If StartText is an empty string, Star tsWith
returns true.
Examples
F O RM UL A DESC RIP T IO N RESULT
EndsWith( "Hello World", "world" Tests whether "Hello World" ends true
) with "world". The test is case
insensitive.
EndsWith( "Good bye", "good" ) Tests whether "Good bye" ends with false
"good". The EndText argument
("good") appears in the text but not
at the end.
EndsWith( "Always say hello", Tests whether "Always say hello" true
"hello" ) ends with "hello".
F O RM UL A DESC RIP T IO N RESULT
EndsWith( "Bye bye", "" ) Tests whether "Bye bye" ends with an true
empty text string (Len returns 0).
Easing its use in Filter expressions,
EndsWith is defined to return true in
this case.
Star tsWith( "Hello World", "hello" Tests whether "Hello World" begins true
) with "hello". The test is case
insensitive.
Star tsWith( "Good bye", "hello" ) Tests whether "Good bye" begins false
with "hello".
Star tsWith( "Always say hello", Tests whether "Always say hello" false
"hello" ) begins with "hello". Although "hello"
appears in the text, it doesn't appear at
the beginning.
Star tsWith( "Bye bye", "" ) Tests whether "Bye bye" starts with true
an empty text string (Len returns 0).
Easing its use in Filter expressions,
Star tsWith is defined to return true
in this case.
To create this data source as a collection, create a Button control and set its OnSelect property to this formula:
ClearCollect( Customers, Table( { Name: "Fred Garcia", Company: "Nor thwind Traders" }, { Name:
"Cole Miller", Company: "Contoso" }, { Name: "Glenda Johnson", Company: "Contoso" }, { Name:
"Mike Collins", Company: "Adventure Works" }, { Name: "Colleen Jones", Company: "Adventure
Works" } ) )
As in this example, you can show a list of records in a Galler y 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, Star tsWith( Filters the Customers data source for
Name, SearchInput.Text ) ) records in which the search string
appears at the start of the Name
column. The test is case 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.
F O RM UL A DESC RIP T IO N RESULT
You can expand your search to include the Company column as well as the Name column:
Filter( Customers, Star tsWith( Filters the Customers data source for
Name, SearchInput.Text ) || records in which either the Name
Star tsWith( Company, column or the Company column
SearchInput.Text ) ) starts with the search string (for
example, co ). The || operator is true if
either Star tsWith function is true.
Description
The Average function calculates the average, or arithmetic mean, of its arguments.
The Max function finds the maximum value.
The Min function finds the minimum value.
The Sum function calculates the sum of its arguments.
The StdevP function calculates the standard deviation of its arguments.
The VarP function calculates the variance of its arguments.
You can supply the values for these functions as:
Separate arguments. For example, Sum( 1, 2, 3 ) returns 6.
A table and a formula to operate over that table. The aggregate will be calculated on the values of the
formula for each 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.
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, ... ] )
Max ( NumericalFormula1, [ NumericalFormula2, ... ] )
Min ( NumericalFormula1, [ NumericalFormula2, ... ] )
Sum ( NumericalFormula1, [ NumericalFormula2, ... ] )
StdevP ( NumericalFormula1, [ NumericalFormula2, ... ] )
VarP ( NumericalFormula1, [ NumericalFormula2, ... ] )
NumericalFormula(s) - Required. Numeric values to operate on.
Average ( Table, NumericalFormula )
Max ( Table, NumericalFormula )
Min ( Table, NumericalFormula )
Sum ( Table, NumericalFormula )
StdevP ( Table, NumericalFormula )
VarP ( Table, NumericalFormula )
Table - Required. Table to operate on.
NumericalFormula - Required. Formula to evaluate for each record. The result of this formula is used for the
aggregation. You can use columns of the table in the formula.
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:
Sum(Sales, CostPerUnit * UnitsSold)
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.
Average(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the average of all values to
which the sliders were set.
Max(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the maximum of all values to
which the sliders were set.
Min(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the minimum of all values to which
the sliders were set.
StdevP(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the standard deviation of all
values to which the sliders were set.
VarP(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the variance of all values to which
the sliders were set.
Replace and Substitute functions in Power Apps
11/19/2022 • 2 minutes to read • Edit Online
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 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 )
String - Required. The string to operate on.
StartingPosition - Required. Character position to start the replacement. The first character of String is at
position 1.
NumberOfCharacters - Required. The number of characters to replace in String.
NewString - Required. The replacement string. The number of characters in this argument can differ from the
NumberOfCharacters argument.
Substitute ( String, OldString, NewString [, InstanceNumber ] )
String - Required. The string to operate on.
OldString - Required. The string to replace.
NewString - Required. The replacement string. OldString and NewString can have different lengths.
InstanceNumber - Optional. Use this argument to specify which instance of OldString to replace if String
contains more than one instance. If you don't specify this argument, all instances will be replaced.
Replace ( SingleColumnTable, StartingPosition, NumberOfCharacters, NewString )
SingleColumnTable - Required. A single-column table of strings to operate on.
StartingPosition - Required. Character position to start the replacement. The first character of each string in
the table is at position 1.
NumberOfCharacters - Required. The number of characters to replace in each string.
NewString - Required. The replacement string. The number of characters in this argument can differ from the
NumberOfCharacters argument.
Substitute ( SingleColumnTable, OldString, NewString [, InstanceNumber ] )
SingleColumnTable - Required. A single-column table of strings to operate on.
OldString - Required. The string to replace.
NewString - Required. The replacement string. OldString and NewString can have different lengths.
InstanceNumber - Optional. Use this argument to specify which instance of OldString to replace if String
contains more than one instance. If you don't specify this argument, all instances will be replaced.
Examples
F O RM UL A DESC RIP T IO N RESULT
Substitute( "Sales Data", "Sales", " Substitutes the string "Cost" for "Cost Data"
Cost" ) "Sales".
Substitute( "Quar ter 1, 2018", Substitutes only the first instance of "Quarter 2, 2018"
"1", "2", 1 ) "1" with "2" because the fourth
argument (InstanceNumber) is
provided with a 1.
Substitute( "Quar ter 1, 2011", Substitutes only the third instance of "Quarter 1, 2012"
"1", "2", 3 ) "1" with "2" because the fourth
argument (InstanceNumber) is
provided with a 3.
Substitute( "Quar ter 1, 2011", Substitutes all instances of "1" with "2" "Quarter 2, 2022"
"1", "2" ) because the fourth argument
(InstanceNumber) isn't provided.
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:
M O DE DESC RIP T IO N
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.
These functions return no values.
You can use these functions only in behavior formulas.
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 validation passes, SubmitForm submits the change to the data source.
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):
Syntax
SubmitForm ( FormName )
FormName - Required. Form control to submit to the data source.
EditForm ( FormName )
FormName - Required. Form control to switch to FormMode.Edit mode.
NewForm ( FormName )
FormName - Required. Form control to switch to FormMode.New mode.
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 )
FormName - Required. Form control to switch to FormMode.View mode.
Examples
See Understand data forms for complete examples.
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:
ResetForm( EditForm ); Back()
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:
NewForm( EditForm ); Navigate( EditScreen, None )
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
11/19/2022 • 2 minutes to read • Edit Online
Description
The Average function calculates the average, or arithmetic mean, of its arguments.
The Max function finds the maximum value.
The Min function finds the minimum value.
The Sum function calculates the sum of its arguments.
The StdevP function calculates the standard deviation of its arguments.
The VarP function calculates the variance of its arguments.
You can supply the values for these functions as:
Separate arguments. For example, Sum( 1, 2, 3 ) returns 6.
A table and a formula to operate over that table. The aggregate will be calculated on the values of the
formula for each 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.
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, ... ] )
Max ( NumericalFormula1, [ NumericalFormula2, ... ] )
Min ( NumericalFormula1, [ NumericalFormula2, ... ] )
Sum ( NumericalFormula1, [ NumericalFormula2, ... ] )
StdevP ( NumericalFormula1, [ NumericalFormula2, ... ] )
VarP ( NumericalFormula1, [ NumericalFormula2, ... ] )
NumericalFormula(s) - Required. Numeric values to operate on.
Average ( Table, NumericalFormula )
Max ( Table, NumericalFormula )
Min ( Table, NumericalFormula )
Sum ( Table, NumericalFormula )
StdevP ( Table, NumericalFormula )
VarP ( Table, NumericalFormula )
Table - Required. Table to operate on.
NumericalFormula - Required. Formula to evaluate for each record. The result of this formula is used for the
aggregation. You can use columns of the table in the formula.
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:
Sum(Sales, CostPerUnit * UnitsSold)
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.
Average(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the average of all values to
which the sliders were set.
Max(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the maximum of all values to
which the sliders were set.
Min(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the minimum of all values to which
the sliders were set.
StdevP(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the standard deviation of all
values to which the sliders were set.
VarP(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the variance of all values to which
the sliders were set.
If and Switch functions in Power Apps
11/19/2022 • 4 minutes to read • Edit Online
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 ] )
If ( Condition1, ThenResult1 [, Condition2, ThenResult2, ... [ , DefaultResult ] ] )
Condition(s) - Required. Formula(s) to test for true . Such formulas commonly contain comparison operators
(such as < , > , and = ) and test functions such as IsBlank and IsEmpty .
ThenResult(s) - Required. The corresponding value to return for a condition that evaluates to true .
DefaultResult - Optional. The value to return if no condition evaluates to true . If you don't specify this
argument, blank is returned.
Switch ( Formula, Match1, Result1 [, Match2, Result2, ... [, DefaultResult ] ] )
Formula - Required. Formula to evaluate for matches. This formula is evaluated only once.
Match(s) - Required. Values to compare with the result from Formula. If an exact match is found, the
corresponding Result is returned.
Result(s) - Required. The corresponding value to return when an exact match is found.
DefaultResult - Optional. If an exact match isn't found, this value is returned. If you don't specify this
argument, blank is returned.
Examples
Values in formulas
In the following examples, a Slider control (named Slider1 ) has a value of 25 .
If( Slider1.Value = 25, "Result1" ) The condition is true , and the "Result1"
corresponding result is returned.
If( Slider1.Value = 25, "Result1", The condition is true , and the "Result1"
"Result2" ) corresponding result is returned.
If( Slider1.Value = 25, "Result1", The first condition is true , and the "Result1"
Slider1.Value > 0, "Result2" ) corresponding result is returned. The
second condition is also true , but it
isn't evaluated because it appears later
in the argument list than a condition
that evaluates to true .
If( IsBlank( Slider1.Value ), The first condition is false because the "Result2"
"Result1", slider isn't blank. The second condition
IsNumeric( Slider1.Value ), is true because the slider's value is a
"Result2" ) number, and the corresponding result
is returned.
If( Slider1.Value > 1000, Both the first and second conditions "Result3"
"Result1", Slider1.Value > 50, are false , a DefaultResult was
"Result2", "Result3") provided, and it's returned.
Switch( Slider1.Value, 25, The slider's value matches the first "Result1"
"Result1" ) value to be checked, and the
corresponding result is returned.
Switch( Slider1.Value, 20, The slider's value matches the second "Result2"
"Result1", 25, "Result2", 30, value to be checked, and the
"Result3" ) corresponding result is returned.
Switch( Slider1.Value, 20, The slider's value doesn't match any "DefaultResult"
"Result1", 10, "Result2", 0, value to be checked. A DefaultResult
"Result3", "DefaultResult" ) was provided, so it's returned.
Step by step
1. Add a Text input control, and name it Text1 if it doesn't have that name by default.
2. In Text1 , type 30 .
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.
4. In Text1 , type 15 .
The Label control shows Order MANY more! because the value of Text1 is less than 20.
5. In Text1 , type 50 .
The Label control shows the value that you typed because it's more than 40.
Table function in Power Apps
11/19/2022 • 2 minutes to read • Edit Online
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, ... ] )
Record(s) - Required. The records to add to the table.
Table ( Untyped )
Untyped - Required. Untyped object that represents a table or array. Acceptable values are dependent on
the untyped provider. For JSON , the untyped object is expected to be a JSON array. Note that regardless of
the content type of the Untyped array, the resulting table will be a single-column table of Untyped objects.
Examples
Set the Items property of a listbox to this formula:
Table({Color :"red"}, {Color :"green"}, {Color :"blue"})
The listbox shows each color as an option.
Add a text gallery, and set its Items property to this function:
Table({Item:"Violin123", Location:"France", Owner :"Fabrikam"}, {Item:"Violin456",
Location:"Chile"})
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
11/19/2022 • 4 minutes to read • Edit Online
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.
The Pi function returns the transcendental number π, which begins 3.141592...
The Radians function converts degrees to radians.
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, 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 )
Radians - Required. Angle to operate on.
Cos ( SingleColumnTable )
Cot ( SingleColumnTable )
Sin ( SingleColumnTable )
Tan ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of angles to operate on.
Inverse Functions
Acos ( Number )
Acot ( Number )
Asin ( Number )
Atan ( Number )
Number - Required. Number to operate on.
Acos ( SingleColumnTable )
Acot ( SingleColumnTable )
Asin ( SingleColumnTable )
Atan ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of numbers to operate on.
Atan2 ( X, Y )
X - Required. X-axis coordinate.
Y - Required. Y-axis coordinate.
Helper Functions
Degrees ( Radians )
Radians - Required. Angle in radians to convert to degrees.
Pi ()
Radians ( Degrees )
Degrees - Required. Angle in degrees to convert to radians.
Examples
Single number
F O RM UL A DESC RIP T IO N RESULT
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:
A predefined date/time format, which you specify by using the DateTimeFormat enumeration. For dates
and times, this approach is preferred as it automatically adjusts to each user's language and region.
A custom format, which comprises a string of placeholders that define, for example, whether numbers show
a decimal separator and dates show the full name of the month, the month as an abbreviation, or the month
as a number. Power Apps supports a subset of the placeholders that Microsoft Excel does. In this string, the
language placeholder specifies the language in which to interpret the other placeholders. If the custom
format includes a period, for example, the language-format placeholder specifies whether the period is a
decimal separator ( ja-JP) or a thousands separator (es-ES).
See working with dates and times for more information.
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 .
Predefined date/time formats
For these examples, date and time used is Tuesday, April 7, 2020 8:26:59.180 PM, in the time zone UTC-7 hours.
LongDateTime Four-digit year, month name, day of "Tuesday, April 7, 2020 8:26:59 PM"
the month, and day of the week, plus
hour (12-hour clock), minutes,
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 "Tuesday, April 7, 2020 20:26:59"
month, and day of the week, plus hour
(24-hour clock), minutes, and seconds.
The names of the month and day of
the week aren't abbreviated.
Shor tDateTime Four-digit year with numerical month "4/7/2020 8:26 PM"
and day of the month, plus hour (12-
hour clock), minutes, and AM/PM
designation.
Number placeholders
P L A C EH O L DER DESC RIP T IO N
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 ).
Date and time placeholders
P L A C EH O L DER DESC RIP T IO N
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.
C H A RA C T ER DESC RIP T IO N
Any currency symbol Dollar sign, cents sign, euro sign, etc.
+ Plus sign
( Left parenthesis
: Colon
' Apostrophe
= Equal sign
- Minus sign
/ 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:
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.
NOTE
In a future version, the syntax of this placeholder may change to avoid confusion with a similar, but different, placeholder
that Excel supports.
Syntax
Text ( NumberOrDateTime, DateTimeFormatEnum [, ResultLanguageTag ] )
NumberOrDateTime - Required. The number or the date/time value to format.
DateTimeFormat - Required. A member of the DateTimeFormat enumeration.
ResultLanguageTag - Optional. The language tag to use for the result text. By default, the language of the
current user is used.
Text ( NumberOrDateTime, CustomFormat [, ResultLanguageTag ] )
Number - Required. The number or the date/time value to format.
CustomFormat - Required. One or more placeholders enclosed in double quotation marks.
ResultLanguageTag - Optional. The language tag to use for the result text. By default, the language of the
current user is used.
Text ( AnyValue )
AnyValue - Required. Value to convert to a text representation. A default format is used.
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
F O RM UL A DESC RIP T IO N RESULT
Text( 1234.59, "####.#" ) Formats the number with one decimal "1234.6"
place.
Text( 0.631, "0.#" ) Pads the whole portion of the number "0.6"
with leading zeros, if needed.
Text( 12000, "$ #,###" ) Places a thousands separator every "$ 12,000"
Text( 1200000, "$ #,###" ) three digits, and includes a currency "$ 1,200,000"
symbol.
Date/Time
At 2:37:47 PM on Monday, November 23, 2015
United States Pacific Time Zone (UTC-8)
Text( Now(), Formats as a long date string, in the "Monday, November 23, 2015"
DateTimeFormat.LongDate ) language and locale of the current
user.
Text( Now(), Formats as a long date and time "Monday, November 23, 2015 2:37:47
DateTimeFormat.LongDateTime ) string, in the language and locale of PM"
the current user, using a 12-hour
clock.
Text(1448318857*1000, "mmm. Shows a Unix date-time value in "Nov. 23, 2015 (02:47:37 PM)"
dd, yyyy (hh:mm:ss AM/PM)") human-readable format if you multiply
the source value by 1,000.
Global apps
F O RM UL A DESC RIP T IO N RESULT
Text(1234567,89; "[$-fr-FR]# If the source data follows the French "1 234 567,89 €"
###,## €") custom of using a 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( Date(2016,1,31), "dddd Returns the weekday, month, and day "Sunday January 31"
mmmm d" ) of the month in the language of the
current user. Because none of the
placeholders are language dependent,
there is no need for a format text
language tag.
Text( Date(2016,1,31), "dddd Returns the weekday, month, and day "domingo enero 31"
mmmm d", "es-ES" ) of the month in the "es-ES" language.
Text( DateTimeValue( "01/04/200 Converts a date/time value to a string "1/4/2003 12:00 AM"
3" ) ) of text. To control the conversion,
provide either a member of the
DateTimeFormat enumeration or a
custom-format string.
Some of these operators are dependent on the language of the author. For more information about language
support in canvas apps, see Global apps.
* 2*3 Multiplication
& String concatenation "hello" & " " & "world" Makes multiple strings
operator appear continuous
&& or And Logical operators Price < 100 && Logical conjunction,
Slider1.Value = 20 equivalent to the And
or Price < 100 And function
Slider1.Value = 20
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')
ThisRecord ForAll, Filter , With , Sum and other The default name for the current
record scope functions record in ForAll and other record
scope functions.
ThisItem operator
For example, in the following Galler y control, the Items property is set to the Employees data source (such as
the Employees table included with the Northwind Traders sample):
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:
ThisItem.Picture
Likewise, the formula for the name also uses ThisItem :
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:
ThisRecord is optional and implied by using the fields directly, for example, in this case, we could have written:
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:
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:
Employees As Employee
The formulas for the picture and name are adjusted to use this name for the current record:
Employee.Picture
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:
Concat(
ForAll( Sequence(8) As Rank,
Concat(
ForAll( Sequence(8) As File,
If( Mod(Rank.Value + File.Value, 2) = 1, " X ", " . " )
),
Value
) & Char(10)
),
Value
)
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:
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:
M ET H O D DESC RIP T IO N
M ET H O D DESC RIP T IO N
Parent operator Some controls host other controls, such as the Screen and
Galler y controls. The 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.
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
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 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.
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).
For more information and examples, see record scopes.
Operators and Identifiers in Power Apps
11/19/2022 • 12 minutes to read • Edit Online
Some of these operators are dependent on the language of the author. For more information about language
support in canvas apps, see Global apps.
* 2*3 Multiplication
& String concatenation "hello" & " " & "world" Makes multiple strings
operator appear continuous
&& or And Logical operators Price < 100 && Logical conjunction,
Slider1.Value = 20 equivalent to the And
or Price < 100 And function
Slider1.Value = 20
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')
ThisRecord ForAll, Filter , With , Sum and other The default name for the current
record scope functions record in ForAll and other record
scope functions.
ThisItem operator
For example, in the following Galler y control, the Items property is set to the Employees data source (such as
the Employees table included with the Northwind Traders sample):
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:
ThisItem.Picture
Likewise, the formula for the name also uses ThisItem :
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:
ThisRecord is optional and implied by using the fields directly, for example, in this case, we could have written:
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:
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:
Employees As Employee
The formulas for the picture and name are adjusted to use this name for the current record:
Employee.Picture
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:
Concat(
ForAll( Sequence(8) As Rank,
Concat(
ForAll( Sequence(8) As File,
If( Mod(Rank.Value + File.Value, 2) = 1, " X ", " . " )
),
Value
) & Char(10)
),
Value
)
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:
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:
M ET H O D DESC RIP T IO N
M ET H O D DESC RIP T IO N
Parent operator Some controls host other controls, such as the Screen and
Galler y controls. The 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.
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
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 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.
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).
For more information and examples, see record scopes.
Date and Time functions in Power Apps
11/19/2022 • 2 minutes to read • Edit Online
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.
Time ( Hour, Minute, Second )
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 :
Date(Value(HireYear.Text), Value(HireMonth.Text), Value(HireDay.Text))
Time
If a user typed 14 in a text-input control named Bir thHour , 50 in a text-input control named Bir thMinute , and
24 in a text-input control named Bir thSecond , this function would return 02:50:24 p .
Text(Time(Value(Bir thHour.Text), Value(Bir thMinute.Text), Value(Bir thSecond.Text)), "hh:mm:ss a/p")
DateValue, TimeValue, and DateTimeValue functions
in Power Apps
11/19/2022 • 4 minutes to read • Edit Online
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.
NOTE
The DateValue, TimeValue, and DateTimeValue functions by default use the language from the current user's settings. You
can override it to ensure that strings are interpreted properly. For example, "10/1/1920" is interpreted as October 1st in
"en" and as January 10th in "fr".
Syntax
DateValue ( String [, Language ])
DateTimeValue ( String [, Language ])
TimeValue ( 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 )
Untyped - Required. Untyped object that represents a date or time. Acceptable values are dependent on the
untyped provider. For JSON , the untyped object is expected to be a JSON string that contains a date and time
in ISO 8601 format. Dates or times in other formats will result in an error. Consider converting such values to
Text first, then to a date or time. Keep in mind that time zones and locale-related formats are important
considerations when communicating with external systems.
Examples
DateValue
If you type 10/11/2014 into a text-input control named Star tdate , 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.
Device set to en locale shows the label as Saturday, October 11, 2014 .
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.
Device set to en locale shows the label as Monday, November 10, 2014 .
If you typed October 20, 2014 instead:
Convert a date from a string in the user's locale and calculate the difference between two days, in days
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 Star t , and then set the Text
property of a label to the following formula:
Convert both a date and time string in the current locale.
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.
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.
Device set to en locale shows the label as Saturday, October 11, 2014 01:50:24.765 PM .
As an alternative, you can specify hh:mm:ss.f or hh:mm:ss.ff to round the time to the nearest 10th or
100th of a second.
TimeValue
Name a text-input control FinishedAt , and set the Text property of a label to this formula:
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
11/19/2022 • 3 minutes to read • Edit Online
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.
For both functions, units can be Milliseconds , Seconds , Minutes , Hours , Days , Months , Quar ters , or Years .
By default, both functions use Days as 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 ] )
DateTime - Required. Date/time value to operate on.
Addition - Required. Number, in Units, to add to the DateTime.
Units - Optional. The type of Units to add: Milliseconds , Seconds , Minutes , Hours , Days , Months ,
Quar ters , or Years . If not specified, Days are used.
DateDiff ( StartDateTime, EndDateTime [, Units ] )
StartDateTime - Required. Starting date/time value.
EndDateTime - Required. Ending date/time value.
Units - Optional. The type of Units to subtract: Milliseconds , Seconds , Minutes , Hours , Days , Months ,
Quar ters , or Years . If not specified, Days are used.
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
F O RM UL A DESC RIP T IO N RESULT
Text( DateAdd( Now(), 3 ), Adds three days (default units) to the "18-07-2013 13:02"
"dd-mm-yyyy hh:mm" ) current date and time.
Text( DateAdd( Now(), 4, Hours ), Add four hours to the current date "15-07-2013 17:02"
"dd-mm-yyyy hh:mm" ) and time.
Text( DateAdd( Today(), 1, Adds one month to the current date, "15-08-2013 00:00"
Months ), without time as Today doesn't return
"dd-mm-yyyy hh:mm" ) a time component.
Text( DateAdd( Now(), 30, Subtracts 30 minutes from the current "15-07-2013 12:32"
Minutes ), date and time.
"dd-mm-yyyy hh:mm" )
Simple DateDiff
F O RM UL A DESC RIP T IO N RESULT
DateDiff( Now(), Today(), Minutes Returns the difference between the -782
) current date/time and the current date
only (no time) in minutes. Since the
Now is later than Today the result will
be negative.
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:
DateAdd( Now(), TimeZoneOffset(), Minutes )
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 .
Converting from UTC
To convert from UTC, subtract the TimeZoneOffset (by adding the negative) for the given time.
For example, imagine the UTC date and time July 15, 2013, 8:02 PM is stored in a variable named Star tTime .
To adjust the time for the user's time zone, use:
DateAdd( Star tTime, −TimeZoneOffset( Star tTime ), Minutes )
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
11/19/2022 • 4 minutes to read • Edit Online
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).
NOTE
UTCNow , UTCToday , and IsUTCToday are only available in Microsoft Dataverse for Teams formula columns, and
only for time-independent fields and values.
Now , Today , and IsToday are not available in Dataverse for Teams formula columns as evaluations are done without
the knowledge of the current user's local time zone.
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
Using the user's local time
Now ()
Today ()
IsToday ( DateTime )
DateTime - Required. The date/time value to test.
Using Coodinated Universal Time (UTC)
UTCNow ()
UTCToday ()
IsUTCToday ( TimeZoneIndependentTime )
TimeZoneIndependentDateTime - Required. The time zone indepdenent date/time value to test.
Examples
For the examples in this section, the current time is 8:58 PM on July 11, 2021 in the Pacific Time Zone (UTC-8)
and the language is en-us .
Text( Now(), "mm/dd/yyyy Retrieves the current date and time in "07/11/2021 20:58:00"
hh:mm:ss" ) the user's time zone, and displays it as
a string.
Text( Today(), "mm/dd/yyyy Retrieves the current date only, leaving "07/12/2021 00:00:00"
hh:mm:ss" ) the time portion as midnight, and
displays it as a string.
Text( DateAdd( Now(), 12 ), Retrieves the current date and time, "07/23/2021 20:58:00"
"mm/dd/yyyy hh:mm:ss" ) adds 12 days to the result, and
displays it as a string.
Text( DateAdd( Today(), 12 ), Retrieves the current date, adds 12 "07/23/2021 00:00:00"
"mm/dd/yyyy hh:mm:ss" ) days to the result, and displays it as a
string.
IsToday( DateAdd( Now(), 12 ) ) Tests whether the current date and false
time, plus 12 days, is between
midnight today and midnight
tomorrow.
IsToday( DateAdd( Today(), 12 ) ) Tests whether the current date, plus 12 false
days, is between midnight today and
midnight tomorrow.
F O RM UL A DESC RIP T IO N RESULT
3. Add a Label control, and set its Text property to this formula:
Text( CurrentTime, LongTime24 )
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 AutoStar t property to true and its Visible property to false .
The timer is invisible and starts automatically.
6. Set the screen's OnStar t 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 Test Studio
11/19/2022 • 2 minutes to read • Edit Online
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, as well as any messages for
both passed and failed assertions, are contained in a Traces table in the TestCaseResult record. The Traces table
has two properties, Message and Timestamp.
Trace messages can also be defined in your app. These can be viewed in the Power Apps Monitor tool along with
other app activities, to help in debugging or identifying issues with real-time diagnostic information for your
app. If you have allowed your app to send telemetry data to Azure Application Insights, the Trace function can
also be used to send custom event or diagnostic information to your Application Insights resource. You can
inspect this data in Application Insights to help diagnose problems or understand usage of your apps and
features. Trace information used in Tests will also be recorded in Application Insights. Test trace information will
not be available in the Monitor tool as the Monitor is connected to the app when it is played from the Canvas
studio.
Syntax
Trace(message, trace_severity, custom_record )
Message – Required. The information to be traced. In tests, this creates a record in the Traces table in the
TestCaseResult record.
Trace_severity - Optional. The severity level of the Trace recorded in Application Insights. Options are
TraceSeverity.Information, TraceSeverity.Warning or TraceSeverity.Error.
custom_record - Optional. A record containing custom data that will be recorded in Application Insights.
See Also
Test Studio Overview
Working with Test Studio
Trim and TrimEnds functions in Power Apps
11/19/2022 • 2 minutes to read • Edit Online
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 )
String - Required. The string of text to remove spaces from.
Trim ( SingleColumnTable )
TrimEnds ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of strings to remove spaces from.
Example
F O RM UL A DESC RIP T IO N RESULT
Trim( " Hello World " ) Removes all spaces from the start and "Hello World"
end of a string and extra spaces from
within the string.
TrimEnds( " Hello World " ) Removes all spaces from the start and "Hello World"
end of a string.
The following examples use a single-column collection, named Spaces , that contains these strings:
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:
ClearCollect( Spaces, [ " Jane Doe ", " Jack and Jill", "Already trimmed",
" Venus, Ear th, Mars ", "Oil and Water " ] )
Trim( Spaces ) Trims all spaces from the start and end
of each string and extra spaces from
within each string in the Spaces
collection.
TrimEnds( Spaces ) Trims all spaces from the start and end
of each string in the Spaces collection.
NOTE
Extra spaces don't appear if you display a collection by clicking or tapping Collections on the File menu. To verify string
length, use the Len function.
Trim and TrimEnds functions in Power Apps
11/19/2022 • 2 minutes to read • Edit Online
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 )
String - Required. The string of text to remove spaces from.
Trim ( SingleColumnTable )
TrimEnds ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of strings to remove spaces from.
Example
F O RM UL A DESC RIP T IO N RESULT
Trim( " Hello World " ) Removes all spaces from the start and "Hello World"
end of a string and extra spaces from
within the string.
TrimEnds( " Hello World " ) Removes all spaces from the start and "Hello World"
end of a string.
The following examples use a single-column collection, named Spaces , that contains these strings:
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:
ClearCollect( Spaces, [ " Jane Doe ", " Jack and Jill", "Already trimmed",
" Venus, Ear th, Mars ", "Oil and Water " ] )
Trim( Spaces ) Trims all spaces from the start and end
of each string and extra spaces from
within each string in the Spaces
collection.
TrimEnds( Spaces ) Trims all spaces from the start and end
of each string in the Spaces collection.
NOTE
Extra spaces don't appear if you display a collection by clicking or tapping Collections on the File menu. To verify string
length, use the Len function.
Int, Round, RoundDown, RoundUp, and Trunc
functions in Power Apps
11/19/2022 • 2 minutes to read • Edit Online
Rounds a number.
Greater than 0 The number is rounded to the right of Round( 12.37, 1 ) returns 12.4.
the decimal separator.
Less than 0 The number is rounded to the left of Round( 12.37, -1 ) returns 10.
the decimal separator.
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)
Number - Required. The number to round.
DecimalPlaces - Required. Number of decimal places to round to. Use a positive value to indicate decimal
places right of the decimal separator, a negative value to the left, and zero for a whole number.
Int (Number)
Trunc (Number)
Number - Required. The number to be rounded to an integer.
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).
ROUNDDOWN( X, [ 0, 1, 2
X INT( X ) ROUND( X, 2 ) ] ) ROUNDUP( X, [ 2 ] )
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:
Use the GroupBy function.
Use the Filter function to remove the entire group of records.
Use the Ungroup function.
You can also aggregate results based on a grouping:
Use the GroupBy function.
Use the AddColumns function with Sum , Average , and other aggregate functions to add a new column
which is an aggregate of the group tables.
Use the DropColumns function to drop the group table.
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.
ColumnName(s) - Required. The column names in Table by which to group records. These columns
become columns in the resulting table.
GroupColumnName - Required. The column name for the storage of record data not in the
ColumnName(s).
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".
Ungroup ( Table, GroupColumnName )
Table - Required. Table to be ungrouped.
GroupColumnName - Required. The column that contains the record data setup with the GroupBy
function.
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:
ClearCollect( CityPopulations,
{ City: "London", Country: "United Kingdom", Population: 8615000},
{ City: "Berlin", Country: "Germany", Population: 3562000},
{ City: "Madrid", Country: "Spain", Population: 3165000},
{ City: "Rome", Country: "Italy", Population: 2874000},
{ City: "Paris", Country: "France", Population: 2273000},
{ City: "Hamburg", Country: "Germany", Population: 1760000},
{ City: "Barcelona", Country: "Spain", Population: 1602000},
{ City: "Munich", Country: "Germany", Population: 1494000},
{ City: "Milan", Country: "Italy", Population: 1344000}
)
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:
ClearCollect( CitiesByCountr y, GroupBy( CityPopulations, "Countr y", "Cities" ) )
3. While holding down the Alt key, select the Group button.
You just created a collection, named CitiesByCountr y , in which the records of the previous collection are
grouped by the Countr y 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):
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" .
2. Set the OnSelect property of the "Sum" button to this formula:
ClearCollect( CityPopulationsSum, AddColumns( CitiesByCountr y, "Sum of City Populations",
Sum( Cities, Population ) ) )
Which results in:
AddColumns starts with the base CitiesByCountr y collection and adds a new column Sum of City
Populations . This column's values are calculated row-by-row, based on the formula Sum( Cities,
Population ) . AddColumns provides the value of the Cities column (a table) for each row, and Sum
adds up the Population for each row of this sub table.
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" .
4. Set the OnSelect property of the "SumOnly" button to this formula:
ClearCollect( CityPopulationsSumOnly, DropColumns( CityPopulationsSum, "Cities" ) )
Which results in:
Relate and unrelate records of two tables through a one-to-many or many-to-many relationship.
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.
You can use these functions only in behavior formulas.
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 )
Table1RelatedTable - Required. For a record of Table1, the table of Table2 records related through a one-to-
many or many-to-many relationship.
Table2Record - Required. The Table2 record to add to the relationship.
Unrelate ( Table1RelatedTable, Table2Record )
Table1RelatedTable - Required. For a record of Table1, the table of Table2 records related through a one-to-
many or many-to-many relationship.
Table2Record - Required. The Table2 record to remove from the relationship.
Examples
Consider a Products table with the following relationships as seen in the Power Apps portal's table viewer:
REL AT IO N SH IP DISP L AY N A M E REL AT ED TA B L E REL AT IO N SH IP T Y P E
Products and Reser vations are related through a One-to-Many relationship. To relate the first record of the
Reser vations table with the first record of the Products table:
Relate( First( Products ).Reservations, First( Reservations ) )
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:
Relate( First( Products ).Contacts, First( Contacts ) )
As Many-to-Many relationships are symmetric, we could also have done this in the opposite direction:
Relate( First( Contacts ).Products, First( Products ) )
or:
Unrelate( First( Contacts ).Products, First( Products ) )
The walk through that follows does exactly these operations on these tables using an app with Galler y 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.
1. Create a tablet app from blank.
2. On the View tab, select Data sources .
3. In the Data pane, select Add data > select Products .
The Products table is part of the sample data loaded above.
4. On the Inser t tab, add a blank vertical Galler y control.
5. Ensure that the control that you just added is named Galler y1 , and then move and resize it to fill the left-
hand side of the screen.
6. On the Proper ties tab, set Galler y1 's Items property to Products and its Layout to Image and title .
7. In Galler y1 , 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 Galler y1 . Add a second blank vertical Galler y
control, and ensure that it's named Galler y2 .
Galler y2 will show the reservations for whatever product the user selects in Galler y1 .
9. Move and resize Galler y2 to fill the upper-right quadrant of the screen.
10. (optional) Add the blue Label control above Galler y2 , as the next graphic shows.
11. In the formula bar, set the Items property of Galler y2 to Galler y1.Selected.Reser vations .
15. Scroll down in the Proper ties tab and set ComboBox1 's Allow multiple selection property to Off .
16. In the formula bar, set ComboBox1 's DefaultSelectedItems property to ThisItem.'Product
Reser vation' .
17. In Galler y2 , set NextArrow2 's OnSelect property to this formula:
When the user selects this icon, the current reservation changes to the product that the user selected in
ComboBox1 .
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 Galler y2_1 where users can assign each contact to
a product.
Many-to -many
Create a many-to-many relationship
The sample data doesn't include a many-to-many relationship, but you'll create one between the Products table
and the Contacts table. Users can relate each product to more than one contact and each contact to more than
one product.
1. From this page, select Data in the left navigation bar, and then select Tables .
2. Change the table filter to include all tables.
By default, sample tables don't appear.
5. In Galler y2 , 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 .
7. Set the Cancel icon's OnSelect property to this formula:
11. On the Proper ties tab, set Allow multiple selection to Off .
12. Insert an Add icon, and set its OnSelect property to this formula:
3. To create the reverse view, change these formulas on the controls of Screen1_1 :
Screen1_1.OnVisible = Refresh( Contacts )
Gallery1_1.Items = Contacts
Title1_1.Text = ThisItem.'Full Name'
Label1_1.Text = "Selected Contact Products"
Gallery2_1.Items = Gallery1_1.Selected.Products
Title2_1.Text = ThisItem.Name
Icon1_1.OnSelect = Unrelate( Gallery1_1.Selected.Products, ThisItem )
ComboBox1_1.Items = Products
Icon2_1.OnSelect = Relate( Gallery1_1.Selected.Products, ComboBox1_1.Selected )
The result will look very similar to the previous screen but comes at the relationship from the Contacts
side.
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
11/19/2022 • 3 minutes to read • Edit Online
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 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 [, 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.
All – Optional. In a collection, the same record may appear more than once. Specify the All argument to
update all copies of the record.
UpdateIf ( DataSource, Condition1, ChangeRecord1 [, Condition2, ChangeRecord2, ... ] )
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:
Step by step
1. Import or create a collection named Inventor y , and show it in a gallery as Show data in a gallery
describes.
2. Name the gallery ProductGaller y .
3. Add a slider named UnitsSold , and set its Max property to this expression:
ProductGaller y.Selected.UnitsInStock
4. Add a button, and set its OnSelect property to this formula:
UpdateIf(Inventor y, ProductName = ProductGaller y.Selected.ProductName,
{UnitsInStock :UnitsInStock-UnitsSold.Value})
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
11/19/2022 • 5 minutes to read • Edit Online
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.
If you specify the name of a variable that you've previously defined, UpdateContext sets the value of the
variable to the value that you specify.
If you specify the name of a variable that doesn't yet exist, UpdateContext creates a variable with that name
and sets the value of that variable to the value that you specify.
If you've previously defined a variable but don't specify it in this particular UpdateContext formula, its value
remains the same.
Context variables are implicitly created by using the UpdateContext or Navigate function. There is no explicit
declaration required. If you remove all the UpdateContext and Navigate references to a context variable, then
that context 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 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 ( { ContextVariable1: Value1 [, ContextVariable2: Value2 [, ... ] ] } )
ContextVariable1 - Required. The name of a context variable to create or update.
Value1 - Required. The value to assign to the context variable.
ContextVariable2: Value2, ... - Optional. Additional context variables to create or update and their values.
Examples
F O RM UL A DESC RIP T IO N RESULT
UpdateContext( { Counter : 1 } ) Creates or modifies the context Counter has the value 1 . You can
variable Counter , setting its value to reference that variable by using the
1. name Counter in a formula.
UpdateContext( { Counter : 2 } ) Sets the value of the Counter context Counter has the value 2 .
variable from the previous example to
2.
UpdateContext( Creates or modifies the context Name has the value Lily , and Score
{ Name: "Lily", Score: 10 } ) variables Name and Score , setting has the value 10 .
their values to Lily and 10
respectively.
UpdateContext( Creates or modifies the context Person has the value of record
{ Person: { Name: "Milton", variable Person , setting its value to a { Name: "Milton",
Address: "1 Main St" } } ) record. The record contains two Address: "1 Main St" } } .
columns, named Name and Address .
The value of the Name column is Reference this record as a whole with
Milton , and the value of the Address the name Person , or reference an
column is 1 Main St . individual column of this record with
Person.Name or Person.Address .
UpdateContext( { Person: Works with the Patch function to Person now has the value of record
Patch( Person, {Address: "2 Main update the Person context variable by { Name: "Milton",
St" } ) } ) setting the value of the Address Address: "2 Main St" } } .
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:
Navigate(Target, ScreenTransition.Fade, {Language:"English"})
4. Set the OnSelect property of the Spanish button to this expression:
Navigate(Target, ScreenTransition.Fade, {Language:"Spanish"})
5. On the Target screen, add a label, and set its Text property to this expression:
If(Language="English", "Hello!", "Hola!")
6. On the Target screen, select Shapes on the Inser t tab, and then select the Back arrow.
7. Set the Back arrow's OnSelect property to this formula:
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.
10. Press Esc to return to the default workspace.
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:
UpdateContext( { Name: "Lily", Score: 10 } )
Update and UpdateIf functions in Power Apps
11/19/2022 • 3 minutes to read • Edit Online
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 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 [, 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.
All – Optional. In a collection, the same record may appear more than once. Specify the All argument to
update all copies of the record.
UpdateIf ( DataSource, Condition1, ChangeRecord1 [, Condition2, ChangeRecord2, ... ] )
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:
Step by step
1. Import or create a collection named Inventor y , and show it in a gallery as Show data in a gallery
describes.
2. Name the gallery ProductGaller y .
3. Add a slider named UnitsSold , and set its Max property to this expression:
ProductGaller y.Selected.UnitsInStock
4. Add a button, and set its OnSelect property to this formula:
UpdateIf(Inventor y, ProductName = ProductGaller y.Selected.ProductName,
{UnitsInStock :UnitsInStock-UnitsSold.Value})
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
11/19/2022 • 2 minutes to read • Edit Online
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.
Lower converts any uppercase letters to lowercase.
Upper converts any lowercase letters to uppercase.
Proper converts the first letter in each word to uppercase if it's lowercase and converts any other uppercase
letters to lowercase.
All three functions ignore characters that aren't letters.
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 )
String - Required. The string to convert.
Lower ( SingleColumnTable )
Upper ( SingleColumnTable )
Proper ( SingleColumnTable )
SingleColumnTable - Required. A single-column table of strings to convert.
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 "E. E. Cummings"
to uppercase if it's lowercase, and
converts any other uppercase letters
to lowercase.
Single -column table
The examples in this section convert strings from the Address column of the People data source, which
contains this data:
Each formula returns a single-column table that contains the converted strings.
Step-by-step example
1. Add a Text input control, and name it Source .
2. Add a label, and set its Text property to this function:
Proper(Source.Text)
3. Press F5, and then type WE ARE THE BEST! into the Source box.
The label shows We Are The Best!
User function in Power Apps
11/19/2022 • 2 minutes to read • Edit Online
Description
The User function returns a record of information about the current user:
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.
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.
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:
Full Name: "John Doe"
Email address: "[email protected]"
Image:
F O RM UL A DESC RIP T IO N RESULT
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).
NOTE
UTCNow , UTCToday , and IsUTCToday are only available in Microsoft Dataverse for Teams formula columns, and
only for time-independent fields and values.
Now , Today , and IsToday are not available in Dataverse for Teams formula columns as evaluations are done without
the knowledge of the current user's local time zone.
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
Using the user's local time
Now ()
Today ()
IsToday ( DateTime )
DateTime - Required. The date/time value to test.
Using Coodinated Universal Time (UTC)
UTCNow ()
UTCToday ()
IsUTCToday ( TimeZoneIndependentTime )
TimeZoneIndependentDateTime - Required. The time zone indepdenent date/time value to test.
Examples
For the examples in this section, the current time is 8:58 PM on July 11, 2021 in the Pacific Time Zone (UTC-8)
and the language is en-us .
Text( Now(), "mm/dd/yyyy Retrieves the current date and time in "07/11/2021 20:58:00"
hh:mm:ss" ) the user's time zone, and displays it as
a string.
Text( Today(), "mm/dd/yyyy Retrieves the current date only, leaving "07/12/2021 00:00:00"
hh:mm:ss" ) the time portion as midnight, and
displays it as a string.
Text( DateAdd( Now(), 12 ), Retrieves the current date and time, "07/23/2021 20:58:00"
"mm/dd/yyyy hh:mm:ss" ) adds 12 days to the result, and
displays it as a string.
Text( DateAdd( Today(), 12 ), Retrieves the current date, adds 12 "07/23/2021 00:00:00"
"mm/dd/yyyy hh:mm:ss" ) days to the result, and displays it as a
string.
IsToday( DateAdd( Now(), 12 ) ) Tests whether the current date and false
time, plus 12 days, is between
midnight today and midnight
tomorrow.
IsToday( DateAdd( Today(), 12 ) ) Tests whether the current date, plus 12 false
days, is between midnight today and
midnight tomorrow.
F O RM UL A DESC RIP T IO N RESULT
3. Add a Label control, and set its Text property to this formula:
Text( CurrentTime, LongTime24 )
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 AutoStar t property to true and its Visible property to false .
The timer is invisible and starts automatically.
6. Set the screen's OnStar t 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
11/19/2022 • 4 minutes to read • Edit Online
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).
NOTE
UTCNow , UTCToday , and IsUTCToday are only available in Microsoft Dataverse for Teams formula columns, and
only for time-independent fields and values.
Now , Today , and IsToday are not available in Dataverse for Teams formula columns as evaluations are done without
the knowledge of the current user's local time zone.
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
Using the user's local time
Now ()
Today ()
IsToday ( DateTime )
DateTime - Required. The date/time value to test.
Using Coodinated Universal Time (UTC)
UTCNow ()
UTCToday ()
IsUTCToday ( TimeZoneIndependentTime )
TimeZoneIndependentDateTime - Required. The time zone indepdenent date/time value to test.
Examples
For the examples in this section, the current time is 8:58 PM on July 11, 2021 in the Pacific Time Zone (UTC-8)
and the language is en-us .
Text( Now(), "mm/dd/yyyy Retrieves the current date and time in "07/11/2021 20:58:00"
hh:mm:ss" ) the user's time zone, and displays it as
a string.
Text( Today(), "mm/dd/yyyy Retrieves the current date only, leaving "07/12/2021 00:00:00"
hh:mm:ss" ) the time portion as midnight, and
displays it as a string.
Text( DateAdd( Now(), 12 ), Retrieves the current date and time, "07/23/2021 20:58:00"
"mm/dd/yyyy hh:mm:ss" ) adds 12 days to the result, and
displays it as a string.
Text( DateAdd( Today(), 12 ), Retrieves the current date, adds 12 "07/23/2021 00:00:00"
"mm/dd/yyyy hh:mm:ss" ) days to the result, and displays it as a
string.
IsToday( DateAdd( Now(), 12 ) ) Tests whether the current date and false
time, plus 12 days, is between
midnight today and midnight
tomorrow.
IsToday( DateAdd( Today(), 12 ) ) Tests whether the current date, plus 12 false
days, is between midnight today and
midnight tomorrow.
F O RM UL A DESC RIP T IO N RESULT
3. Add a Label control, and set its Text property to this formula:
Text( CurrentTime, LongTime24 )
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 AutoStar t property to true and its Visible property to false .
The timer is invisible and starts automatically.
6. Set the screen's OnStar t 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
11/19/2022 • 2 minutes to read • Edit Online
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:
whether a column requires a value
how long a string of text can be
how high and low a number can be
how early and late a date can be
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 )
DataSource – Required. The data source to validate with.
Column – Required. The column to validate.
Value – Required. The value for the selected column to be validated.
Validate ( DataSource, OriginalRecord, Updates )
DataSource – Required. The data source to validate with.
OriginalRecord - Required. The record to which updates are to be validated.
Updates - Required. The changes to apply to the original record.
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 with a single column
F O RM UL A DESC RIP T IO N RESULT
Validate( Scores, Percentage, 120 Checks whether 120 is a valid value "Values must be between 0 and 100."
) for the Percentage column in the
Scores data source.
Validate( Scores, EditRecord, Checks whether values in all columns "Values must be between 0 and 100."
Galler y.Updates ) are valid for the Scores data source. In
this example, the value in the
Percentage column is 120 .
Value function in Power Apps
11/19/2022 • 2 minutes to read • Edit Online
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.
Notes on the format of the string:
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".
If the number is not in a proper format, Value will return blank.
To convert date and time values, use the DateValue , TimeValue , or DateTimeValue functions.
Syntax
Value ( String [, LanguageTag ] )
String - Required. String to convert to a numeric value.
LanguageTag - Optional. The language tag in which to parse the string. If not specified, the language of the
current user is used.
Value ( Untyped )
Untyped - Required. Untyped object that represents a number. Acceptable values are dependent on the
untyped provider. For JSON , the untyped object is expected to be a JSON number. Values inside of a string,
such as "15" or "12.5" , are not accepted. Consider converting such untyped objects to Text first, then to a
value. Keep in mind that locale-related formats are important considerations when communicating with
external systems.
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", "es-ES" ) "es-ES" is the language tag for Spanish 123456
in Spain. In Spain, a period is a
thousands separator.
Value( "123,456", "es-ES" ) "es-ES" is the language tag for Spanish 123.456
in Spain. In Spain, a comma is the
decimal separator.
Value( "$ 12.34" ) The currency symbol for the current 12.34
language is ignored.
Description
The Average function calculates the average, or arithmetic mean, of its arguments.
The Max function finds the maximum value.
The Min function finds the minimum value.
The Sum function calculates the sum of its arguments.
The StdevP function calculates the standard deviation of its arguments.
The VarP function calculates the variance of its arguments.
You can supply the values for these functions as:
Separate arguments. For example, Sum( 1, 2, 3 ) returns 6.
A table and a formula to operate over that table. The aggregate will be calculated on the values of the
formula for each 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.
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, ... ] )
Max ( NumericalFormula1, [ NumericalFormula2, ... ] )
Min ( NumericalFormula1, [ NumericalFormula2, ... ] )
Sum ( NumericalFormula1, [ NumericalFormula2, ... ] )
StdevP ( NumericalFormula1, [ NumericalFormula2, ... ] )
VarP ( NumericalFormula1, [ NumericalFormula2, ... ] )
NumericalFormula(s) - Required. Numeric values to operate on.
Average ( Table, NumericalFormula )
Max ( Table, NumericalFormula )
Min ( Table, NumericalFormula )
Sum ( Table, NumericalFormula )
StdevP ( Table, NumericalFormula )
VarP ( Table, NumericalFormula )
Table - Required. Table to operate on.
NumericalFormula - Required. Formula to evaluate for each record. The result of this formula is used for the
aggregation. You can use columns of the table in the formula.
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:
Sum(Sales, CostPerUnit * UnitsSold)
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.
Average(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the average of all values to
which the sliders were set.
Max(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the maximum of all values to
which the sliders were set.
Min(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the minimum of all values to which
the sliders were set.
StdevP(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the standard deviation of all
values to which the sliders were set.
VarP(Slider1.Value, Slider2.Value, Slider3.Value) : The label would show the variance of all values to which
the sliders were set.
EditForm, NewForm, SubmitForm, ResetForm, and
ViewForm functions in Power Apps
11/19/2022 • 5 minutes to read • Edit Online
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:
M O DE DESC RIP T IO N
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.
These functions return no values.
You can use these functions only in behavior formulas.
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 validation passes, SubmitForm submits the change to the data source.
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):
Syntax
SubmitForm ( FormName )
FormName - Required. Form control to submit to the data source.
EditForm ( FormName )
FormName - Required. Form control to switch to FormMode.Edit mode.
NewForm ( FormName )
FormName - Required. Form control to switch to FormMode.New mode.
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 )
FormName - Required. Form control to switch to FormMode.View mode.
Examples
See Understand data forms for complete examples.
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:
ResetForm( EditForm ); Back()
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:
NewForm( EditForm ); Navigate( EditScreen, None )
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
11/19/2022 • 2 minutes to read • Edit Online
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 )
DateTime - Required. Date/Time value to operate on.
Weekday ( DateTime [, WeekdayFirst ] )
DateTime - Required. Date/Time value to operate on.
WeekdayFirst - Optional. Excel code specifying which day starts the week. If not supplied, 1 (Sunday first) is
used.
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 ])
DateTime - Required. Date/Time value to operate on.
StartOfWeek - Optional. Excel code or StartOfWeek enumeration that determines which day the week begins.
ISOWeekNum (DateTime)
DateTime - Required. Date/Time value to operate on. The week always begins on Monday.
Examples
First and last calendar weeks of 2021
W EEK N UM ( DAT E,
STA RTO F W EEK . W EDN ESDAY
DAT E W EEK N UM ( DAT E ) ISO W EEK N UM ( DAT E ) )
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
Simple named values
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
With( { AnnualRate: RateSlider/8/100, // slider moves in 1/8th increments and convert to decimal
Amount: AmountSlider*10000, // slider moves by 10,000 increment
Years: YearsSlider, // slider moves in single year increments, no adjustment
required
AnnualPayments: 12 }, // number of payments per year
With( { r: AnnualRate/AnnualPayments, // interest rate
P: Amount, // loan amount
n: Years*AnnualPayments }, // number of payments
r*P / (1 - (1+r)^-n) // standard interest calculation
)
)
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.
Here are the detailed instructions for creating this app:
1. Create a new app.
2. Add a Slider control and name it RateSlider . Set its Max property to 48.
3. Add a Label control to the left of the slider control. Set its Text property to "Interest Rate:" .
4. Add a Label control to the right of the slider control. Set its Text property to the formula RateSlider/8 &
" %" .
5. Add another Slider control and name it AmountSlider . Set its Max property to 60.
6. Add a Label control to the left of this slider control. Set its Text property to "Loan Amount:" .
7. Add a Label control to the right of this slider control. Set its Text property to the formula AmountSlider/8
* 10000 .
8. Add another Slider control and name it YearsSlider . Set its Max property to 40.
9. Add a Label control to the left of this slider control. Set its Text property to "Number of Years:" .
10. Add a Label control to the right of this slider control. Set its Text property to the formula YearsSlider .
11. Add a Label control and set its Text property to the formula shown above.
12. Add a Label control to the left of the last label control. Set its Text property to "Recurring Monthly
Payment:" .
Primary key returned from Patch
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.
Extracted values with a regular expression
With(
Match( "PT2H1M39S", "PT(?:(?<hours>\d+)H)?(?:(?<minutes>\d+)M)?(?:(?<seconds>\d+)S)?" ),
Time( Value( hours ), Value( minutes ), Value( seconds ) )
)
// 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.
Map a record in a component
See Map record.
Day, Month, Year, Hour, Minute, Second, and
Weekday functions in Power Apps
11/19/2022 • 2 minutes to read • Edit Online
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 )
DateTime - Required. Date/Time value to operate on.
Weekday ( DateTime [, WeekdayFirst ] )
DateTime - Required. Date/Time value to operate on.
WeekdayFirst - Optional. Excel code specifying which day starts the week. If not supplied, 1 (Sunday first) is
used.
Examples
For the following example, the current time is 3:59:37 PM on Thursday, April 9, 2015 .