One of the keys to reusing a form for both inserting new records and displaying existing record detail is the ability to determine if the form is currently in insert mode or detail mode. There are several ways to determine this at runtime so you can take the necessary steps depeding on the current form mode.
Out of the box, there are three defined form types: Detail, Insert, & List
Some of the code we’ll use will differ whether you’re using a C# Snippet Action (where the code is added to the form itself) or a Code Snippet Action (where the code is added to a separate assembly and you’re passed an adapter object to access limited form properties).
From a C# Snippet Action
Use the following code to access the exposed EntityForm property of the form and determine the form mode.
From a Code Snippet Action
For a Code Snippet Action, you’ll need to do things a little differently. In a Code Snippet Action you’re only passed an adapter, or a wrapper, for the form, not the form itself. So, the problem is that you cannot access the page’s EntityPage reference. You can still get to it however, you’ll just have a few extra steps to dig through. Luckily, the form adapter exposes the SmartPart via the NativeForm property.
// First get a reference to the underlying SmartPart itself
Checking the Entity’s ID Property
One last way you can use to check to see if the page is in Insert mode is to check the entity’s Id property. If it is null then you have a new entity, not yet persisted to the database.
if (myentity.Id == null)
The problem is that it is possible that this won’t infer the correct mode. That is telling you that the object hasn’t yet been persisted to the database, which might be enough, but you might want different behavior for new objects on the form vs the form being in insert mode itself. Just make sure that if you use this method to determine the page mode that you understand the differences so you know what you’re really checking.