From 69eb6b11d0ee288b41d6b905e890b5995273e092 Mon Sep 17 00:00:00 2001 From: jeremystretch Date: Tue, 18 Jan 2022 16:01:40 -0500 Subject: [PATCH] Closes #8368: Enable controlling the order of custom script form fields with field_order --- docs/customization/custom-scripts.md | 4 ++++ docs/release-notes/version-3.1.md | 1 + netbox/extras/scripts.py | 13 +++++++++++-- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/docs/customization/custom-scripts.md b/docs/customization/custom-scripts.md index df436fe99..02af19726 100644 --- a/docs/customization/custom-scripts.md +++ b/docs/customization/custom-scripts.md @@ -77,6 +77,10 @@ This is the human-friendly names of your script. If omitted, the class name will A human-friendly description of what your script does. +### `field_order` + +By default, script variables will be ordered in the form as they are defined in the script. `field_order` may be defined as an iterable of field names to determine the order in which variables are rendered. Any fields not included in this iterable be listed last. + ### `commit_default` The checkbox to commit database changes when executing a script is checked by default. Set `commit_default` to False under the script's Meta class to leave this option unchecked by default. diff --git a/docs/release-notes/version-3.1.md b/docs/release-notes/version-3.1.md index 9cfdcad23..ee49a9b64 100644 --- a/docs/release-notes/version-3.1.md +++ b/docs/release-notes/version-3.1.md @@ -6,6 +6,7 @@ * [#8275](https://github.com/netbox-community/netbox/issues/8275) - Introduce alternative ASDOT-formatted column for ASNs * [#8367](https://github.com/netbox-community/netbox/issues/8367) - Add ASNs to global search function +* [#8368](https://github.com/netbox-community/netbox/issues/8368) - Enable controlling the order of custom script form fields with `field_order` * [#8381](https://github.com/netbox-community/netbox/issues/8381) - Add contacts to global search function ### Bug Fixes diff --git a/netbox/extras/scripts.py b/netbox/extras/scripts.py index 3c7ad3c15..fb3c6558a 100644 --- a/netbox/extras/scripts.py +++ b/netbox/extras/scripts.py @@ -296,12 +296,21 @@ class BaseScript: @classmethod def _get_vars(cls): - vars = OrderedDict() + vars = {} for name, attr in cls.__dict__.items(): if name not in vars and issubclass(attr.__class__, ScriptVariable): vars[name] = attr - return vars + # Order variables according to field_order + field_order = getattr(cls.Meta, 'field_order', None) + if not field_order: + return vars + ordered_vars = { + field: vars.pop(field) for field in field_order if field in vars + } + ordered_vars.update(vars) + + return ordered_vars def run(self, data, commit): raise NotImplementedError("The script must define a run() method.")