Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "deleteBlocks" not working in phpWord?

Tags:

block

phpword

I´m trying to use blocks in my Word document but I´m having some problems. First of all, when I declare a block in my document, if I don´t use the function "cloneBlock", the result appears like this:

${sec}
example
${/sec}

Maybe I must use that function to appear properly. But my main problem is that "deleteBlock" is not working. If I don´t clone the block, the generated docx is corrupted. But if I clone the block, the function "deleteBlock" doesn´t delete the block and it appear the information that is inside that block in my final docx file.

This is my code:

//Word
// Creating the new document...
$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('../example.docx');
//set value
//$templateProcessor->setValue('title', 'Example');

//Triplicate block
$templateProcessor->cloneBlock('firstblock', 3, true, true);
$templateProcessor->setValue('firstname#1', 'John');
$templateProcessor->setValue('lastname#1', 'Doe');
$templateProcessor->setValue('firstname#2', 'John');
$templateProcessor->setValue('lastname#2', 'Doe');
$templateProcessor->setValue('firstname#3', 'John');
$templateProcessor->setValue('lastname#3', 'Doe');

//Delete Block
$templateProcessor->cloneBlock('sec', 1, true, true);
$templateProcessor->deleteBlock('sec');
$templateProcessor->saveAs('example.docx');

Docx template:

${firstblock}
Hello ${firstname} ${lastname}!
${/firstblock}
${sec}
example
${/sec}

UPDATE: Instead of using the function "deleteBlock", I have use the function "cloneBlock" like this and it deletes the block:

//Delete Block
$templateProcessor->cloneBlock('sec', 0, true, true);

So, I have write to clone the block 0 times, so it disappears But I have another problem. I don´t know why, but this only works sometimes

like image 643
d1845412 Avatar asked Sep 05 '25 03:09

d1845412


1 Answers

I'm not sure why user @d1845412 deleted their previous answer, but it actually solved my issue. I overwrote the deleteBlock method with the following code and it seems to work. I prefer this small change over larger changes to the replaceBlock method.

/**
 * Override this method since deleteBlock doesn't seem to work.
 * @param string $blockname
 */
public function deleteBlock($blockname)
{
    $this->cloneBlock($blockname, 0, true, true);
}
like image 74
Code Commander Avatar answered Sep 07 '25 23:09

Code Commander