Each time we create or draw an element in Revit, a new record is added to the Revit database. This could be a wall, a window, a floor, and so on. These new records are identified by an ID, which is a number stored in a class called ElementId.
When we develop an add-in that generates elements, these elements receive new IDs. Creating elements through code can take two forms: either using Document.Create or through Prompts (Prompts is not the same as PostableCommand). For instance, creating a dimension using Document.NewDimension(View, Line, ReferenceArray)
through Document.Create results in a Dimension instance.
Obtaining the new ID from Document.Create is straightforward because the method returns the newly created element. However, dealing with Prompts is a bit more complex.
Prompts involve handing over control to the user to place and create elements before returning to the code session. This disconnection of sessions restricts access to the created elements. To work around this, one approach is to gather all the newly created IDs from the project, re-collect them after the session ends, and then filter out the existing IDs to identify the newly created elements. Below is a snippet I have created for this scenario:
FamilyInstanceFilter familyInsFilter = new FamilyInstanceFilter(symbol.Document, symbol.Id);
// collect all existing instanced and store their ids
var oldIds = new FilteredElementCollector(symbol.Document, symbol.Document.ActiveView.Id)
.WherePasses(familyInsFilter)
.ToElementIds();
try
{
// Ask user to place a familyInstance
uiDoc.PromptForFamilyInstancePlacement(symbol);
}
catch (Autodesk.Revit.Exceptions.OperationCanceledException ex)
{
// user has exited the operation
}
catch (Exception ex)
{
// something bad happened abort
return;
}
// Again collect all existing instances, and compare it to the old collection
var newFamilyInstanceIds = new FilteredElementCollector(symbol.Document, symbol.Document.ActiveView.Id)
.WherePasses(familyInsFilter)
.ToElementIds()
.Except(oldIds);
In the above example, I used a prompt to create familyinstance that essentially asks the user to choose where to position these familyInstances. After creating them, we compare the collection results to extract the newly created family IDs.