Refactor some of the logic into form

It’s messy having a lot of logic in the view methods. Handling the form
stuff can be better encapsulated inside the `Form` subclass itself.
This commit is contained in:
Chris Hill-Scott
2018-08-31 17:31:26 +01:00
parent 80801d827a
commit d80b735b2b
3 changed files with 50 additions and 23 deletions

View File

@@ -682,15 +682,37 @@ class ServiceSwitchLettersForm(StripWhitespaceForm):
)
class BrandingStyle(RadioField):
def post_validate(self, form, validation_stopped):
if self.data == 'None':
self.data = None
class ServiceSetBranding(StripWhitespaceForm):
branding_style = RadioField(
branding_style = BrandingStyle(
'Branding style',
validators=[
DataRequired()
]
)
DEFAULT = ('None', 'GOV.UK')
def __init__(self, all_email_brandings, current_email_branding):
super().__init__(branding_style=current_email_branding)
self.branding_style.choices = sorted(
all_email_brandings + [self.DEFAULT],
key=lambda branding: (
branding[0] != current_email_branding,
branding[0] is not self.DEFAULT[0],
branding[1].lower(),
),
)
class ServicePreviewBranding(StripWhitespaceForm):

View File

@@ -887,24 +887,17 @@ def set_free_sms_allowance(service_id):
def service_set_email_branding(service_id):
email_branding = email_branding_client.get_all_email_branding()
form = ServiceSetBranding()
# dynamically create org choices, including the null option
form.branding_style.choices = sorted(
get_branding_as_value_and_label(email_branding) + [('None', 'GOV.UK')],
key=lambda branding: (
branding[0] != current_service.email_branding,
branding[0] is not 'None',
branding[1].lower(),
),
form = ServiceSetBranding(
all_email_brandings=get_branding_as_value_and_label(email_branding),
current_email_branding=current_service.email_branding,
)
if form.validate_on_submit():
branding_style = None if form.branding_style.data == 'None' else form.branding_style.data
return redirect(url_for('.service_preview_email_branding', service_id=service_id,
branding_style=branding_style))
form.branding_style.data = current_service['email_branding'] or 'None'
return redirect(url_for(
'.service_preview_email_branding',
service_id=service_id,
branding_style=form.branding_style.data,
))
return render_template(
'views/service-settings/set-email-branding.html',