Dec 1, 2020

Get CropBox Id in Revit with Python.

Learn how to get CropBox Id in Revit API.

1️⃣ FilteredElementCollector.Excluding()

The first method is quite straight forward and goes like this:

  1. Hide the CropBox

  2. Use FilteredElementCollector(doc, view_id) to collect all elements you can see in the view.

  3. Unhide the CropBox

  4. Use FilteredElementCollector again, but this time exclude elements you collected the first time with .Excluding(element_ids)

  5. Get ElementId of the CropBox from the collection.

  6. Lastly, RollBack your Transactions so nothing has changed.

def GetViewCropBoxElement(view):
    """Function to get a cropbox_id from the given view."""

    tGroup = TransactionGroup(doc, "Py: Get cropbox_id")
    tGroup.Start()

    trans1 = Transaction(doc, "temp")
    trans1.Start()
    view.CropBoxVisible = False
    trans1.Commit()

    shown_elements_ids= FilteredElementCollector(doc, view.Id).ToElementIds()

    trans1.Start()
    view.CropBoxVisible = True
    trans1.Commit()

    cropbox_id= FilteredElementCollector(doc, view.Id).Excluding(shown_elements_ids).FirstElementId()
    
    tGroup.RollBack()

    return cropbox_id

This method is a bit messy because of multiple transactions. So I have another option.

FilteredElementCollector.WherePasses()

I have found an article by Jeremy Tammik - "Efficiently Retrieve Crop Box for Given View" in C#.

So I've translated it to python for people who don't "speak" C# well enough. I encourage you to read his article to better understand the logic behind this function.

Be aware that FilteredElementCollector will grab CropBox and View so be aware of that.

def get_cropbox_id(view):
    """Function to get cropbox_id of a given view."""
    provider     = ParameterValueProvider(ElementId( int(BuiltInParameter.ID_PARAM)) )
    rule         = FilterElementIdRule(provider, FilterNumericEquals(), view.Id)
    param_filter = ElementParameterFilter(rule)
    collector    = FilteredElementCollector(doc).WherePasses(param_filter).ToElementIds()
    if collector:
        for id in collector:
            if id != view.Id:
                return id

Join Newsletter

📩 You will be added to Revit API Newsletter

Join Us!

which is already read by 7400+ people!

Ready to become Revit Hero for your office? Learn Revit API!

Join this comprehensive course that will guide you step by step on how to create your dream tools for Revit that save time.