Reputation: 21
I have an Office web add-in for Word that needs to fetch custom properties from an API and store them under document.properties.customProperties
the user will then be able to insert them into their document as a DocProperty field. This is done using the following code snippet:
await Word.run(async (context) => {
var range = context.document.getSelection().getRange();
range.insertField(Word.InsertLocation.after, Word.FieldType.docProperty, '"' + req.property + '"', false);
await context.sync();
dialog.close();
});
This all works fine and I can see that the custom properties are being set correctly. My problem occurs when trying to update the fields. Simply using "Select All + F9" won't work in my case since I first need to fetch the custom properties from an API to make sure they are up-to-date so my only option is using a custom Ribbon button.
The updating of the fields is done using the following snippet:
async function updateAllFields(event) {
await Word.run(async (context) => {
// fetch properties from API
await getFileProperties()
context.document.body.fields.load();
await context.sync()
var field = context.document.body.fields.getFirstOrNullObject();
await updateField(context, field)
});
event.completed();
}
async function updateField(context, field) {
await field.load();
await context.sync();
if (field.isNull) {
return;
}
await field.updateResult();
await context.sync();
const nextField = field.getNextOrNullObject();
if (nextField) {
await updateField(context, nextField);
}
}
When I execute the updateAllFields function through the console it works exactly as expected, but when I try to run it through a Ribbon button it simply fails without errors.
Some information that might be relevant
The requested permissions are ReadWriteDocument
The action is defined as follows
<Action xsi:type="ExecuteFunction">
<FunctionName>updateAllFields</FunctionName>
</Action>
The add-in uses the SharedRuntime
option.
Upvotes: 0
Views: 114
Reputation: 9784
I see a couple problems with your code. First the line if (nextField)
should be if (!(nextField.isNull))
. The way you have written it, it is always going to be true because you are testing for the existence of the proxy object and since you just created it in the preceding line, it always exists. What you want to test is whether the corresponding object in the Word doc exists.
Second, your code is kind of hard to read because you've got the test for field.isNull
inside a subfunction. The best practice when an object might be null is to test for nullity before you do anything with the object, including passing it to a subfunction.
Upvotes: 0