Virtual field for setting static list of departments based on item selected in requisition

Department list needs to be populated based on the allowed list of departments shared by client. For this virtual field is created and static list set on it. On saving value is set into the department field.

function fieldChanged(scriptContext) {
        try {
            let rec = scriptContext.currentRecord;
            if (scriptContext.sublistId === 'item' && scriptContext.fieldId === 'item') {
                let itemId = rec.getCurrentSublistValue({
                    sublistId: 'item',
                    fieldId: 'item'
                });
                if (!itemId) {
                    return;
                }
                let items = search.lookupFields({
                    type: search.Type.ITEM,
                    id: itemId,
                    columns: ['type']
                });
                let itemType = items.type && items.type[0] && items.type[0].value;
                if (itemType === "NonInvtPart" && isInternal(itemId)) {
                    console.log('Selected itemsss:', itemId);
                    listedNonInvItems(rec, itemId);
                }
            }
        } catch (e) {
            console.error('Error @ fieldChanged:', e);
        }
    }

function listedNonInvItems(rec, itemId) {
        try {
            let customItemField = rec.getSublistField({
                sublistId: 'item',
                fieldId: 'custpage_virtual_department',
                line: 0
            });
            let optionCount = customItemField.getSelectOptions().length;
            for (let i = optionCount - 1; i >= 0; i--) {
                customItemField.removeSelectOption({
                    value: customItemField.getSelectOptions()[i].value
                });
            }
            customItemField.insertSelectOption({ value: '', text: '' });
            let allowedDeptIds = itemDeptMap[itemId];
            console.log('Dept Details:', allowedDeptIds);
            let deptNamesMap = {};
            let deptSearch = search.create({
                type: search.Type.DEPARTMENT,
                filters: [['internalid', 'anyof', allowedDeptIds]],
                columns: ['internalid', 'name']
            });
            deptSearch.run().each(result => {
                let id = result.getValue({ name: 'internalid' });
                let name = result.getValue({ name: 'name' });
                deptNamesMap[id] = name;
                return true;
            });
            allowedDeptIds.forEach(deptId => {
                customItemField.insertSelectOption({
                    value: deptId.toString(),
                    text: deptNamesMap[deptId]
                });
            });
        } catch (e) {
            console.error('Error @ listedNonInvItems:', e);
        }
    }

Leave a comment

Your email address will not be published. Required fields are marked *