Added the possibility to use "option" field type outside a group. This is convenient to create just a single checkbox.

This commit is contained in:
Tomas Bures 2018-12-28 20:54:00 +01:00
parent 64af46b685
commit 2e847460f4
10 changed files with 117 additions and 26 deletions

View file

@ -357,6 +357,9 @@ class CheckBox extends Component {
} }
} }
@withComponentMixins([
withFormStateOwner
])
class CheckBoxGroup extends Component { class CheckBoxGroup extends Component {
static propTypes = { static propTypes = {
id: PropTypes.string.isRequired, id: PropTypes.string.isRequired,

View file

@ -15,6 +15,7 @@ import {
ACEEditor, ACEEditor,
Button, Button,
ButtonRow, ButtonRow,
CheckBox,
Dropdown, Dropdown,
Fieldset, Fieldset,
Form, Form,
@ -95,9 +96,7 @@ export default class CUD extends Component {
data.default_value = ''; data.default_value = '';
} }
if (data.type !== 'option') { data.isInGroup = data.group !== null;
data.group = null;
}
data.enumOptions = ''; data.enumOptions = '';
data.dateFormat = DateFormat.EUR; data.dateFormat = DateFormat.EUR;
@ -121,6 +120,11 @@ export default class CUD extends Component {
case 'birthday': case 'birthday':
data.dateFormat = data.settings.dateFormat; data.dateFormat = data.settings.dateFormat;
break; break;
case 'option':
data.checkedLabel = data.isInGroup ? '' : data.settings.checkedLabel;
data.uncheckedLabel = data.isInGroup ? '' : data.settings.uncheckedLabel;
break;
} }
data.orderListBefore = data.orderListBefore.toString(); data.orderListBefore = data.orderListBefore.toString();
@ -135,9 +139,12 @@ export default class CUD extends Component {
key: '', key: '',
default_value: '', default_value: '',
group: null, group: null,
isInGroup: false,
renderTemplate: '', renderTemplate: '',
enumOptions: '', enumOptions: '',
dateFormat: 'eur', dateFormat: 'eur',
checkedLabel: '',
uncheckedLabel: '',
orderListBefore: 'end', // possible values are <numeric id> / 'end' / 'none' orderListBefore: 'end', // possible values are <numeric id> / 'end' / 'none'
orderSubscribeBefore: 'end', orderSubscribeBefore: 'end',
orderManageBefore: 'end' orderManageBefore: 'end'
@ -168,7 +175,8 @@ export default class CUD extends Component {
const type = state.getIn(['type', 'value']); const type = state.getIn(['type', 'value']);
const group = state.getIn(['group', 'value']); const group = state.getIn(['group', 'value']);
if (type === 'option' && !group) { const isInGroup = state.getIn(['isInGroup', 'value']);
if (isInGroup && !group) {
state.setIn(['group', 'error'], t('groupHasToBeSelected')); state.setIn(['group', 'error'], t('groupHasToBeSelected'));
} else { } else {
state.setIn(['group', 'error'], null); state.setIn(['group', 'error'], null);
@ -261,7 +269,7 @@ export default class CUD extends Component {
data.default_value = null; data.default_value = null;
} }
if (data.type !== 'option') { if (!data.isInGroup) {
data.group = null; data.group = null;
} }
@ -284,13 +292,23 @@ export default class CUD extends Component {
case 'birthday': case 'birthday':
data.settings.dateFormat = data.dateFormat; data.settings.dateFormat = data.dateFormat;
break; break;
case 'option':
if (!data.isInGroup) {
data.settings.checkedLabel = data.checkedLabel;
data.settings.uncheckedLabel = data.uncheckedLabel;
}
break;
} }
delete data.renderTemplate; delete data.renderTemplate;
delete data.enumOptions; delete data.enumOptions;
delete data.dateFormat; delete data.dateFormat;
delete data.checkedLabel;
delete data.uncheckedLabel;
delete data.isInGroup;
if (data.type === 'option') { if (data.group !== null) {
data.orderListBefore = data.orderSubscribeBefore = data.orderManageBefore = 'none'; data.orderListBefore = data.orderSubscribeBefore = data.orderManageBefore = 'none';
} else { } else {
data.orderListBefore = Number.parseInt(data.orderListBefore) || data.orderListBefore; data.orderListBefore = Number.parseInt(data.orderListBefore) || data.orderListBefore;
@ -318,7 +336,7 @@ export default class CUD extends Component {
const getOrderOptions = fld => { const getOrderOptions = fld => {
return [ return [
{key: 'none', label: t('notVisible')}, {key: 'none', label: t('notVisible')},
...this.props.fields.filter(x => (!this.props.entity || x.id !== this.props.entity.id) && x[fld] !== null && x.type !== 'option').sort((x, y) => x[fld] - y[fld]).map(x => ({ key: x.id.toString(), label: `${x.name} (${this.fieldTypes[x.type].label})`})), ...this.props.fields.filter(x => (!this.props.entity || x.id !== this.props.entity.id) && x[fld] !== null && x.group === null).sort((x, y) => x[fld] - y[fld]).map(x => ({ key: x.id.toString(), label: `${x.name} (${this.fieldTypes[x.type].label})`})),
{key: 'end', label: t('endOfList')} {key: 'end', label: t('endOfList')}
]; ];
}; };
@ -327,6 +345,7 @@ export default class CUD extends Component {
const typeOptions = Object.keys(this.fieldTypes).map(key => ({key, label: this.fieldTypes[key].label})); const typeOptions = Object.keys(this.fieldTypes).map(key => ({key, label: this.fieldTypes[key].label}));
const type = this.getFormValue('type'); const type = this.getFormValue('type');
const isInGroup = this.getFormValue('isInGroup');
let fieldSettings = null; let fieldSettings = null;
switch (type) { switch (type) {
@ -436,7 +455,16 @@ export default class CUD extends Component {
fieldSettings = fieldSettings =
<Fieldset label={t('fieldSettings')}> <Fieldset label={t('fieldSettings')}>
<TableSelect id="group" label={t('group')} withHeader dropdown dataUrl={`rest/fields-grouped-table/${this.props.list.id}`} columns={fieldsGroupedColumns} selectionLabelIndex={1} help={t('selectGroupToWhichTheOptionsShouldBelong')}/> <CheckBox id="isInGroup" label={t('group')} text={t('Belongs to checkbox / dropdown / radio group')}/>
{isInGroup &&
<TableSelect id="group" label={t('Containing group')} withHeader dropdown dataUrl={`rest/fields-grouped-table/${this.props.list.id}`} columns={fieldsGroupedColumns} selectionLabelIndex={1} help={t('selectGroupToWhichTheOptionsShouldBelong')}/>
}
{!isInGroup &&
<>
<InputField id="checkedLabel" label={t('Checked label')} help={t('Label that will be displayed in list and subscription when the option is checked')}/>
<InputField id="uncheckedLabel" label={t('Unchecked label')} help={t('Label that will be displayed in list and subscription when the option is unchecked')}/>
</>
}
<InputField id="default_value" label={t('defaultValue')} help={t('defaultValueUsedWhenTheFieldIsEmpty')}/> <InputField id="default_value" label={t('defaultValue')} help={t('defaultValueUsedWhenTheFieldIsEmpty')}/>
</Fieldset>; </Fieldset>;
break; break;

View file

@ -51,7 +51,7 @@ export default class List extends Component {
const columns = [ const columns = [
{ data: 4, title: "#" }, { data: 4, title: "#" },
{ data: 1, title: t('name'), { data: 1, title: t('name'),
render: (data, cmd, rowData) => rowData[2] === 'option' ? <span><Icon icon="dot-circle"/> {data}</span> : data render: (data, cmd, rowData) => rowData[5] !== null ? <span><Icon icon="dot-circle"/> {data}</span> : data
}, },
{ data: 2, title: t('type'), render: data => this.fieldTypes[data].label, sortable: false, searchable: false }, { data: 2, title: t('type'), render: data => this.fieldTypes[data].label, sortable: false, searchable: false },
{ data: 3, title: t('mergeTag') }, { data: 3, title: t('mergeTag') },

View file

@ -2,7 +2,16 @@
import React from "react"; import React from "react";
import {SubscriptionStatus} from "../../../../shared/lists"; import {SubscriptionStatus} from "../../../../shared/lists";
import {ACEEditor, CheckBoxGroup, DatePicker, Dropdown, InputField, RadioGroup, TextArea} from "../../lib/form"; import {
ACEEditor,
CheckBox,
CheckBoxGroup,
DatePicker,
Dropdown,
InputField,
RadioGroup,
TextArea
} from "../../lib/form";
import {formatBirthday, formatDate, parseBirthday, parseDate} from "../../../../shared/date"; import {formatBirthday, formatDate, parseBirthday, parseDate} from "../../../../shared/date";
import {getFieldColumn} from '../../../../shared/lists'; import {getFieldColumn} from '../../../../shared/lists';
import 'brace/mode/json'; import 'brace/mode/json';
@ -124,6 +133,20 @@ export function getFieldTypes(t) {
indexable: false indexable: false
}; };
const optionFieldType = {
form: groupedField => <CheckBox key={getFieldColumn(groupedField)} id={getFieldColumn(groupedField)} text={groupedField.settings.checkedLabel} label={groupedField.name}/>,
assignFormData: (groupedField, data) => {
const value = data[getFieldColumn(groupedField)];
data[getFieldColumn(groupedField)] = !!value;
},
initFormData: (groupedField, data) => {
data[getFieldColumn(groupedField)] = false;
},
assignEntity: (groupedField, data) => {},
validate: (groupedField, state) => {},
indexable: true
};
const enumSingleFieldType = componentType => ({ const enumSingleFieldType = componentType => ({
form: groupedField => React.createElement(componentType, { key: getFieldColumn(groupedField), id: getFieldColumn(groupedField), label: groupedField.name, options: groupedField.settings.options }, null), form: groupedField => React.createElement(componentType, { key: getFieldColumn(groupedField), id: getFieldColumn(groupedField), label: groupedField.name, options: groupedField.settings.options }, null),
assignFormData: (groupedField, data) => { assignFormData: (groupedField, data) => {
@ -146,8 +169,7 @@ export function getFieldTypes(t) {
data[getFieldColumn(groupedField)] = ''; data[getFieldColumn(groupedField)] = '';
} }
}, },
assignEntity: (groupedField, data) => { assignEntity: (groupedField, data) => {},
},
validate: (groupedField, state) => {}, validate: (groupedField, state) => {},
indexable: false indexable: false
}); });
@ -176,6 +198,7 @@ export function getFieldTypes(t) {
groupedFieldTypes.date = dateFieldType; groupedFieldTypes.date = dateFieldType;
groupedFieldTypes.birthday = birthdayFieldType; groupedFieldTypes.birthday = birthdayFieldType;
groupedFieldTypes.json = jsonFieldType; groupedFieldTypes.json = jsonFieldType;
groupedFieldTypes.option = optionFieldType;
groupedFieldTypes['dropdown-enum'] = enumSingleFieldType(Dropdown); groupedFieldTypes['dropdown-enum'] = enumSingleFieldType(Dropdown);
groupedFieldTypes['radio-enum'] = enumSingleFieldType(RadioGroup); groupedFieldTypes['radio-enum'] = enumSingleFieldType(RadioGroup);

View file

@ -17,7 +17,7 @@ async function ajaxListTx(tx, params, queryFun, columns, options) {
columnsNames.push(col.name); columnsNames.push(col.name);
if (col.raw) { if (col.raw) {
columnsSelect.push(tx.raw(col.raw)); columnsSelect.push(tx.raw(col.raw, col.data || []));
} else if (col.query) { } else if (col.query) {
columnsSelect.push(function () { return col.query(this); }); columnsSelect.push(function () { return col.query(this); });
} }

View file

@ -215,7 +215,19 @@ fieldTypes.option = {
grouped: false, grouped: false,
enumerated: false, enumerated: false,
cardinality: Cardinality.SINGLE, cardinality: Cardinality.SINGLE,
parsePostValue: (field, value) => !(['false', 'no', '0', ''].indexOf((value || '').toString().trim().toLowerCase()) >= 0) parsePostValue: (field, value) => {
if (Array.isArray(value)) {
// HTML checkbox does not provide any value when not checked. To detect the presence of the checkbox, we add a hidden field with the same name (see subscription-custom-fields.hbs:130).
// When the checkbox is selected, two values are returned and "value" is an array instead of a string. We assume the hidden field always comes after the actual value and thus take
// the first value in the array
value = value[0]
}
return !(['false', 'no', '0', ''].indexOf((value || '').toString().trim().toLowerCase()) >= 0)
},
getHbsType: field => 'typeOption',
forHbs: (field, value) => value ? 1 : 0,
render: (field, value) => value ? field.settings.checkedLabel : field.settings.uncheckedLabel
}; };
fieldTypes['date'] = { fieldTypes['date'] = {
@ -358,15 +370,15 @@ async function listDTAjax(context, listId, params) {
// All this is to show options always below their group parent // All this is to show options always below their group parent
.innerJoin('custom_fields AS parent_fields', function() { .innerJoin('custom_fields AS parent_fields', function() {
this.on(function() { this.on(function() {
this.on('custom_fields.type', '=', knex.raw('?', ['option'])) this.onNotNull('custom_fields.group')
.on('custom_fields.group', '=', 'parent_fields.id'); .on('custom_fields.group', '=', 'parent_fields.id');
}).orOn(function() { }).orOn(function() {
this.on('custom_fields.type', '<>', knex.raw('?', ['option'])) this.orOnNull('custom_fields.group')
.on('custom_fields.id', '=', 'parent_fields.id'); .on('custom_fields.id', '=', 'parent_fields.id');
}); });
}) })
.where('custom_fields.list', listId), .where('custom_fields.list', listId),
[ 'custom_fields.id', 'custom_fields.name', 'custom_fields.type', 'custom_fields.key', 'custom_fields.order_list' ], [ 'custom_fields.id', 'custom_fields.name', 'custom_fields.type', 'custom_fields.key', 'custom_fields.order_list', 'custom_fields.group' ],
{ {
orderByBuilder: (builder, orderColumn, orderDir) => { orderByBuilder: (builder, orderColumn, orderDir) => {
// We use here parent_fields to keep options always below their parent group // We use here parent_fields to keep options always below their parent group
@ -374,13 +386,13 @@ async function listDTAjax(context, listId, params) {
builder builder
.orderBy(knex.raw('-parent_fields.order_list'), orderDir === 'asc' ? 'desc' : 'asc') // This is MySQL speciality. It sorts the rows in ascending order with NULL values coming last .orderBy(knex.raw('-parent_fields.order_list'), orderDir === 'asc' ? 'desc' : 'asc') // This is MySQL speciality. It sorts the rows in ascending order with NULL values coming last
.orderBy('parent_fields.name', orderDir) .orderBy('parent_fields.name', orderDir)
.orderBy(knex.raw('custom_fields.type = "option"'), 'asc') .orderBy(knex.raw('custom_fields.group is not null'), 'asc')
} else { } else {
const parentColumn = orderColumn.replace(/^custom_fields/, 'parent_fields'); const parentColumn = orderColumn.replace(/^custom_fields/, 'parent_fields');
builder builder
.orderBy(parentColumn, orderDir) .orderBy(parentColumn, orderDir)
.orderBy('parent_fields.name', orderDir) .orderBy('parent_fields.name', orderDir)
.orderBy(knex.raw('custom_fields.type = "option"'), 'asc'); .orderBy(knex.raw('custom_fields.group is not null'), 'asc');
} }
} }
} }
@ -444,8 +456,7 @@ async function serverValidate(context, listId, data) {
async function _validateAndPreprocess(tx, listId, entity, isCreate) { async function _validateAndPreprocess(tx, listId, entity, isCreate) {
enforce(entity.type === 'option' || !entity.group, 'Only option may have a group assigned'); enforce(entity.type === 'option' || !entity.group, 'Only option may have a group assigned');
enforce(entity.type !== 'option' || entity.group, 'Option must have a group assigned.'); enforce(!entity.group || (entity.orderListBefore === 'none' && entity.orderSubscribeBefore === 'none' && entity.orderManageBefore === 'none'), 'Field with a group assigned cannot be made visible');
enforce(entity.type !== 'option' || (entity.orderListBefore === 'none' && entity.orderSubscribeBefore === 'none' && entity.orderManageBefore === 'none'), 'Option cannot be made visible');
enforce(!entity.group || await tx('custom_fields').where({list: listId, id: entity.group}).first(), 'Group field does not exist'); enforce(!entity.group || await tx('custom_fields').where({list: listId, id: entity.group}).first(), 'Group field does not exist');
enforce(entity.name, 'Name must be present'); enforce(entity.name, 'Name must be present');
@ -638,6 +649,7 @@ function forHbsWithFieldsGrouped(fieldsGrouped, subscription) { // assumes group
const entry = { const entry = {
name: fld.name, name: fld.name,
key: fld.key, key: fld.key,
field: fld,
[type.getHbsType(fld)]: true, [type.getHbsType(fld)]: true,
order_subscribe: fld.order_subscribe, order_subscribe: fld.order_subscribe,
order_manage: fld.order_manage, order_manage: fld.order_manage,
@ -726,6 +738,7 @@ function _fromText(listId, data, flds, isGrouped, keyName, singleCardUsesKeyName
if (isGrouped) { if (isGrouped) {
for (const fld of flds) { for (const fld of flds) {
const fldKey = fld[keyName]; const fldKey = fld[keyName];
if (fldKey && fldKey in data) { if (fldKey && fldKey in data) {
const type = fieldTypes[fld.type]; const type = fieldTypes[fld.type];
const fldCol = getFieldColumn(fld); const fldCol = getFieldColumn(fld);

View file

@ -76,6 +76,11 @@ fieldTypes.birthday = {
listRender: (groupedField, value) => formatBirthday(groupedField.settings.dateFormat, value) listRender: (groupedField, value) => formatBirthday(groupedField.settings.dateFormat, value)
}; };
fieldTypes.option = {
afterJSON: (groupedField, entity) => {},
listRender: (groupedField, value) => value ? groupedField.settings.checkedLabel : groupedField.settings.uncheckedLabel
};
function getSubscriptionTableName(listId) { function getSubscriptionTableName(listId) {
@ -97,7 +102,6 @@ function groupSubscription(groupedFieldsMap, entity) {
const fieldType = fields.getFieldType(fld.type); const fieldType = fields.getFieldType(fld.type);
if (fieldType.grouped) { if (fieldType.grouped) {
let value = null; let value = null;
if (fieldType.cardinality === fields.Cardinality.SINGLE) { if (fieldType.cardinality === fields.Cardinality.SINGLE) {
@ -273,7 +277,8 @@ async function listDTAjax(context, listId, segmentId, params) {
} else { } else {
columns.push({ columns.push({
name: listTable + '.' + fldCol, name: listTable + '.' + fldCol,
raw: 0 raw: '?',
data: [0]
}) })
} }

View file

@ -323,7 +323,7 @@ async function migrateCustomForms(knex) {
async function migrateCustomFields(knex) { async function migrateCustomFields(knex) {
// ----------------------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------------------
// Move form field order to custom fileds and make all fields configurable // Move form field order to custom fields and make all fields configurable
// ----------------------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------------------
await knex.schema.table('custom_fields', table => { await knex.schema.table('custom_fields', table => {
table.integer('order_subscribe'); table.integer('order_subscribe');

View file

@ -49,6 +49,16 @@
</div> </div>
{{/if}} {{/if}}
{{#if typeOption}}
<div class="form-group checkbox">
<label>{{name}}</label>
<label class="label-checkbox">
<input type="checkbox" name="{{key}}" value="1" {{#if value}} checked {{/if}}> {{field.settings.checkedLabel}}
</label>
<input type="hidden" value="0" name="{{key}}">
</div>
{{/if}}
{{#if typeGpg}} {{#if typeGpg}}
<div class="form-group gpg {{key}}"> <div class="form-group gpg {{key}}">
<label for="{{key}}">{{name}}</label> <label for="{{key}}">{{name}}</label>
@ -117,6 +127,7 @@
{{#if typeCheckboxGrouped}} {{#if typeCheckboxGrouped}}
<div class="form-group checkbox"> <div class="form-group checkbox">
<input type="hidden" value="<present>" name="{{key}}">
<label>{{name}}</label> <label>{{name}}</label>
{{#each options}} {{#each options}}
<label class="label-checkbox"> <label class="label-checkbox">

View file

@ -40,11 +40,19 @@ function parseBirthday(format, text) {
} }
function formatDate(format, date) { function formatDate(format, date) {
return moment.utc(date).format(dateFormatStrings[format]); if (date === null) {
return '';
} else {
return moment.utc(date).format(dateFormatStrings[format]);
}
} }
function formatBirthday(format, date) { function formatBirthday(format, date) {
return moment.utc(date).format(birthdayFormatStrings[format]); if (date === null) {
return '';
} else {
return moment.utc(date).format(birthdayFormatStrings[format]);
}
} }
function getDateFormatString(format) { function getDateFormatString(format) {