{"record":{"id":"282aee605a810e4b","repo":"PHPOffice/PHPWord","slug":"cannot-add-method-in-this-container","errorCode":null,"errorMessage":"Cannot add {$method} in {$this->container}.","messagePattern":"Cannot add (.+?) in (.+?)\\.","errorType":"exception","errorClass":"BadMethodCallException","httpStatus":null,"severity":"error","filePath":"src/PhpWord/Element/AbstractContainer.php","lineNumber":275,"sourceCode":"            'PreserveText' => ['Section', 'Header', 'Footer', 'Cell'],\n            'Title' => ['Section', 'Cell', 'Header'],\n            'TOC' => ['Section'],\n            'PageBreak' => ['Section'],\n            'Chart' => ['Section', 'Cell'],\n        ];\n\n        // Special condition, e.g. preservetext can only exists in cell when\n        // the cell is located in header or footer\n        $validSubcontainers = [\n            'PreserveText' => [['Cell'], ['Header', 'Footer', 'Section']],\n            'Footnote' => [['Cell', 'TextRun'], ['Section']],\n            'Endnote' => [['Cell', 'TextRun'], ['Section']],\n        ];\n\n        // Check if a method is valid for current container\n        if (isset($validContainers[$method])) {\n            if (!in_array($this->container, $validContainers[$method])) {\n                throw new BadMethodCallException(\"Cannot add {$method} in {$this->container}.\");\n            }\n        }\n\n        // Check if a method is valid for current container, located in other container\n        if (isset($validSubcontainers[$method])) {\n            $rules = $validSubcontainers[$method];\n            $containers = $rules[0];\n            $allowedDocParts = $rules[1];\n            foreach ($containers as $container) {\n                if ($this->container == $container && !in_array($this->getDocPart(), $allowedDocParts)) {\n                    throw new BadMethodCallException(\"Cannot add {$method} in {$this->container}.\");\n                }\n            }\n        }\n\n        return true;\n    }\n}","sourceCodeStart":257,"sourceCodeEnd":293,"githubUrl":"https://github.com/PHPOffice/PHPWord/blob/aef95c04151b5633cc505f672ddd6a71da900ee1/src/PhpWord/Element/AbstractContainer.php#L257-L293","documentation":"AbstractContainer::checkValidity() rejects adding an element type that is not valid for the current container at all. The $validContainers map defines which containers (Section, Cell, TextRun, Header, Footer, etc.) may hold each element type; adding e.g. a TextRun directly to a Cell that only accepts certain children throws this BadMethodCallException naming the method and container.","triggerScenarios":"Calling e.g. $cell->addTextRun(...), $textrun->addFootnote(...), or $section->addComment-style calls where the element method exists on the container class but is not listed for that container type in $validContainers. Triggered via any addElement() dispatch like addText, addImage, addTextRun on the wrong container.","commonSituations":"Trying to nest elements in ways OOXML does not allow (e.g. a Table inside a TextRun, a Footer inside a Cell); copying code from one container context to another; upgrading PhpWord where containment rules were tightened.","solutions":["Move the add* call to the correct container (e.g. add TextRun to a Section, not a Cell if disallowed)","Check the $validContainers rules in AbstractContainer.php for the element type you are adding","Use TextRun as an intermediate container where direct addition is not allowed","Restructure the document so the element belongs to an allowed parent"],"exampleFix":"// before\n$cell->addTextRun(); // not allowed for Cell\n// after\n$textrun = $cell->addText();\n$textrun->addText('nested content');","handlingStrategy":"try-catch","validationCode":"$validMap = ['TextRun' => ['Section', 'Cell', 'TextRun', 'Header', 'Footer', 'Footnote']];\n$containerType = (new ReflectionClass($container))->getShortName();\nif (isset($validMap['TextRun']) && !in_array($containerType, $validMap['TextRun'], true)) {\n    // choose a different parent before adding\n}","typeGuard":null,"tryCatchPattern":"use PhpOffice\\PhpWord\\Element\\AbstractContainer;\ntry {\n    $container->addTextRun();\n} catch (\\BadMethodCallException $e) {\n    // fall back to adding to the parent Section\n    $section->addTextRun();\n}","preventionTips":["Read the $validContainers array in AbstractContainer.php before nesting elements","Model document structure per OOXML rules: TextRun in Section/Cell, Table in Section/Cell only","Isolate document building in a builder class so container misuse is caught in one place","Add smoke tests that build your document template end-to-end"],"tags":["php","phpword","bad-method-call","container"],"backgroundTag":"unsupported-operation","analyzedSha":"aef95c04151b5633cc505f672ddd6a71da900ee1","analyzedAt":"2026-09-14T10:53:58.933Z","contentChangedAt":"2026-09-14T10:53:58.933Z","schemaVersion":2},"datasetVersion":"2026-09-16T09:17:16.951Z"}