添付ファイルの更新:app.record.create.submit.successでは失敗して、app.record.edit.submit.successでは成功する

レコードの新規登録と更新後にPDFファイルを添付ファイルを更新したいのですが、

「app.record.edit.submit.success」時は成功して、「app.record.create.submit.success」時は失敗します。

エラー内容は、

{code: ‘CB_VA01’, id: ‘M9FdANAQCDt1T6LcEoQR’, message: ‘入力内容が正しくありません。’, errors: {…}}

filekeyはどちらも取得出来ています。

 

    kintone.events.on(['app.record.create.submit.success', 'app.record.edit.submit.success'], function (event) {

        //blobで出力

        var blob = pdfDoc.output('blob');

        // FormDataにファイルを格納

        var formData = new FormData();

        formData.append(' __REQUEST_TOKEN__', kintone.getRequestToken());

        formData.append('file', blob, InvoiceNum + '.pdf');

        //HttpRequestの送信

        var key;

        var xmlHttp = new XMLHttpRequest();

        xmlHttp.open('POST', kintone.api.url('/k/v1/file.json', true), false);

        xmlHttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

        xmlHttp.send(formData);

        if (xmlHttp.status === 200) {

            key = JSON.parse(xmlHttp.responseText).fileKey;

        }

        console.log("key : " + key);

        var json = {

            app: kintone.app.getId(),

            id: kintone.app.record.getId(),

            record: {

                shiharaiMeisai: {

                    value: [{ fileKey: key }]

                }

            }

        };

        return kintone.api(

            kintone.api.url('/k/v1/record', true),

            'PUT',

            json

        ).catch(function (resp) {

            var errmsg = 'エラーが発生しました。 登録時';

            if (resp.message !== undefined) {

                errmsg += '' + resp.message;

            }

            console.log(errmsg);

            console.log(resp);

            alert(errmsg);

        });

    });

‘app.record.create.submit.success’ イベントでは、まだ kintone.app.record.getId() でレコードIDを取得できません。

event.recordId に、入っていますのでそちらが使えます。

なお xmlHttp.open の同期処理は、多くのブラウザーで非推奨となっていますので、Promise を使った処理に変更されたほうがいいと思います。