Search code examples
phpdocxopentbstinybutstrong

How to insert conditional spaces in docx with opentbs (only if certain fields are not blank)


I am using opentbs to generate reports in .docx format from data entered by users into a form, and would like to be able to add spaces between fields conditionally. Here's the paradigm example of the issue: The user must enter a street address (address1), but the fields immediately before and after the address field (business and address2, respectively) are optional. Is there a way to set up the merge fields in the template so that, if the user puts something into the business field, the document resulting from the merge will have the value of the business field followed by a space, but if the user leaves the field blank, the document resulting from the merge will not have either the field or the space? I can see two possible ways of achieving this: 1. using a stand-alone merge field that prints a space only if the field "business" is not blank; or 2. using a merge field in the template that prints both the value of the field and a space, but only if the field is not blank.

Here's my psuedocode for these two solutions: 1. [onshow.business][onshow;if[business]!=blank;then' ';else''][onshow.address1] 2. [onshow.business AND ' '][onshow.address1]

It seems like this must be possible, and yet I haven't been able to find a way to turn either pseudocode into real, functioning merge fields in my docx. template. I've searched all of the entries on this forum and on the tbs forum, as well as the documentation, but the issue hasn't squarely been raised, and the things I have tried have not worked. Any help would be much appreciated.


Solution

  • This will insert a non-breaking space after the value of business, if it is not '':

    [onshow.business; if [val] != ''; then [val] ]
    

    The issue you may encounter is how Word represents a space... I would suggest starting with inserting a less problematic character to ensure your tag is working correctly (like a ^ or and a maybe), then work on finding the proper character / parameter combination to make a space work.

    When you start looking at that, I'd try \s: http://www.tinybutstrong.com/forum.php?thr=3234 Then I'd look at xml:space="preserve": http://www.tinybutstrong.com/forum.php?thr=3263

    It looks like it shows up on a <w:t> tag like this: <w:t xml:space="preserve"> so you might try something like:

    PHP:

    $f = 'preserve';
    

    TEMPLATE:

    [onshow.business; if [val] != ''; then '[val] ';][onshow.p;att='xml:space']
    

    There is probably a better way to handle the att but this should get you started at least.