Today I would like to discuss whether we can access global variables in table or page from table extensions or page extensions?
I was asked this question last week. In conclusion, we can, but not completely.
Let’s see an example.
First, create a Page Extension to extend the standard General Journal page.
As you know, the Batch Name of this page is a global variable.
When we try to access it in Page Extension, it gives error.
The name ‘CurrentJnlBatchName’ does not exist in the current context
So it is generally understood that we cannot access global variables in extensions. But see the next example.
Although we don’t declare, we can access the variables from DimVisible1 to DimVisible8 directly. And they are identified as a global variable.
So you can set values directly in the Page Extension.
Why is there this difference? Let’s look at the standard code again.
Different from ‘CurrentJnlBatchName’, they are all defined as protected var.
Protected Variables: The
protected keyword can be used to make variables accessible between tables and table extensions and between pages and page extensions. If you want to only expose some variables as
protected, you must create two sections of
var declarations. See the syntax below.
APPLIES TO: Business Central 2019 release wave 2 and later
protected var myInt: Integer; // protected var var myLocalInt: Integer; // local var
Let’s do another test.
I copied the standard General Journal page to create a new General Journal page.
Then moved the CurrentJnlBatchName variable to the protected var.
Create another new Project (Extension) to extend the new General Journal page just created.
Create a new action to change CurrentJnlBatchName variable. (Emmm, this may not be a great example, but I think it’s the most intuitive)
Also, Microsoft’s documentation doesn’t say much about Protected Variables, and I didn’t find any difference other than whether or not they are accessible in Extension. Its behavior is the same as normal Global Variables.
As you’ve read this far, I’m sure you’ve noticed that we can’t access variables if they’re not defined to Protected in the standard code. Of course, Microsoft cannot set all variables to protected for some security and other reasons. And we can’t modify the standard code in SaaS. At this time, we can rely on some predefined events.
For example: In page 39 “General Journal”
Update 2023.10.12: CurrentJnlBatchName has been added as Protected var by Microsoft
Hope this will help.
Thanks for reading.