Is there a way to create/remove view types through the API?
To clarify what I mean- manual process in Revit is here: (Create a view type)
You can create view types for plans, elevations, sections, 3D views, drafting views, legends, and schedules.
I haven't found reference in the API yet- but just started searching. Seems to be scarce and I am a little concerned as you cannot get view types thorugh a transfer project standards.
Solved! Go to Solution.
Solved by GallowayUS_com_RonAllen1. Go to Solution.
This works:
##https://forum.dynamobim.com/t/python-create-new-viewfamilytype/37755
import clr
#Import the Revit API
clr.AddReference('RevitAPI')
import Autodesk
from Autodesk.Revit.DB import *
#Import DocumentManager and TransactionManager
clr.AddReference('RevitServices')
import RevitServices
from RevitServices.Persistence import DocumentManager
#from RevitServices.Transactions import TransactionManager
#Reference the active Document and application
doc = DocumentManager.Instance.CurrentDBDocument
##fec = FilteredElementCollector(doc).OfClass(ViewFamilyType).ToElements() ##Works returns ViewFamilyTypes
fec = FilteredElementCollector(doc).OfClass(ViewFamilyType).ToElements()
#vft = [x.Id for x in fec if x.ViewFamily == ViewFamily.StructuralPlan][0] #This gets the Id of the ViewFamilyType,
#and is sort of what Jeremy does with the Linq method, but it i don't think it can be implemented the same way.
#Instead I'm using a list comprehension.
OUT = fec
This from Sean Page works:
#Sean Page, 2021
#https://forum.dynamobim.com/t/view-family-types-selection/22359/15
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
from Autodesk.Revit.DB.Structure import *
clr.AddReference('RevitAPIUI')
from Autodesk.Revit.UI import *
clr.AddReference('System')
from System.Collections.Generic import List
clr.AddReference('RevitNodes')
import Revit
clr.ImportExtensions(Revit.GeometryConversion)
clr.ImportExtensions(Revit.Elements)
clr.AddReference('RevitServices')
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
doc = DocumentManager.Instance.CurrentDBDocument
uidoc=DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument
#Preparing input from dynamo to revit
names = IN[0]
results = []
#Do some action in a Transaction
#TransactionManager.Instance.EnsureInTransaction(doc)
ViewFamilyTypes = FilteredElementCollector(doc).OfClass(ViewFamilyType).ToElements()
for name in names:
for VFT in ViewFamilyTypes:
nm = VFT.get_Parameter(BuiltInParameter.ALL_MODEL_TYPE_NAME).AsString()
if name == nm:
results.append(VFT)
#TransactionManager.Instance.TransactionTaskDone()
OUT = results
Edited the wrong post : (
Warning: TypeError : No method matches given arguments for Duplicate: () [' File "<string>", line 113, in <module>\n', ' File "<string>", line 99, in GetDraftingViewTypeByName\n']
# Load the Python Standard and DesignScript Libraries
import sys
import clr
##https://forum.dynamobim.com/t/collecting-all-elements-of-family-types-in-active-view/19838/2
from Autodesk.Revit.DB import FilteredElementCollector
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
# Drafting Views
from Autodesk.Revit.DB import FilteredElementCollector, BuiltInCategory, BuiltInParameter
from Autodesk.Revit.DB import ViewFamilyType, ViewDrafting, Element
from Autodesk.Revit.DB import ViewFamily
from Autodesk.Revit.DB import Transaction
doc = DocumentManager.Instance.CurrentDBDocument
#######################################################
def GetDraftingViews():
##https://forums.autodesk.com/t5/revit-api-forum/view3d-collector/td-p/5277451
DraftingViewsList = FilteredElementCollector(doc).OfClass(ViewDrafting).ToElements()
##DraftingViewTemplates = [v.Id for v in DraftingViewsList if v.IsTemplate == True]
DraftingViewsList = [v for v in DraftingViewsList if v.IsTemplate == False]
return [DraftingViewsList]
def GetDraftingViewTemplates():
##https://forums.autodesk.com/t5/revit-api-forum/view3d-collector/td-p/5277451
DraftingViewsList = FilteredElementCollector(doc).OfClass(ViewDrafting).ToElements()
DraftingViewTemplates = [v for v in DraftingViewsList if v.IsTemplate == True]
##DraftingViewsList = [v.Id for v in DraftingViewsList if v.IsTemplate == False]
return [DraftingViewTemplates]
def GetNameByID(oID): ##GenericAnnotationFamilyType".Name"
return doc.GetElement(oID).get_Parameter(BuiltInParameter.ALL_MODEL_TYPE_NAME).AsString()
def GetDraftingView_AllTypes(): ##Returns all draft view family types
viewfamily_types = FilteredElementCollector(doc).OfClass(ViewFamilyType)
DraftViewTypes=[]
for i in viewfamily_types:
if i.ViewFamily == ViewFamily.Drafting: ##*.ViewFamily Backwards 'parent' ref I've been looking for!##<<<<<<<<<<<<<<<<<<<<<<<<<<HERE
DraftViewTypes.append( i)
return DraftViewTypes
def GetDraftingViewByBame(strName=""): ##Check if drafting view existds = if not, create it and assign view name
if not strName == "": ##If string name is set look for the drafting view
DraftingView = FilteredElementCollector(doc).OfClass(ViewDrafting).ToElements() ##Get all drafting views
DraftingView = [v for v in DraftingView if v.Name == strName] ##Return Drafting view for each Drafting view eq. Name
if DraftingView:
DraftingView =DraftingView[0] ##Return single item not list<<<<<<<<<<<<<<<
if not DraftingView: ##If no drafting view found
drafting_type_id = get_drafting_type_id() ##Get TYPE ID
DraftingView = ViewDrafting.Create(doc, drafting_type_id) ##Create View
##After creating view-
if not strName=="" : ##IF string is not null set the name of the new view
DraftingView.Name = strName
return DraftingView ##Return single value
def GetDraftingViewType():
##Selects First available ViewType that Matches Drafting Type.##
viewfamily_types = FilteredElementCollector(doc).OfClass(ViewFamilyType)
for i in viewfamily_types:
if i.ViewFamily == ViewFamily.Drafting: ##*.ViewFamily Backwards 'parent' ref I've been looking for!
return i
##If view doesn't exist create and delete
def Main():
##draftview = get_drafting_type()
viewfamily_types = UnwrapElement(FilteredElementCollector(doc).OfClass(ViewFamilyType).ToElements())
##viewfamily_types = UnwrapElement(FilteredElementCollector(doc).OfClass(ViewFamilyType).OfClass(ViewDrafting))
return viewfamily_types
#return GetNameByID(viewfamily_types)
########################################################
def GetDraftingViewTypeByName(DraftViewTypeName=""): ##Returns Default "Drafting View" ViewType or name as specified or creates ViewType by DraftViewTypeName
##Trans_GDVBTN = Transaction (doc, 'Drafting View Type')
##Trans_GDVBTN.Start()
##Get all View_Family_Types from Drafting Views:
DraftViewTypes = [ x for x in FilteredElementCollector(doc).OfClass(ViewFamilyType) if x.ViewFamily == ViewFamily.Drafting ]
found=False ##Found as false
if not DraftViewTypeName == "": ##If view name is not null
for DraftViewType in DraftViewTypes: ##<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<DEBUG
#return GetNameByID(v.Id) ##<<<<<<<<<<<<<<<<<THIS WORKS TO GET THE NAME
#return v.Name ##<<<<<<<<<<<<<<<<<<<<<<<<<<<<THIS BREAKS
#return type(v),dir(v) ##<<<<<<<<<<<<<<<<<<<<List all methods / Properties
if GetNameByID(DraftViewType.Id) == DraftViewTypeName:
found=True
break
if not found:
DraftViewType = None
##FAILS##viewfamily_types = [v for v in viewfamily_types if v.Name == strName] ##Return Drafting view for each Drafting view eq. Name
if DraftViewType == None: ##If no DraftingViewType found
##Duplicate existing type
##REname copy ##NOTE Must be in transaction to rename and apply!
DraftViewTypes = DraftViewTypes[0] ##Set to base type
DraftViewType = DraftViewTypes.Duplicate ##(strName) as ViewFamilyType
##After Duplicating viewType-
if not DraftViewTypeName=="" : ##IF string is not null set the name of the new view
DraftViewType.Name = DraftViewTypeName
##Trans_GDVBTN.Commit() ##Commit transaction - will see if we can do paralell with another transaction per API
return DraftViewType ##Return list
##############
t = Transaction (doc, 'Create Drafting View Type')
t.Start()
DVT=GetDraftingViewTypeByName("Test3") ## GetDraftingView_AllTypes()
#DVT=GetDraftingView_AllTypes()
#DVT[1].Name="Test2" ##Works... but cannot read DVT[1].Name??? BUG in Pyhon PER:.Name
#DVT = [I.Name for I in DVT]
##OUT =DVT[0].Name ##[v.Name for v in DVT] ##Cannot Read?
#OUT=GetDraftingViewTypeByName ("NewType")
##GetDraftingView ()
OUT=DVT
t.Commit()
Where:
##Quick return of some of the variables
return type(DraftViewTypes), type(ViewFamilyType), dir(DraftViewTypes)
[
[
Autodesk.Revit.DB.ViewFamilyType, ##RETURN Type of "DraftViewTypes"
<class 'CLR.CLR Metatype'>, ##RETURN Type of our variable (ViewFamilyType)
[ ##Return dir() of our variable
ArePhasesModifiable,
AssemblyInstanceId,
CanBeCopied,
CanBeDeleted,
CanBeHidden,
CanBeLocked,
CanBeRenamed,
CanDeleteSubelement,
CanHaveAnalyticalModel,
CanHaveTypeAssigned,
Category,
ChangeTypeId,
CreatedPhaseId,
DefaultTemplateId,
DeleteEntity,
DeleteSubelement,
DeleteSubelements,
DemolishedPhaseId,
DesignOption,
Dispose,
Document,
Duplicate, ##Duplicate is an optoion...
Equals,
FamilyName,
Finalize,
GetAnalyticalModel,
GetAnalyticalModelId,
GetChangeTypeAny,
GetChangeTypeElementAddition,
GetChangeTypeElementDeletion,
GetChangeTypeGeometry,
GetChangeTypeParameter,
GetDependentElements,
GetEntity,
GetEntitySchemaGuids,
GetExternalFileReference,
GetExternalResourceReference,
GetExternalResourceReferences,
GetGeneratingElementIds,
GetGeometryObjectFromReference,
GetHashCode,
GetMaterialArea,
GetMaterialIds,
GetMaterialVolume,
GetMonitoredLinkElementIds,
GetMonitoredLocalElementIds,
GetOrderedParameters,
GetParameter,
GetParameterFormatOptions,
GetParameters,
GetPhaseStatus,
GetPreviewImage,
GetSimilarTypes,
GetSubelements,
GetType,
GetTypeId,
GetValidTypes,
GroupId,
HasPhases,
Id,
IsCreatedPhaseOrderValid,
IsDemolishedPhaseOrderValid,
IsExternalFileReference,
IsHidden,
IsMonitoringLinkElement,
IsMonitoringLocalElement,
IsPhaseCreatedValid,
IsPhaseDemolishedValid,
IsSimilarType,
IsTransient,
IsValidDefaultFamilyType,
IsValidDefaultTemplate,
IsValidObject,
IsValidType,
LevelId,
Location,
LookupParameter,
MemberwiseClone,
Name,
Overloads,
OwnerViewId,
Parameters,
ParametersMap,
Pinned,
PlanViewDirection,
ReferenceEquals,
RefersToExternalResourceReference,
RefersToExternalResourceReferences,
ReleaseUnmanagedResources,
SetEntity,
ToString,
UniqueId,
VersionGuid,
ViewFamily,
ViewSpecific,
WorksetId,
__call__,
__class__,
__delattr__,
__delitem__,
__dir__,
__doc__,
__enter__,
__eq__,
__exit__,
__format__,
__ge__,
__getattribute__,
__getitem__,
__gt__,
__hash__,
__init__,
__init_subclass__,
__iter__,
__le__,
__lt__,
__module__,
__ne__,
__new__,
__overloads__,
__reduce__,
__reduce_ex__,
__repr__,
__setattr__,
__setitem__,
__sizeof__,
__str__,
__subclasshook__,
getBoundingBox,
get_AssemblyInstanceId,
get_BoundingBox,
get_CanBeCopied,
get_CanBeDeleted,
get_CanBeRenamed,
get_Category,
get_CreatedPhaseId,
get_DefaultTemplateId,
get_DemolishedPhaseId,
get_DesignOption,
get_Document,
get_FamilyName,
get_Geometry,
get_GroupId,
get_Id,
get_IsTransient,
get_IsValidObject,
get_LevelId,
get_Location,
get_Name,
get_OwnerViewId,
get_Parameter,
get_Parameters,
get_ParametersMap,
get_Pinned,
get_PlanViewDirection,
get_UniqueId,
get_VersionGuid,
get_ViewFamily,
get_ViewSpecific,
get_WorksetId,
setElementType,
set_CreatedPhaseId,
set_DefaultTemplateId,
set_DemolishedPhaseId,
set_Name,
set_Pinned,
set_PlanViewDirection
]
]
]
Two seconds after I posted that tried yet another variation and it worked!
DVT=GetDraftingViewTypeByName("Test3") ## GetDraftingView_AllTypes()
OUT=DVT
and:
Creates it if it doesn't exist AND passes it back if it does!
# Load the Python Standard and DesignScript Libraries
import sys
import clr
##https://forum.dynamobim.com/t/collecting-all-elements-of-family-types-in-active-view/19838/2
from Autodesk.Revit.DB import FilteredElementCollector
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
# Drafting Views
from Autodesk.Revit.DB import FilteredElementCollector, BuiltInCategory, BuiltInParameter
from Autodesk.Revit.DB import ViewFamilyType, ViewDrafting, Element
from Autodesk.Revit.DB import ViewFamily
from Autodesk.Revit.DB import Transaction
doc = DocumentManager.Instance.CurrentDBDocument
#######################################################
def GetDraftingViews():
##https://forums.autodesk.com/t5/revit-api-forum/view3d-collector/td-p/5277451
DraftingViewsList = FilteredElementCollector(doc).OfClass(ViewDrafting).ToElements()
##DraftingViewTemplates = [v.Id for v in DraftingViewsList if v.IsTemplate == True]
DraftingViewsList = [v for v in DraftingViewsList if v.IsTemplate == False]
return [DraftingViewsList]
def GetDraftingViewTemplates():
##https://forums.autodesk.com/t5/revit-api-forum/view3d-collector/td-p/5277451
DraftingViewsList = FilteredElementCollector(doc).OfClass(ViewDrafting).ToElements()
DraftingViewTemplates = [v for v in DraftingViewsList if v.IsTemplate == True]
##DraftingViewsList = [v.Id for v in DraftingViewsList if v.IsTemplate == False]
return [DraftingViewTemplates]
def GetNameByID(oID): ##GenericAnnotationFamilyType".Name"
return doc.GetElement(oID).get_Parameter(BuiltInParameter.ALL_MODEL_TYPE_NAME).AsString()
def GetDraftingView_AllTypes(): ##Returns all draft view family types
viewfamily_types = FilteredElementCollector(doc).OfClass(ViewFamilyType)
DraftViewTypes=[]
for i in viewfamily_types:
if i.ViewFamily == ViewFamily.Drafting: ##*.ViewFamily Backwards 'parent' ref I've been looking for!##<<<<<<<<<<<<<<<<<<<<<<<<<<HERE
DraftViewTypes.append( i)
return DraftViewTypes
def GetDraftingViewByBame(strName=""): ##Check if drafting view existds = if not, create it and assign view name
if not strName == "": ##If string name is set look for the drafting view
DraftingView = FilteredElementCollector(doc).OfClass(ViewDrafting).ToElements() ##Get all drafting views
DraftingView = [v for v in DraftingView if v.Name == strName] ##Return Drafting view for each Drafting view eq. Name
if DraftingView:
DraftingView =DraftingView[0] ##Return single item not list<<<<<<<<<<<<<<<
if not DraftingView: ##If no drafting view found
drafting_type_id = get_drafting_type_id() ##Get TYPE ID
DraftingView = ViewDrafting.Create(doc, drafting_type_id) ##Create View
##After creating view-
if not strName=="" : ##IF string is not null set the name of the new view
DraftingView.Name = strName
return DraftingView ##Return single value
def GetDraftingViewType():
##Selects First available ViewType that Matches Drafting Type.##
viewfamily_types = FilteredElementCollector(doc).OfClass(ViewFamilyType)
for i in viewfamily_types:
if i.ViewFamily == ViewFamily.Drafting: ##*.ViewFamily Backwards 'parent' ref I've been looking for!
return i
##If view doesn't exist create and delete
def Main():
##draftview = get_drafting_type()
viewfamily_types = UnwrapElement(FilteredElementCollector(doc).OfClass(ViewFamilyType).ToElements())
##viewfamily_types = UnwrapElement(FilteredElementCollector(doc).OfClass(ViewFamilyType).OfClass(ViewDrafting))
return viewfamily_types
#return GetNameByID(viewfamily_types)
########################################################
def GetDraftingViewTypeByName(DraftViewTypeName=""): ##Returns Default "Drafting View" ViewType or name as specified or creates ViewType by DraftViewTypeName
##Trans_GDVBTN = Transaction (doc, 'Drafting View Type')
##Trans_GDVBTN.Start()
##Get all View_Family_Types from Drafting Views:
DraftViewTypes = [ x for x in FilteredElementCollector(doc).OfClass(ViewFamilyType) if x.ViewFamily == ViewFamily.Drafting ]
found=False ##Found as false
if not DraftViewTypeName == "": ##If view name is not null
for DraftViewType in DraftViewTypes: ##<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<DEBUG
#return GetNameByID(v.Id) ##<<<<<<<<<<<<<<<<<THIS WORKS TO GET THE NAME
#return v.Name ##<<<<<<<<<<<<<<<<<<<<<<<<<<<<THIS BREAKS
#return type(v),dir(v) ##<<<<<<<<<<<<<<<<<<<<List all methods / Properties
if GetNameByID(DraftViewType.Id) == DraftViewTypeName:
found=True
break
if not found:
DraftViewType = None
##FAILS##viewfamily_types = [v for v in viewfamily_types if v.Name == strName] ##Return Drafting view for each Drafting view eq. Name
if DraftViewType == None: ##If no DraftingViewType found
##Duplicate existing type
##REname copy ##NOTE Must be in transaction to rename and apply!
DraftViewTypes = DraftViewTypes[0] ##Set to base type
DraftViewType = DraftViewTypes.Duplicate(DraftViewTypeName) ##(strName) as ViewFamilyType
##Trans_GDVBTN.Commit() ##Commit transaction - will see if we can do paralell with another transaction per API
return DraftViewType ##Return list
##############
t = Transaction (doc, 'Create Drafting View Type')
t.Start()
DVT=GetDraftingViewTypeByName("Test3") ## GetDraftingView_AllTypes()
#DVT=GetDraftingView_AllTypes()
#DVT[1].Name="Test2" ##Works... but cannot read DVT[1].Name??? BUG in Pyhon PER:.Name
#DVT = [I.Name for I in DVT]
##OUT =DVT[0].Name ##[v.Name for v in DVT] ##Cannot Read?
#OUT=GetDraftingViewTypeByName ("NewType")
##GetDraftingView ()
OUT=DVT
t.Commit()
Hello,
Thank you very much for the post, this helped me a lot.
I created the following C# macros based in your information. I hope they can be useful.
The macros will copy the ViewFamilyTypes from another document to the current document.
The first one will only copy the ViewFamilyTypes and not the associated template. The second will include the associated View templates but these must exist already in the target document (use another macro for that or transfer standards tool in Revit).
First Macro without view templates:
/// <summary>
/// This copies Plan familyviewtypes to the current document from another document.
/// This will only duplicate the name, it won't include the associated template
/// </summary>
public void CopyViewTypes()
{
Document targetDoc = this.ActiveUIDocument.Document;
Document sourceDoc=null;
foreach(Document d in this.Application.Documents)
{
if(d!=targetDoc && !d.IsLinked)
{
sourceDoc=d;
}
}
FilteredElementCollector sourceViewTypeCollector = new FilteredElementCollector(sourceDoc);
List<string> sourcePlanTypes = sourceViewTypeCollector.OfClass(typeof(ViewFamilyType))
.Cast<ViewFamilyType>()
.Where(x=>x.ViewFamily==ViewFamily.FloorPlan)
.Select(x=>x.Name)
.ToList();
List<ViewFamilyType> floorPlanTypes = new List<ViewFamilyType>();
FilteredElementCollector targetViewTypeCollector = new FilteredElementCollector(targetDoc);
ViewFamilyType typeToDuplicate = targetViewTypeCollector.OfClass(typeof(ViewFamilyType)).Cast<ViewFamilyType>().Where(x=>x.ViewFamily== ViewFamily.FloorPlan).FirstOrDefault();
using(Transaction t = new Transaction(targetDoc,"Copy View types"))
{
t.Start();
foreach(string s in sourcePlanTypes)
{
if(s=="Floor Plan") continue;
typeToDuplicate.Duplicate(s);
}
t.Commit();
}
}
The second macro will include the associated view templates:
/// <summary>
/// This copies Plan familyviewtypes to the current document from another document.
/// This will include the associated view template but the template must already exist in the target document.
/// Use another macro to copy the view templates first
/// </summary>
public void CopyViewTypesWithTemplate()
{
Document targetDoc = this.ActiveUIDocument.Document;
Document sourceDoc=null;
foreach(Document d in this.Application.Documents)
{
if(d!=targetDoc && !d.IsLinked)
{
sourceDoc=d;
}
}
FilteredElementCollector sourceViewTypeCollector = new FilteredElementCollector(sourceDoc);
IEnumerable<ViewFamilyType> sourcePlanTypes = sourceViewTypeCollector.OfClass(typeof(ViewFamilyType))
.Cast<ViewFamilyType>()
.Where(x=>x.ViewFamily==ViewFamily.FloorPlan);
List<ViewFamilyType> floorPlanTypes = new List<ViewFamilyType>();
FilteredElementCollector targetViewTypeCollector = new FilteredElementCollector(targetDoc);
ViewFamilyType typeToDuplicate = targetViewTypeCollector.OfClass(typeof(ViewFamilyType))
.Cast<ViewFamilyType>()
.Where(x=>x.ViewFamily== ViewFamily.FloorPlan)
.FirstOrDefault();
using(Transaction t = new Transaction(targetDoc,"Copy View types"))
{
t.Start();
foreach(ViewFamilyType s in sourcePlanTypes)
{
if(s.Name=="Floor Plan") continue;
string templateName = sourceDoc.GetElement(s.DefaultTemplateId).Name;
FilteredElementCollector viewTemplateCollector = new FilteredElementCollector(targetDoc);
ElementId templateId = viewTemplateCollector.OfClass(typeof(ViewPlan))
.Cast<ViewPlan>()
.Where(x=>x.IsTemplate && x.Name==templateName)
.Select(x=>x.Id)
.FirstOrDefault();
ViewFamilyType newViewFamilyType = typeToDuplicate.Duplicate(s.Name) as ViewFamilyType;
newViewFamilyType.DefaultTemplateId=templateId;
}
t.Commit();
}
}
Nice! Great way to pay it forward.
I am getting into API development and this will save some grief converting from PY to C# : )
Can't find what you're looking for? Ask the community or share your knowledge.