Skip to content
This repository has been archived by the owner on Sep 5, 2019. It is now read-only.

Commit

Permalink
Adds a helper function to configure the render options of any given W…
Browse files Browse the repository at this point in the history
…TForms widget
  • Loading branch information
Denis Krienbühl committed Apr 24, 2015
1 parent e970018 commit 95ecb92
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 3 deletions.
4 changes: 2 additions & 2 deletions onegov/form/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
from onegov.form.core import Form
from onegov.form.core import Form, with_options

__all__ = ['Form']
__all__ = ['Form', 'with_options']
20 changes: 20 additions & 0 deletions onegov/form/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,23 @@ class Form(BaseForm):
def submitted(self, request):
""" Returns true if the given request is a successful post request. """
return request.POST and self.validate()


def with_options(widget_class, **render_options):
""" Takes a widget class and returns a child-instance of the widget class,
with the given options set on the render call.
This makes it easy to use existing WTForms widgets with custom render
options:
field = StringField(widget=with_options(TextArea, class_="markdown"))
"""

class Widget(widget_class):

def __call__(self, *args, **kwargs):
render_options.update(kwargs)
return super(Widget, self).__call__(*args, **render_options)

return Widget()
21 changes: 20 additions & 1 deletion onegov/form/tests/test_core.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from onegov.form import Form
from onegov.form import Form, with_options
from wtforms import StringField, validators
from wtforms.widgets import TextArea


class DummyPostData(dict):
Expand All @@ -15,6 +16,16 @@ def __init__(self, POST):
self.POST = DummyPostData(POST)


class DummyField(object):
def __init__(self, id, name, value):
self.id = id
self.name = name
self.value = value

def _value(self):
return self.value


def test_submitted():

class TestForm(Form):
Expand All @@ -25,3 +36,11 @@ class TestForm(Form):

request = DummyRequest({'test': 'Test'})
assert TestForm(request.POST).submitted(request)


def test_with_options():
widget = with_options(TextArea, class_="markdown")
assert 'class="markdown"' in widget(DummyField('one', 'one', '1'))

widget = with_options(TextArea, class_="x")
assert 'class="x"' in widget(DummyField('one', 'one', '1'))

0 comments on commit 95ecb92

Please sign in to comment.