Text Fields


A text field is text content that is usually seamlessly inserted into the existing text, but the actual content comes from elsewhere-for example, the total number of pages or a database field. Table 24 lists the standard field types.

Table 24: Text field interfaces starting with com.sun.star.text.TextField.

Field Type

Description

Annotation

Inserted note with string properties Author and Content. The property Date, of type com.sun.star.util.Date, contains the date that the note was created.

Author

Displays the document's author. The following optional fields may be present:

  • IsFixed - If False, the author is modified every time the document is saved.

  • Content - String content of the text field.

  • AuthorFormat - Constants from the com.sun.star.text.AuthorDisplayFormat constant group ; these have the values: FULL (0), LAST_NAME (1), FIRST_NAME (2), or INITIALS (3).

  • CurrentPresentation - String containing the current text of the field.

  • FullName - If False, the initials are displayed rather than the full name .

Bibliography

Contains a property named Fields, which is an array of type PropertyValue. This field is dependent on a Bibliography text field master.

Chapter

Chapter information. The Level property is a Byte integer. The ChapterFormat property is a constant group of type com.sun.star.text. ChapterFormat with the following valid values: NAME (0), NUMBER (1), NAME_NUMBER (2), NO_PREFIX_SUFFIX (3), or DIGIT (4).

CharacterCount

Indicates the number of characters in the document. This contains one property, NumberingType, from the constant group com.sun.star.style.NumberingType; valid values are shown in Table 25.

CombinedCharacters

Displays one to six characters and treats them as one character.

ConditionalText

Displays text that changes based on a condition in the text field.

  • TrueContent - String to use if the condition is True.

  • FalseContent - String to use if the condition is False.

  • Condition - String condition to evaluate.

  • IsConditionTrue - Boolean result of the evaluation (read-only value).

DDE

Displays the result from a DDE connection. Uses a DDE text field master.

Database

Database text field used as a mail-merge field. This field depends on a text field master and contains the following properties:

  • Content - Merged database content as a String.

  • CurrentPresentation - Displays content as a String.

  • DataBaseFormat - If True, the database number display format is used.

  • NumberFormat - com.sun.star.util.NumberFormatter that formats the field.

DatabaseName

Display the database name when performing database operations (depends on a text field master) with these properties:

  • DataBaseName - String containing the database name.

  • DataCommandType - Constant group com.sun.star.sdb.CommandType specifies what DataTable Name supports: TABLE (0), QUERY(1), or COMMAND (2).

  • DataTableName - String containing the table name, query, or statement.

DatabaseNextSet

Increment a selection (depends on a text field master) with these properties:

  • DataBaseName - String name of the database.

  • DataCommandType - Constant group com.sun.star.sdb.CommandType specifies what DataTable Name supports: TABLE (0), QUERY(1), or COMMAND (2).

  • DataTableName - String containing the table name, query, or statement.

  • Condition - String that determines if the selection is advanced to the next position.

DatabaseNumberOfSet

Set the database cursor selection (depends on a text field master) with these properties:

  • DataBaseName - String name of the database.

  • DataCommandType - Constant group com.sun.star.sdb.CommandType specifies what DataTable Name supports: TABLE (0), QUERY(1), or COMMAND (2).

  • DataTableName - String containing the table name, query, or statement.

  • Condition - String condition that determines if the SetNumber is applied.

  • SetNumber - Long Integer set number to be applied.

DatabaseSetNumber

Display the current database set number (depends on a text field master) with these properties:

  • DataBaseName - String name of the database.

  • DataCommandType - Constant group com.sun.star.sdb.CommandType specifies what DataTableName supports: TABLE (0), QUERY(1), or COMMAND (2).

  • DataTableName - String containing the table name, query, or statement.

  • Numbering Type - See CharacterCount property for valid values.

  • SetNumber - Long Integer database set.

DateTime

Display a date or time with the following optional properties:

  • IsFixed - If False, the current date or time is displayed.

  • IsDate - If False, this is only a time. If True, this is a date with an optional time.

  • DateTimeValue - com. sun. star. util.DateTime object with the actual content.

  • NumberFormat - com.sun.star.util.NumberFormatter that formats the field.

  • Adjust - Long Integer offset to the date or time in minutes.

  • IsFixedLanguage - If False, setting the adjacent text language may change the field display.

DropDown

Display a drop-down field with the following properties:

  • Name - Field name.

  • Items - Array of strings with the drop-down value.

  • Selected Item - The selected item or an empty string if nothing is selected.

EmbeddedObjectCount

Display the number of objects embedded in the document. Contains the NumberingType property; see CharacterCount property for valid values.

ExtendedUser

Display information for the user data (under Tools I Options I OpenOffice.org I User Data) such as name, address, or phone number.

  • Content - String content.

  • Current Presentation - String containing the current text of the field.

  • IsFixed - If False, the content is updated.

  • UserDataType - Specify what to display from the com.sun.star.text.UserDataPart constant group: COMPANY, FIRSTNAME, NAME, SHORTCUT, STREET, COUNTRY, ZIP, CITY, TITLE, POSITION, PHONE_PRIVATE, PHONE_COMPANY, FAX, EMAIL, STATE.

FileName

Display the document file name (URL). Contains the following properties:

  • Current Presentation - String containing the current text of the field.

  • FileFormat - File name format com.sun.star.text.FilenameDisplayFormat constants with the following values: FULL, PATH, NAME, and NAME_AND_EXT.

  • IsFixed - If False, the content is updated.

GetExpression

Display the result from a "get expression" text field.

  • Content - String content

  • CurrentPresentation - String containing the current text of the field.

  • NumberFormat - com.sun.star.util.NumberFormatter that formats the field.

  • NumberingType - See CharacterCount property for valid values.

  • IsShowFormula - If True, the formula is displayed rather than the content.

  • SubType - Variable type from the com.sun.star.text.SetVariableType constants with the following values: VAR, SEQUENCE, FORMULA, and STRING.

  • Value - Numerical (Double) value of the field.

  • IsFixedLanguage - If False, setting the adjacent text language may change the field display.

GetReference

Reference field with these properties:

  • Current Presentation - String containing the current text of the field.

  • Reference FieldSource - com.sun.star.text.Reference Field Source constant with the following values: REFERENCE MARK, SEQUENCE FIELD, BOOKMARK, FOOTNOTE, or ENDNOTE.

  • SourceName - String reference name such as a bookmark name.

  • Reference Field Part - com.sun. star.text.Reference FieIdPart constant with the following values: PAGE, CHAPTER, TEXT, UP - DOWN, PAGE - DESC, CATEGORY - AND - NUMBER, ONLY CAPTION, and ONLY_SEQUENCE_NUMBER.

  • SequenceNumber - Short integer sequence number used as sequence field or Referenceld property of a footnote or endnote.

GraphicObjectCount

Display the number of graphic objects embedded in the document. Contains the NumberingType property; see CharacterCount property for valid values.

HiddenParagraph

Allow a paragraph to be hidden. Used, for example, to create a test with the questions and answers all in one document. Setting the answers to hidden allows the test questions to be printed for the students.

  • Condition - String condition to evaluate.

  • IsHidden - Boolean result of the last evaluation of the condition.

HiddenText

A field with hidden text. Differs from a hidden paragraph in that only the text in the field is hidden, rather than the entire containing paragraph.

  • Content - String text content of the hidden text field.

  • Condition - String condition.

  • IsHidden - Boolean result of the last evaluation of the condition.

Input

Text input field.

  • Content - String text content of the field.

  • Hint - String hint text.

InputUser

User-defined text field that depends on a field master.

  • Content - String text content of the field.

  • Hint - String hint text.

JumpEdit

Placeholder text field.

  • Hint - String hint text.

  • PIaceHolder - String text of the placeholder.

  • PIaceHolderType - com.sun.star.text. PlaceholderType constant with the following valid values: TEXT, TABLE, TEXTFRAME, GRAPHIC, or OBJECT.

Macro

Macro text field.

  • Hint - Sting hint text.

  • MacroName - String macro name to run.

  • MacroLibrary - String library name that contains the macro.

PageCount

Display the number of pages in the document. Contains the NumberingType property; see CharacterCount property for valid values.

PageNumber

Display a page number.

  • Offset - Short Integer offset to show a different page number.

  • SubType - Which page is displayed from the com.sun.star.text.PageNumberType enumeration. Valid values: PREV, CURRENT, or NEXT.

  • UserText - String that is displayed when the NumberingType is CHAR_SPECIAL.

  • NumberingType - See CharacterCount property for valid values.

ParagraphCount

Display the number of paragraphs in the document. Contains the NumberingType property; see CharacterCount property for valid values.

Reference PageGet

Display the page number of a reference point. Contains the NumberingType property; see CharacterCount property for valid values.

Reference PageSet

Insert additional page numbers . Contains these properties:

  • Offset - Short Integer that changes the displayed value of a ReferencePageGet field.

  • NameOn - If True, the ReferencePageGet text fields are displayed.

Script

Display text obtained by running a script. Contains these properties:

  • Content - Script text or URL of the script as a string.

  • ScriptType - String script type, such as JavaScript.

  • URLContent - If True, Content is a URL. If False, Content is the script text.

SetExpression

An expression text field. Contains these properties:

  • Content - String content.

  • CurrentPresentation - String containing the current text of the field.

  • NumberFormat - com.sun.star.util.NumberFormatter that formats the field.

  • NumberingType - See CharacterCount property for valid values.

  • IsShowFormula - If True, the formula is displayed rather than the content.

  • Hint - String hint used if this is an input field.

  • IsInput - If True, the field is an input field.

  • IsVisible - If True, the field is visible.

  • SequenceValue - Sequence value when this field is used as sequence field.

  • SubType - Variable type from the com.sun.star.text.SetVariableType constants with the following values: VAR, SEQUENCE, FORMULA, and STRING.

  • Value - Numerical (Double) value of the field.

  • VariableName - Name of the associated set expression field master.

  • IsFixedLanguage - If False, setting the adjacent text language may change the field display.

TableCount

Display the number of tables in the document. Contains the NumberingType property; see CharacterCount property for valid values.

TemplateName

Display the name of the template used to create the document. Supports the FileFormat property as supported by the Filename property.

URL

Display a URL. Contains these properties:

  • Format - Short Integer specifying the URL output format.

  • URL - String containing the unparsed original URL.

  • Representation - Display string shown to the user.

  • TargetFrame - String frame name where the URL will be opened.

User

Display a user-defined field with a field master. Contains these properties:

  • IsShowFormula - If True, the formula is displayed rather than the content.

  • IsVisible - If True, the field is visible.

  • NumberFormat - com.sun.star.util.NumberFormatter that formats the field.

  • IsFixedLanguage - If False, setting the adjacent text language may change the field display.

WordCount

Display the number of words in the document. Contains the NumberingType property; see CharacterCount property for valid values.

docinfo.ChangeAuthor

Display the name of the last author to modify the document.

  • Author - String containing the name of the author.

  • CurrentPresentation - Current content of the text field as a String.

  • IsFixed - If False, the content is updated when the document is saved.

docinfo.ChangeDateTime

Display the date and time the document was last changed. Contains these properties:

  • CurrentPresentation - Current content of the text field as a String.

  • IsFixed - If False, the current date or time is displayed.

  • IsDate - If False, this is only a time. If True, this is a date with an optional time.

  • DateTimeValue - com.sun.star.util.DateTime object with the actual content.

  • NumberFormat - com.sun.star.util.NumberFormatter that formats the field.

  • IsFixedLanguage - If False, setting the adjacent text language may change the field display.

docinfo.CreateAuthor

Display the name of the author who created the document (see docinfo.ChangeAuthor for supported properties).

docinfo.CreateDateTime

Display the date and time the document was created (see docinfo.ChangeDateTime for supported properties).

docinfo.Description

Display the document description as contained in the document properties (File Properties).

  • Content - String content.

  • CurrentPresentation - String containing the current text of the field.

  • IsFixed - If False, the content is updated when the document information is changed.

docinfo.EditTime

Display the duration the document has been edited. In other words, how long did it take to write?

  • CurrentPresentation - String containing the current text of the field.

  • IsFixed - If False, the date or time is always displayed as the current date or time.

  • DateTimeValue - Date and time as a Double.

  • NumberFormat - com.sun.star.util.NumberFormatter that formats the field.

  • IsFixedLanguage - If False, setting the adjacent text language may change the field display.

docinfo.InfoO

Display the document info 0 (see doc.Description).

docinfo.Info1

Display the document info 1 (see doc.Description).

docinfo.Info2

Display the document info 2 (see doc.Description).

docinfo.Info3

Display the document info 3 (see doc.Description).

docinfo.Keywords

Display the document info keywords (see doc.Description).

docinfo.PrintAuthor

Display the name of the author who printed the document (see docinfo.ChangeAuthor for supported properties).

docinfo.PrintDateTime

Display the time the document was last printed (see docinfo.Change DateTime for supported properties).

docinfo.Revision

Display the current document revision (see doc.Description).

docinfo.Subject

Display the document subject specified in the document information (see doc.Description).

docinfo.Title

Display the document title specified in the document information (see doc.Description).

Table 25: Constants defined by com.sun.star.style.NumberingType.

Constant

Description

CHARS_UPPER_LETTER

Numbering is in uppercase letters as "A, B, C, D, ...".

CHARS_LOWER_LETTER

Numbering is in lowercase letters as "a, b, c, d,...".

ROMAN_UPPER

Numbering is in Roman numbers with uppercase letters as "I, II, III, IV, ...".

ROMAN_LOWER

Numbering is in Roman numbers with lowercase letters as "i, ii, iii, iv, ...".

ARABIC

Numbering is in Arabic numbers as "1, 2, 3, 4, ...".

NUMBER_NONE

Numbering is invisible.

CHAR_SPECIAL

Use a character from a specified font.

PAGE_DESCRIPTOR

Numbering is specified in the page style.

BITMAP

Numbering is displayed as a bitmap graphic.

CHARS_UPPER_LETTER_N

Numbering is in uppercase letters as "A, B, ..., Y, Z, AA, BB, CC, ... AAA, ...".

CHARS_LOWER_LETTER_N

Numbering is in lowercase letters as "a, b, ..., y, z, aa, bb, cc, ... aaa, ...".

TRANSLITERATION

A transliteration module is used to produce numbers in Chinese, Japanese, etc.

NATIVE_NUMBERING

The native-number-supplier service is called to produce numbers in native languages.

FULLWIDTH_ARABIC

Numbering for full-width Arabic number.

CIRCLE_NUMBER

Bullet for Circle Number.

NUMBER_LOWER_ZH

Numbering for Chinese lowercase numbers.

NUMBER_UPPER_ZH

Numbering for Chinese uppercase numbers.

NUMBER_UPPER_ZH_TW

Numbering for Traditional Chinese uppercase numbers.

TIAN_GAN_ZH

Bullet for Chinese Tian Gan.

DI_ZI_ZH

Bullet for Chinese Di Zi.

NUMBER_TRADITIONAL_JA

Numbering for Japanese traditional numbers.

AIU_FULLWIDTH_JA

Bullet for Japanese AIU full width.

AIU_HALFWIDTH_JA

Bullet for Japanese AIU half width.

IROHA_FULLWIDTH_JA

Bullet for Japanese IROHA full width.

IROHA_HALFWIDTH_JA

Bullet for Japanese IROHA half width.

NUMBER_UPPER_KO

Numbering for Korean uppercase numbers.

NUMBER_HANGUL_KO

Numbering for Korean hangul numbers.

HANGUL_JAMO_KO

Bullet for Korean Hangul Jamo.

HANGUL_SYLLABLE_KO

Bullet for Korean Hangul Syllable.

HANGUL_CIRCLED_JAMO_KO

Bullet for Korean Hangul Circled Jamo.

HANGUL_CIRCLED_SYLLABLE_KO

Bullet for Korean Hangul Circled Syllable.

CHARS_ARABIC

Numbering in Arabic alphabet letters.

CHARS_THAI

Numbering in Thai alphabet letters.

The Annotation field is a service of type com.sun.star.text.TextField.Annotation. Some sources of documentation show the text "textfield" in all lowercase letters; this is incorrect. The code in Listing 48 shows this correctly.

Listing 48: DisplayFields is found in the Writer module in this chapter's source code files as SC13.sxw.
Tip  
start example
 Sub DisplayFields   oEnum = ThisComponent.getTextFields().createEnumeration()   Do While oEnum.hasMoreElements()     oField = oEnum.nextElement()     s = s & oField.getPresentation(True)  & " = "    'Field type     If oField.supportsService("com.sun.star.text.TextField.Annotation") Then       REM More cryptic, I could use If oField.getPresentation(True) = "Note"...       REM A "Note" has no displayed content so calling getPresentation(False)       REM returns an empty string. Instead, obtain the author and the content.       s = s & oField.Author & " says " & oField.Content     Else       s = s & oField.getPresentation(False)          'String content     End If     s = s & CHR$(13)   Loop   MsgBox s, 0, "Text Fields" End Sub 
end example
 

Table 25 contains the valid values for the CharacterCount property from Table 24.

The text fields contained in the document are available using the getTextFields() object method (see Table 17). Every text field object supports the object method getPresentation(boolean), which returns a string representing either the field type (True) or the displayed text (False). See Listing 48 and Figure 2 .

click to expand
Figure 2: Text fields in the current document.

The source document used to create Figure 2 contains a DateTime field, PageNumber fields, Annotation field, and a User field. The code in Listing 48 provides special treatment for note fields to display both the author and the note. The field is checked to see if it supports the Annotation service by using the supportsServiceObject() method.

The primary method of finding a specific text field is by enumerating the text fields as shown in Listing 48. If the document is large and contains many text fields, it may take a long time to find a specific text field. If you know where the text field is located in the document, Listing 20 demonstrates how to find a text field by enumerating text content in a paragraph.

Note  

Text fields implement the object method update(). The update() method causes a text field to update itself with the most current information if it is applicable . For example, date/time, file name, and the document information text fields all update to the most current information.

Text Master Fields

Some text fields contain their own content, and others rely on an external source to obtain the displayed information. The external source is called a master field. Table 26 lists the text field types that require a master field. Besides the properties shown in Table 26, every text field master also supports the properties shown in Table 27 .

Table 26: Text field interfaces starting with com.sun.star.text.FieldMaster.

Field Type

Description

Bibliography

Field master to a Bibliography text field. Contains these properties:

  • IsNumberEntries - If True, the fields are numbered; otherwise , the short entry name is used.

  • IsSortByPosition - If True, the bibliography index is sorted by the document position (see SortKey).

  • BracketBefore - The opening bracket displayed in the Bibliography text field.

  • BracketAfter - The closing bracket displayed in the Bibliography text field.

  • SortKeys - This array of PropertyValues is used if IsSortByPosition is False. The properties are a sequence of the property SortKey (com.sun.star.text.BibliographyDataField constant identifying the field to sort ) and IsSortAscending (Boolean).

  • Locale - com.sun.star.lang.Locale of the field master.

  • SortAlgorithm - String containing the name of the sort algorithm used to sort the text fields.

DDE

Field master to a DDE text field. Contains these properties:

  • DDECommandElement - DDE command as a string.

  • DDECommandFile - File string of the DDE command.

  • DDECommandType - DDE command type as a string.

  • IsAutomaticUpdate - If True, the DDE link is automatically updated.

Database

Field master to a Database text field. Contains these properties:

  • DataBaseName - String name of the data source.

  • CommandType - Long Integer CommandType (0 = table, 1 = query, 2 = statement).

  • DataTableName - Command string type is determined by the CommandType property.

  • DataColumnName - Database table name as a String.

SetExpression

Field master to a "set expression" text field. Contains these properties:

  • ChapterNumberingLevel - Chapter number as a byte, if this is a number sequence.

  • NumberingSeparator - Numbering separator string, used if this is a number sequence.

  • SubType - Variable type from the com.sun.star.text.SetVariableType constants with the following values: VAR, SEQUENCE, FORMULA, and STRING.

User

Field master to a user text field. Contains the properties:

  • IsExpression - If True, the field contains an expression.

  • Value - Double value.

  • Content - Field content as a string.

Table 27: Properties defined by the service com.sun.star.text.FieldMaster.

Property

Description

Name

Optional string with the field name; this must be set before the field is added to the document.

DependentTextFields

Array of text fields that use this master field.

InstanceName

String instance name as it is used in the XTextFieldsSupplier.

Bug  

The object method getTextFieldMaster() returns a text field's master field. Unfortunately, every field, even fields that do not have master fields, implements this method and returns a non-null master field. OOo 1.1.0 may crash if you obtain and manipulate a master field from a field that does not contain one.

Although text fields are accessible only by enumeration, master fields are accessible by name and enumeration (see Table 17). The name used for a master field is obtained by appending the field name to the field master type. For example, the User field "AndyField", as shown in Figure 2, has a master field named com.sun.star.text.Field-Master.User.AndyField. Database master fields are named differently than all of the other master fields; they append the DatabaseName, DatatableName, and DataColumnName to the service name. Listing 49 demonstrates how to obtain the text field masters in a document. Figure 3 shows the results.

click to expand
Figure 3: Text fields in the current document.
Listing 49: ShowFieldMasters is in the Writer module in this chapter's source code files as SC13.sxw.
start example
 Sub ShowFieldMasters   Dim oMasters      'All of the text field masters   Dim oMasterNames  'Array of the text field master names   Dim i%, j%        'Index variables   Dim sMasterName$  'Full name of the master field   Dim s$            'Utility string   Dim oMaster       'Master field   REM Obtain the text field masters object.   oMasters = ThisComponent.getTextFieldMasters()   REM Obtain ALL of the text master field names.   REM This is an array of strings.   oMasterNames = oMasters.getElementNames()   For i = LBound(oMasterNames) to UBound(oMasterNames)     REM For a given name, obtain the master field,     REM then look at the DependentTextFields property,     REM which is an array of text fields that depend     REM on this master field.     sMasterName = oMasterNames(i)     oMaster = oMasters.getByName(sMasterName)     s = s & "***" & sMasterName & "***" & CHR$(10)     s = s & oMaster.Name & " Contains " &_         CStr(UBound(oMaster.DependentTextFields) +1) &_         " dependent fields" & CHR$(10)     s = s & CHR$(13)   Next i   REM Directly obtain a master field based on the name.   REM This is a user field that I added to the source code file.   If oMasters.hasByName("com.sun.star.text.FieldMaster.User.AndyField") Then     oMaster=oMasters.getByName("com.sun.star.text.FieldMaster.User.AndyField")     s = s & "Directly obtained the field master " & oMaster.Name & CHR$(10) &_         "The field contains the text " & oMaster.Content   End If   MsgBox s, 0, "Text Field Masters" End Sub 
end example
 

Creating and Adding Text Fields

Text fields must be created by the document that will contain them. It is also the document that will destroy them if you choose to remove them from the document. Listing 50 demonstrates the creation, configuration, and insertion of both a DateTime text field and an Annotation text field. The text fields are appended to the end of the document. The DateTime text field is formatted in an unusual manner, so a new number format style is created if it does not yet exist.

Listing 50: InsertFields is in the Writer module in this chapter's source code files as SC13.sxw.
start example
 Sub InsertFields   Dim oText   'Text object for the current document   Dim oField  'Field to insert   Dim oDoc    'oDoc is fewer characters than ThisComponent   oDoc = ThisComponent   oText = oDoc.Text   REM Start by inserting a date time text field at the end of the   REM document. Format the date time as "DD. MMM YYYY"   REM Insert some explanatory text before the newly inserted field.   oText.insertString(oText.getEnd(), "Today is ", FALSE)   REM Create a date time field.   oField = oDoc.createInstance("com.sun.star.text.TextField.DateTime")   oField.IsFixed = TRUE   oField.NumberFormat = FindCreateNumberFormatStyle("DD. MMMM YYYY", oDoc)   oText.insertTextContent(oText.getEnd(), oField, False)   REM Now, insert an Annotation after the inserted text field.   Dim oDate As New com.sun.star.util.Date   REM Lie about the date and say that I did it a little while ago!   With oDate     .Day   = Day(Now - 10)     .Month = Month(Now - 10)     .Year  = Year(Now - 10)   End With   REM Like most text content, the field must be created by the document   REM that will contain it.    oField = oDoc.createInstance("com.sun.star.text.TextField.Annotation")   With oField     .Author  = "AP"     .Content = "This note is next to a date field that I just added"     .Date    = oDate 'Ommit the date and it defaults to today!   End With   oText.insertTextContent(oText.getEnd(), oField, False)   MsgBox "Two fields inserted at the end of the document" End Sub Function FindCreateNumberFormatStyle (_   sFormat As String, Optional doc, Optional locale)   Dim oDocument  'Document to use   Dim oFormats   'All of the format objects   Dim formatNum% 'Index of number format in the number formats.   Dim aLocale as new com.sun.star.lang.Locale   REM Use doc if it was provided and ThisComponent if it was not.   oDocument = IIf(IsMissing(doc), ThisComponent, doc)   oFormats = oDocument.getNumberFormats()   REM I use a newly created locale and let it use the default for my system   REM unless a format was passed in.   If ( Not IsMissing(locale)) Then     aLocale = locale   End If   REM See if the number format exists by obtaining the index of   REM the number format with the specified style.   formatNum = oFormats.queryKey (sFormat, aLocale, TRUE)   REM If the number format does not exist then add it.   If (formatNum = -1) Then     formatNum = oFormats.addNew(sFormat, aLocale)     REM If failed to add, and it should not fail to add, then use zero.     If (formatNum = -1) Then formatNum = 0   End If   FindCreateNumberFormatStyle = formatNum End Function 
end example
 

Inserting a field that requires a text field master is slightly more difficult than inserting a regular text field. Both the master field and the dependent text field must be created by the document using the object method creatcInstance (). The master field must be named before it is used; after inserting a field into a document, you cannot change the name. The dependent field is attached to the master field, which provides the content to the dependent field. The dependent field, not the master field, is inserted as text content into the document. The dependent field can be removed from the document by using the removeTextContent() object method. To remove the master field, use the dispose() method of the master field.

Listing 51 demonstrates the use of master fields by performing various operations on a master field named "TestField". Three specific states are checked and appropriate behavior is taken as follows :

  • If the master field does not exist, the master field and a dependent field are created and inserted into the document. The field is now visible by opening the Field dialog using Insert Fields Other and choosing the Variables tab.

  • If the master field exists with a corresponding dependent field, the dependent field is removed from the document. The master field still exists, but no dependent field is inserted in the document. You can view the master field by using the Field dialog.

  • If the master field exists and has no corresponding dependent field, the master field is removed by using the dispose() object method. The Field dialog no longer shows the master field.

Listing 51: InsertFieldMaster is in the Writer module in this chapter's source code files as SC13.sxw.
start example
 Sub InsertFieldMaster   Dim oMasters  'All of the text field masters   Dim oText     'Text object for the current document   Dim oUField   'User field to insert   Dim oMField   'The master field for the user field   Dim oDoc      'oDoc is fewer characters than ThisComponent   Dim sLead$    'Leading field name   Dim sName$    'Name of the field to remove or insert   Dim sTotName$ 'The entire name   REM Set the names.   sName = "TestField"   sLead = "com.sun.star.text.FieldMaster.User"   sTotName = sLead & "." & sName   REM Initialize some values.   oDoc = ThisComponent   oText = oDoc.Text   oMasters = ThisComponent.getTextFieldMasters()   REM If the master field already exists, then perform special handling.   REM Special handling is for illustrative purposes only, not that it   REM solves any particularly fun and exciting problem.   If oMasters.hasByName(sTotName) Then     REM Obtain the master field and the fields dependent on this field.     oMField = oMasters.getByName(sTotName)     REM If there are fields dependent on this field then     REM the array of dependent fields has values!     If UBound(oMField.DependentTextFields) >= 0 Then       REM Remove the text content and it disappears from the       REM document. The master field still exists, however!       oUField = oMField.DependentTextFields(0)       oText.removeTextContent(oUField)       MsgBox "Removed one instance from the document"     Else       REM I arbitrarily decided that I would destroy the master field       REM but I could just as easily create a new user field and       REM attach it to the existing master field and then insert       REM the new field into the document.       MsgBox "No instances in the document, disposing master field"       oMField.content=""       oMField.dispose()     End If   Else     REM Create a User text field that requires a master field.     oUField = oDoc.createInstance("com.sun.star.text.TextField.User")     REM Now create the master field.     Dim oMasterField     oMasterField = oDoc.createInstance(sLead)     REM You CANNOT change the name of a master field AFTER it is inserted     REM into a document so you must set it now.     oMasterField.Name = sName     REM This is the data that will be displayed. Remember that the     REM user field displays what the master tells it to display.     oMasterField.Content = "Hello"     REM A user field must be attached to a master field.     REM The user field is now a "DependentTextField".     oUField.attachTextFieldMaster(oMasterField)     REM Insert the user field into the document.     oText.insertTextContent(oText.getEnd(), oUField, False)     MsgBox "One field inserted at the end of the document"   End If End Sub 
end example
 

Bookmarks

A bookmark is text content that is accessible based on its name. A bookmark may encompass a text range or a single point. Listing 38 inserts text content at the point where a bookmark is anchored. Use the getString() object method to obtain the string contained in the bookmark. Use setString() to set the string contained in the bookmark. If the bookmark is merely a point, the text is merely inserted before the bookmark. When a created bookmark is inserted into the text, the insertion point determines the bookmark's anchor position. See Listing 51 .

Listing 51: AddBookmark is in the Writer module in this chapter's source code files as SC13.sxw.
start example
 Sub AddBookmark   Dim oBookmark  'Created bookmark to add   Dim oCurs      'Text cursor   REM Create a text cursor that contains the last four characters   REM in the document.   oCurs = ThisComponent.Text.createTextCursor()   oCurs.gotoEnd(False)   oCurs.goLeft(4, True)   REM Create the bookmark.   oBookmark = ThisComponent.createInstance("com.sun.star.text.Bookmark")   REM If the bookmark is not given a name, OOo will create a name.   REM If the name already exists, a number is appended to the name.   oBookmark.setName("Bobert")   REM Because True is used, the bookmark contains the last four characters   REM in the document. If False is used instead, then the bookmark   REM contains no characters and it is positioned before the fourth character   REM from the end of the document.   ThisComponent.Text.insertTextContent(oCurs, oBookmark, False) End Sub 
end example
 



OpenOffice.org Macros Explained
OpenOffice.org Macros Explained
ISBN: 1930919514
EAN: 2147483647
Year: 2004
Pages: 203

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net