misc: let item fields be prefilled by text value (#12384) #1040

Merged
fpeters merged 1 commits from wip/12384-prefill-item-by-text into main 2024-01-26 08:47:52 +01:00
2 changed files with 66 additions and 0 deletions

View File

@ -10,6 +10,7 @@ from webtest import Upload
from wcs import fields
from wcs.admin.settings import UserFieldsFormDef
from wcs.blocks import BlockDef
from wcs.carddef import CardDef
from wcs.categories import Category
from wcs.data_sources import NamedDataSource
from wcs.wf.create_formdata import Mapping
@ -401,6 +402,62 @@ def test_form_page_template_list_prefill(pub):
assert 'invalid value selected' not in resp.text
def test_form_page_template_list_prefill_by_text(pub):
NamedDataSource.wipe()
data_source = NamedDataSource(name='foobar')
data_source.data_source = {
'type': 'jsonvalue',
'value': '[{"id": 1, "text": "foo"}, {"id": 2, "text": "bar"}]',
}
data_source.store()
formdef = create_formdef()
formdef.data_class().wipe()
formdef.fields = [
fields.ItemField(
id='1',
label='item',
varname='item',
required=True,
data_source={'type': data_source.slug},
prefill={'type': 'string', 'value': 'bar'},
)
]
formdef.store()
resp = get_app(pub).get('/test/')
assert resp.form['f1'].value == '2'
assert 'invalid value selected' not in resp.text
# check with card data source
CardDef.wipe()
carddef = CardDef()
carddef.name = 'Test'
carddef.fields = [
fields.StringField(id='0', label='blah', varname='blah'),
]
carddef.digest_templates = {'default': '{{ form_var_blah }}'}
carddef.store()
carddef.data_class().wipe()
carddata1 = carddef.data_class()()
carddata1.data = {'0': 'foo'}
carddata1.just_created()
carddata1.store()
carddata2 = carddef.data_class()()
carddata2.data = {'0': 'bar'}
carddata2.just_created()
carddata2.store()
formdef.data_source = {'type': 'carddef:test'}
formdef.store()
resp = get_app(pub).get('/test/')
assert resp.form['f1'].value == str(carddata2.id)
assert 'invalid value selected' not in resp.text
def test_form_page_query_string_list_prefill(pub):
create_user(pub)
formdef = create_formdef()

View File

@ -319,6 +319,15 @@ class ItemField(WidgetField, MapOptionsMixin, ItemFieldMixin, ItemWithImageField
return data_sources.get_id_by_option_text(self.data_source, text_value)
return text_value
def get_prefill_value(self, user=None, force_string=True):
value, explicit_lock = super().get_prefill_value(user=user, force_string=False)
if value and self.data_source:
data_source = data_sources.get_object(self.data_source)
struct_value = data_source.get_structured_value(value)
if struct_value:
value = str(struct_value.get('id'))
return (value, explicit_lock)
def get_display_mode(self, data_source=None):
if not data_source:
data_source = data_sources.get_object(self.data_source)