Forum


Replies: 2   Views: 472
How to get a list of inputfields, similar to gettemplatevariables()?
Topic closed:
Please note this is an old forum thread. Information in this post may be out-to-date and/or erroneous.
Every phpdocx version includes new features and improvements. Previously unsupported features may have been added to newer releases, or past issues may have been corrected.
We encourage you to download the current phpdocx version and check the Documentation available.

Posted by kronholm  · 01-09-2022 - 10:41

You can easily get a list of template variables with the getTemplateVariables() method.

But is there a similar way to get a list of InputFields in the document?

As far as I can tell, it's possible to modify input fields via modifyInputFields($data) method, but there is no way to actually get a list of available input fields.

Edit: Same question for MergeFields.

Posted by admin  · 01-09-2022 - 11:05

Hello,

There's no direct method to get all input fields or merge fields. These are complex elements that contain a lot of information. For example, in the case of structure document tags (w:sdt): alias, tag, text contents, styles, id...

The best approach for this specific case is using getDOCXPathQueryInfo. For example, to return the tag value of all w:sdt elements:

$docx = new CreateDocxFromTemplate('template.docx');

// query w:sdt/w:sdtPr elements
$referenceNode = array(
        'customQuery' => '//w:sdt//w:sdtPr'
);
$foundNodes = $docx->getDOCXPathQueryInfo($referenceNode);

if (count($foundNodes['elements']) > 0) {
        $inputFieldNodes = array();
        // iterate the elements to get the needed information
        foreach ($foundNodes['elements'] as $nodes) {
                $tagNodes = $nodes->getElementsByTagName('tag');
                if ($tagNodes->length > 0 && $tagNodes->item(0)->hasAttribute('w:val')) {
                        $inputFieldNodes[] = $tagNodes->item(0)->getAttribute('w:val');
                }
        }

        print_r($inputFieldNodes);
}

And a very similar approach can be used for merge fields.

Regards.

Posted by kronholm  · 01-09-2022 - 11:23

Works like a charm! Thanks!