Forum


Replies: 6   Views: 896
Using cloneblock to clone elements
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 admin  · 10-05-2022 - 07:22

Hello,

You can use the cloneBlock method with your document but it will clone the sibling elements between the block placeholders (the table in your document):

$docx = new CreateDocxFromTemplate('sample.docx');
$docx->setTemplateSymbol('${', '}');

$docx->cloneBlock('CONTACT_PERSONS');

$docx->createDocx('output');

If you only want to clone a specific row, then you need to use the cloneWordContent method:

$docx = new CreateDocxFromTemplate('sample.docx');
$docx->setTemplateSymbol('${', '}');

$referenceToBeCloned = array(
    'customQuery' => '//w:tbl/w:tr[contains(., "${contact_person_name}")]',
);
$docx->cloneWordContent($referenceToBeCloned, $referenceToBeCloned);

$docx->createDocx('output');

cloneWordContent uses XPath internally. This sample code gets the row based on a specific content, but any XPath query can be used.

Also please note that to fill a table that contains placeholders, the recommended method is replaceTableVariable (https://www.phpdocx.com/api-documentation/templates/replace-table-variable-Word-document):

$docx = new CreateDocxFromTemplate('sample.docx');
$docx->setTemplateSymbol('${', '}');

$data = array(
    array(
        'contact_person_name' => 'Name A',
        'contact_person_email' => 'email1@email.com',
        'contact_person_mobile' => '000001',
    ),
    array(
        'contact_person_name' => 'Name B',
        'contact_person_email' => 'email2@email.com',
        'contact_person_mobile' => '000002',
    ),
);

$docx->replaceTableVariable($data, array('parseLineBreaks' => true));

$docx->createDocx('output');

If needed you can use replaceTableVariable adding new placeholders instead of values so you can do any other tasks.

Please check and test all previous samples so you can choose the one that best suits your needs.

Regards.