Как мне установить context.currentRecord в пакете? - PullRequest
0 голосов
/ 17 ноября 2018

Я создаю простой Suitelet, где на первой странице пользователь вводит заказ # и нажимает кнопку Поиск.Это перенаправляет на страницу, которая загружает информацию о позициях в подсписок.Оттуда пользователь может редактировать несколько полей позиции, прежде чем сохранять эти изменения.Все работает вплоть до сохранения изменений ...

Мой скрипт Suitelet выглядит так:

/**
* @NApiVersion 2.x
* @NScriptType Suitelet
*/
define(['N/search', 'N/ui/serverWidget', 'N/format', 'N/redirect', 'N/https', 'N/record', 'N/error'],
function(s, ui, format, redirect, https, record, error) {

    function onRequest_(context) {  
        try {
            if (context.request.method === 'GET') {
                showForm(context);
            } else {
                showResults(context);
            }
        } catch (e) {
            log.error('onRequest_', 'ERROR : ' + e.message);

            var errObj = error.create({
                name : 'SL ERROR',
                message : e.message,
                notifyOff : true
            });
            throw 'ERROR: ' + e.message;
        }
    }

    function showForm(context) {

        var form = ui.createForm({
            title : 'Update PO'
        });

        var req = context.request;

        var poSearch = form.addField({
            id : 'po_search',
            type : ui.FieldType.TEXT,
            label : 'PO# SEARCH'
        });
        poSearch.isMandatory = true;

        form.addSubmitButton({
            label : 'Search'
        });

        context.response.writePage(form);
    }

    function showResults(context) {

        var form = ui.createForm({
            title : 'Updating PO#' + context.request.parameters['po_search']
        });

        var req = context.request;
        form.clientScriptFileId = 5310184;


        var poSearch = form.addField({
            id : 'po_search',
            type : ui.FieldType.TEXT,
            label : 'PO# Search'
        });
        poSearch.isMandatory = true;
        poSearch.defaultValue = context.request.parameters['po_search'];

        form.addSubmitButton({
            label : 'Search'
        });

        // Button to update the Purchase Order
        form.addButton({
            id : 'custpage_updaterecord',
            label : 'Update Record',
            functionName: 'updateRecord'
        });

        // Create the item sublist
        var itemSublist = form.addSublist({
            id : 'custpage_item',
            type : ui.SublistType.LIST,
            label : 'Item(s)'
        });

        // Item
        var itemCol = itemSublist.addField({
            id : 'custpage_item_item',
            label : 'Item',
            type : ui.FieldType.SELECT,
            source : 'item'
        }).updateDisplayType({
            displayType : ui.FieldDisplayType.INLINE
        });

        // Description
        var descCol = itemSublist.addField({
            id : 'custpage_item_desc',
            label : 'Description',
            type : ui.FieldType.TEXT
        });

        // Purchase Price
        var priceCol = itemSublist.addField({
            id : 'custpage_item_price',
            label : 'Purchase Price',
            type : ui.FieldType.CURRENCY
        }).updateDisplayType({
            displayType : ui.FieldDisplayType.ENTRY
        });

        // Expected Date
        var dateCol = itemSublist.addField({
            id : 'custpage_item_date',
            label : 'Expected Date',
            type : ui.FieldType.DATE
        }).updateDisplayType({
            displayType : ui.FieldDisplayType.ENTRY
        });

        // Vendor SO#
        var vendorsoCol = itemSublist.addField({
            id : 'custpage_item_vendorso',
            label : 'Vendor SO#',
            type : ui.FieldType.TEXT
        }).updateDisplayType({
            displayType : ui.FieldDisplayType.ENTRY
        });

        // Run a search on the PO#, to find the internal Id
        s.create({
            type: s.Type.PURCHASE_ORDER,
            columns: [
                'internalid'
            ],
            filters: [
                s.createFilter({
                    name: "tranid",
                    operator: s.Operator.IS,
                    values: "PO" + context.request.parameters['po_search']
                }),
                s.createFilter({
                    name: "mainline",
                    operator: s.Operator.IS,
                    values: true
                })
            ]
        }).run().each(function(result) {
            // There should be no more than 1 result
            if (result.id) {
                // Load the PO
                var rec = record.load({
                    type: record.Type.PURCHASE_ORDER,
                    id: result.id
                });

                // Loop through the items sublist to create our list
                var lineCount = rec.getLineCount({
                    sublistId: 'item'
                });


                for (i = 0; i < lineCount; i++) {
                    // Get then set the Item
                    var item = rec.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'item',
                        line: i
                    });

                    itemSublist.setSublistValue({
                        id: 'custpage_item_item',
                        line: i,
                        value: item
                    });

                    // Get then set the Description
                    var desc = rec.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'description',
                        line: i
                    });

                    if (desc) {
                        itemSublist.setSublistValue({
                            id: 'custpage_item_desc',
                            line: i,
                            value: desc
                        });
                    }

                    // Get then set the Purchase Price
                    var price = rec.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'amount',
                        line: i
                    });

                    if (price) {
                        itemSublist.setSublistValue({
                            id: 'custpage_item_price',
                            line: i,
                            value: price
                        });
                    }

                    // Get then set the Expected Date
                    var date = rec.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcol_mts_expected_date',
                        line: i
                    });

                    if (date) {
                        var formattedDate = format.format({
                            value: date,
                            type: format.Type.DATE
                        });

                        itemSublist.setSublistValue({
                            id: 'custpage_item_date',
                            line: i,
                            value: formattedDate
                        });
                    }

                    // Get then set the Vendor Sales Order #
                    var vendorso = rec.getSublistValue({
                        sublistId: 'item',
                        fieldId: 'custcolcustcol_mts_vendsonumb',
                        line: i
                    });

                    if (vendorso) {
                        itemSublist.setSublistValue({
                            id: 'custpage_item_vendorso',
                            line: i,
                            value: vendorso
                        });
                    }
                }

                return false;
            }
        });

        context.response.writePage(form);
    }

    return {
        onRequest : onRequest_
    }
});

Чтобы сохранить запись, я начал с создания этого клиентского сценария:

/**
*@NApiVersion 2.x
*@NScriptType ClientScript
*/
define(['N/record'],
function(record) {
    function pageInit(context) {
        try {
            var cr = context.currentRecord;
        } catch (e) {
            console.log('pageInit_ ERROR : ' + e.message);
        }
    }
    function updateRecord(context) {
        console.log("foo");
    }
    return {
    pageInit: pageInit,
    updateRecord: updateRecord
    };
});

В функции pageInit я запутался, как получить запись, над которой я работаю, в качестве context.currentRecord, чтобы внести изменения и зафиксировать?

Ответы [ 2 ]

0 голосов
/ 30 ноября 2018

Существует два способа получения данных текущей записи на стороне клиента.

1) Использование модуля N / currentRecord

Пример:

var currentRecObj = currentRecord.get();
var entity = currentRecObj.getValue('entity');

2) Использование параметра scriptContext на стороне клиента. Функции SuiteScript

Пример:

function pageInit(scriptContext) {
    var currentRecObj = scriptContext.currentRecord;
    var entity = currentRecObj.getValue('entity');
}
0 голосов
/ 18 ноября 2018

Для клиентских сценариев, работающих на Suitelet, pageInit не передается ни в каком контексте.Вы извлекаете данные из текущей формы, загружая модуль N/currentRecord и используя его метод get(), чтобы получить ссылку на форму в контексте.Оттуда вы можете работать с ним как с обычным Record экземпляром.

...