James Gardner: Home > Blog > 2007 > Static Fields in FormEncode HTMLFill

Static Fields in FormEncode HTMLFill

Posted:2007-10-01 18:00
Tags:Pylons, Python, Web

It is sometimes rather useful to be able to populate a form with static text which you don't want the user to be able to edit. FormEncode's htmlfill.render() does have an optoin for text_as_default which you can set to true which will render any unknown input fields as text. It does try to render the form field but needs this patch to render the value:

Index: formencode/htmlfill.py
===================================================================
--- formencode/htmlfill.py      (revision 3008)
+++ formencode/htmlfill.py      (working copy)
@@ -436,9 +436,15 @@
             if value is None:
                 value = self.get_attr(attrs, 'value', '')
             self.set_attr(attrs, 'value', value)
-            self.write_tag('input', attrs, startend)
+           self.write_text(self.get_attr(attrs, 'value'))

I like to go further and implement support for a static field (it feels less hacky) just add this to the end of the patch:

             self.skip_next = True
             self.add_key(name)
+        elif t == 'static':
+            self.set_attr(attrs, 'value', value or
+                          self.get_attr(attrs, 'value', ''))
+            self.write_text(self.get_attr(attrs, 'value'))
+            self.skip_next = True
+            self.add_key(name)
         else:
             assert 0, "I don't know about this kind of <input>: %s (pos: %s)" \
                    % (t, self.getpos())

Then you can create fields like this:

<input type="static" name="name" />

and htmlfilll will replace them with the text value associated with the name key.

(view source)

James Gardner: Home > Blog > 2007 > Static Fields in FormEncode HTMLFill