wagtailstreamforms
wagtailstreamforms copied to clipboard
Adding additional options to existing fields
I am trying to add an additional field option that takes in an integer from 1 to 12 to set the Bootstrap column width for the form field. At the moment, I'm only overriding the singleline
field, but once it works, I'll be overriding all available (built-in) fields with this integer input.
My wagtailstreamforms_fields.py contains the following:
from django import forms
from wagtailstreamforms.fields import BaseField, register
from wagtail.core import blocks
class CustomCharField(forms.CharField):
def __init__(self,*args, **kwargs):
self.col_width = kwargs.pop('col_width')
print(self.col_width)
super().__init__(*args,**kwargs)
@register('singleline')
class Column_SingleLineTextField(BaseField):
field_class = CustomCharField
def get_options(self, block_value):
return {
'label': block_value.get('label'),
'help_text': block_value.get('help_text'),
'required': block_value.get('required'),
'initial': block_value.get('default_value'),
'col_width': block_value.get('width')
}
def get_form_block(self):
return blocks.StructBlock([
('label', blocks.CharBlock()),
('help_text', blocks.CharBlock(required=False)),
('required', blocks.BooleanBlock(required=False)),
('default_value', blocks.CharBlock(required=False)),
('width', blocks.IntegerBlock(help_text="Width of field, 1 to 12, 12 is full width.", max_value=12, min_value=1, default=12, required=True)),
], icon=self.icon, label=self.label)
With that code, the singleline
field has a new integer input box on the settings page.
I am struggling to access the col_width
option in the HTML templates.
The template, templates/partials/custom_form_field.html
consists of:
<div class="col-{{ field.col_width }}">
{{ field.label_tag }}
{{ field }}
{{ field.col_width }}
{% if field.help_text %}<p class="help-text">{{ field.help_text }}</p>{% endif %}
{{ field.errors }}
</div>
{{ field.col_width }}
returns nothing. Why's this, what am I doing wrong and how do I fix this?
Bumping this. Having the ability to extend the form to include css classes, placeholder text, etc (if desired) seems like it would add loads of utility to this awesome package.
Hey @jamesdossis, I actually managed to add additional options to each form field. This is a very hacky solution that consists of setting the attrs
of each form class and using jQuery in the templates to fetch the HTML attributes that have been set from the attrs
and carrying out your desired functionalities. You can check it out here: https://stackoverflow.com/a/68938370/11742478
But yeah you're right, a better extension functionality would really improve this package substantially, and would remove the need to rely on external dependencies such as jQuery/Javascript.