Blog

Our News/Articles/Opinions/Technotes from the world of HCL Digital Solutions

count Acttachments Rich Text Field Image

Count attachments in Rich Text Fields – LotusScript Function

We came across a situation where we needed to be able to count how many attachments were in a rich text field in LotusScript.

Scenario – We had a table with four tabbed rows. In each tab was a rich text field (which was hidden unless user clicked on tab). We needed a way of viewing how many attachments (if any) each rich text field was holding without clicking on each tab to see.

The below function CountAttachmentsRTF takes in two arguments, a NotesDocument variable, and a rich text field name as a string.

This function depends on the function IsRtfMT. This Function can be found at https://searchdomino.techtarget.com/tip/Check-Rtf-Field-Empty-New-One-Which-Works.

The Function CountAttachmentsRTF returns an integer which is equal to the total attachments in the provided rich text field.

Function CountAttachmentsRTF (doc As NotesDocument, rtfFieldName As String) As Integer
'-------------------------------
' Functionality: Counts how many attachments a Rich Text Field holds. 
' Author: Adrian Marikar
' Company: Domino People Ltd
' Date: 12/02/2020
' Dependency
'    IsrtfMT function (https://searchdomino.techtarget.com/tip/Check-Rtf-Field-Empty-New-One-Which-Works)
'-------------------------------

' Error handling: https://www.polymorph.co.uk/content/blog-posts/lotusscript-error-handling-in-a-structured-manner/
  ' Use any error handling method you like. 
  
If True Then

Dim AttachmentsField As Variant
Dim counter As Integer
    
try:
  On Error Goto catch
  Set AttachmentsField = doc.GetFirstItem(rtfFieldName)
  counter% = 0
    'Use isrtfMT function to validate if rtf is not empty i.e. has attachments or text
  If isrtfMT(doc, rtfFieldName) = 0 Then 
      If Isarray(AttachmentsField.EmbeddedObjects) Then ' Isarray validates for attachments ignoring embedded text
        Forall att In AttachmentsField.EmbeddedObjects
            If att.Type = EMBED_ATTACHMENT Then
                counter% = counter + 1
            End If
        End Forall
    Else
    counter = 1 'If embedded text only, then add 1 to counter. 
    End If
  End If
Else
catch:
    On Error Goto 0
    ' Displays error details to user
'Turn on for debugging
' Msgbox "Fn: CountAttachmentsRTF" & " ERROR: " & Error$ & " (" & Err & ") on line " & Erl

' handle the error
    Select Case Err
    Case Else
        ' an error I can't handle here so pass back to caller
        Error Err, Error$
    End Select
    Resume finally
End If
finally:
CountAttachmentsRTF = counter ' return counter (integer)
End Function



Function IsrtfMT (doc As Notesdocument , FieldName As String) As Integer
' Purpose: This function checks if a rich text field is empty
' Origin: This function is taken from https://searchdomino.techtarget.com/tip/Check-Rtf-Field-Empty-New-One-Which-Works
' Error handling: https://www.polymorph.co.uk/content/blog-posts/lotusscript-error-handling-in-a-structured-manner/
' Use any error handling method you like. 
  
If True Then

Dim mbdcount As Integer
Dim plaintext As String
Dim rtitem As Variant
    
try:
    On Error Goto catch
    ' do some code
    mbdcount =0 ' initialize
    Set rtitem = doc.GetFirstItem(fieldname)
    If ( rtitem.Type = RICHTEXT ) Then
        plainText = rtitem.GetFormattedText( False, 0 ) ' render the Rich item into text this gets all text values and ignores attachments/OLE
        If Len(plaintext) < 1 Then		
            If Isarray(rtitem.EmbeddedObjects) Then
                Forall o In rtitem.EmbeddedObjects ' loop through array of embedded objects in the rich text item
                    mbdcount=mbdcount+1 ' there is at least one emb object
                End Forall
            End If
        End If
    End If
Else
catch:
On Error Goto 0
'Turn on for debugging
'Msgbox fnName & " ERROR: " & Error$ & " (" & Err & ") on line " & Erl	
' handle the error
Select Case Err
Case Else
    ' an error I can't handle here so pass back to caller
    Error Err, Error$
End Select
Resume finally
End If
finally:
If (mbdcount + Len(plaintext)) < 1 Then ' if there are no embedded objects AND there is no text also
    IsrtfMT=1 ' return flag to calling string RTF IS EMPTY
Else
    IsrtfMT=0 ' return flag to calling string RTF IS NOT EMPTY
End If
End Function




Example Usage

Step 1. Create a new Notes application (.NSF) and create a new form similar to form in screenshot below. Set up a form similar to below in designer. Important thing is to have at least one rich text field and one result field to display the count. Make the txt_Result fields computed.

Count attachments in Rich Text Field - LotusScript

Step 2. Add both functions to target form’s “Objects” so that they show in Objects window as in screenshot below. You can do this by clicking on Initialize and pasting the functions outside of the Sub tags.

Count attachments in Rich Text Field - LotusScript

Step 3. Paste below code into Initialize Object of target form. This code runs when form is opened for either viewing or editing. If you changed field names or added more/less fields in the form creation step, then please update code to reflect your form.

Sub Initialize
	If True Then
try:
		On Error Goto catch
		Dim ws As New NotesUIWorkspace
		Dim doc As NotesDocument
		Dim uidoc As NotesUIDocument
		
		Set uidoc = ws.CurrentDocument
		Set doc = ws.CurrentDocument.Document
		
		If Not ( uidoc.IsNewDoc ) Then
			'replacing txt_Result fields with number of attachments inside the rti_TestRTF fields
			Call doc.ReplaceItemValue( "txt_Result1",CountAttachmentsRTF(doc, "rti_TestRTF1") )
			Call doc.ReplaceItemValue( "txt_Result2",CountAttachmentsRTF(doc, "rti_TestRTF2") )
		End If
catch:
		On Error Goto 0
		'Displays error details to user
		' Ignoring this error on purpose!
		' Msgbox "Form: LicenseHCL, Sub: Initialize" & " ERROR: " & Error$ & " (" & Err & ") on line " & Erl
		Select Case Err
		Case 0: 
			Exit Sub
		Case Else
			Error Err, Error$
		End Select
		Resume finally
	End If		
	
finally:		
  'Dummy edit/de-edit - This shows value of computed field in UI without having Edit and Save. 
	Call ws.Currentdocument.Close(True)
	Call ws.EditDocument(False, doc)
End Sub

Step 4. Preview form in Notes and fill in fields, placing attachments/text into fields. Ctrl+S to save (if you have not created Save Action button). You can now close the form.

Count attachments in Rich Text Field - LotusScript

Step 5. Create a view that displays the txt_Name field in first column. Preview this view. Double click on the document that we created earlier.

Count attachments in Rich Text Field - LotusScript

As you can see, the counter counts the three PDFs in the first rich text field as 3 and counts the two lines of text as 1. We can now count the attachments in a rich text field in LotusScript.

EDIT: Please note that the lines of text being counted as 1 was a special use case for ourselves. We needed to know if any text existed in rich text field even if there were no embedded attachments. If you do not need this functionality, please comment out line 32 of CountAttachmentsRTF function i.e. counter = 1 ‘If embedded text only, then add 1 to counter.

Best regards,
Adrian Marikar – Domino People Ltd

2 thoughts on “Count attachments in Rich Text Fields – LotusScript Function

    • Adrian Marikar says:

      Hi, Lars. Thank you for pointing this out. I have now updated post. We wanted to know if any text existed in RTI even if there were no embedded attachments. Thanks again. Maybe see you at Engage đŸ™‚

Leave a Reply

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

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>