Let us implement the event handler in the InputOpeningMaterialBalances document object module.
- Return to Designer and comment out the handler script in the form module.
- In the InputOpeningMaterialBalances document object editor, on the Other tab, open the object module and add the script shown in listing 21.2.
Listing 21.2. BeforeWrite event handler of the object module
Procedure BeforeWrite(Cancel, WriteMode, PostingMode) // Determining whether updating register record dates is required UpdateRegisterRecordsDate = IsNew() Or RegisterRecords.BalanceOfMaterials.Modified(); If Not UpdateRegisterRecordsDate Then // Verifying that the date changed Query = New Query; Query.SetParameter("CurDocument", Ref); Query.Text = "SELECT | Date |FROM | Document.InputOpeningMaterialBalances |WHERE | Ref = &CurDocument"; Selection = Query.Execute().Select(); Selection.Next(); UpdateRegisterRecordsDate = Selection.Date <> Date; EndIf; // Assigning the new date to all records, if required If UpdateRegisterRecordsDate Then If Not RegisterRecords.BalanceOfMaterials.Selected() And Not RegisterRecords.BalanceOfMaterials.Modified() Then RegisterRecords.BalanceOfMaterials.Read(); EndIf; For Each RegisterRecord In RegisterRecords.BalanceOfMaterials Do RegisterRecord.Period = Date; EndDo; EndIf; EndProcedureAs you can see, in this case the handler contains more lines, due to the additional checks that are performed because both interactive and script-based writing of the object is possible.
Let us walk through the handler contents in greater detail. If a new document is written or its register records are changed, you need to update the register record dates. Otherwise, the query reads the document date from the database and then the date is compared to the date of the object being written. If the dates do not match, you also need to update the register record dates.
Before a date is set, the script checks whether a record set was read from the RegisterRecords property of the object and whether it has been modified. If both conditions are false, it means that the record set in the RegisterRecords property of the object is empty and that this condition is not due to its modification. In this case, to prevent erroneous deletion of register records (overwriting them with an empty record set), the script preliminary reads the register records from the register into the RegisterRecords property.
Then, as in the previous scenario (writing register records from a form), the required date is assigned to all the records in that set. When the document object is recorded, this record set is written to the accumulation register.