add helpers to insert new fields in forms
authorFlorent <florent@secondweb.fr>
Mon, 25 May 2009 22:21:13 +0200
changeset 1935 a54a3b665361
parent 1934 be86bb31c4c2
child 1936 c5af2fbda5b6
add helpers to insert new fields in forms
web/form.py
--- a/web/form.py	Mon May 25 22:14:58 2009 +0200
+++ b/web/form.py	Mon May 25 22:21:13 2009 +0200
@@ -261,13 +261,17 @@
             self.restore_previous_post(self.session_key())
 
     @iclassmethod
-    def field_by_name(cls_or_self, name, role='subject'):
-        """return field with the given name and role"""
+    def _fieldsattr(cls_or_self):
         if isinstance(cls_or_self, type):
             fields = cls_or_self._fields_
         else:
             fields = cls_or_self.fields
-        for field in fields:
+        return fields
+
+    @iclassmethod
+    def field_by_name(cls_or_self, name, role='subject'):
+        """return field with the given name and role"""
+        for field in cls_or_self._fieldsattr():
             if field.name == name and field.role == role:
                 return field
         raise FieldNotFound(name)
@@ -275,20 +279,24 @@
     @iclassmethod
     def remove_field(cls_or_self, field):
         """remove a field from form class or instance"""
-        if isinstance(cls_or_self, type):
-            fields = cls_or_self._fields_
-        else:
-            fields = cls_or_self.fields
-        fields.remove(field)
+        cls_or_self._fieldsattr().remove(field)
 
     @iclassmethod
     def append_field(cls_or_self, field):
         """append a field to form class or instance"""
-        if isinstance(cls_or_self, type):
-            fields = cls_or_self._fields_
-        else:
-            fields = cls_or_self.fields
-        fields.append(field)
+        cls_or_self._fieldsattr().append(field)
+
+    @iclassmethod
+    def insert_field_before(cls_or_self, new_field, name, role='subject'):
+        field = cls_or_self.field_by_name(name, role)
+        fields = cls_or_self._fieldsattr()
+        fields.insert(fields.index(field), new_field)
+
+    @iclassmethod
+    def insert_field_after(cls_or_self, new_field, name, role='subject'):
+        field = cls_or_self.field_by_name(name, role)
+        fields = cls_or_self._fieldsattr()
+        fields.insert(fields.index(field)+1, new_field)
 
     @property
     def form_needs_multipart(self):