cakephp / docs

CakePHP CookBook
http://book.cakephp.org
Other
679 stars 2.58k forks source link

JSON, XML view examples from docs: “Missing Template” #7932

Closed mehov closed 1 month ago

mehov commented 1 month ago

I just followed https://book.cakephp.org/5/en/views/json-and-xml-views.html#creating-xml-views and I got the missing template error.

Searched online and found this thread https://discourse.cakephp.org/t/json-view-example-from-docs-gives-missing-template-error/10536

Adding $this->viewBuilder()->setClassName("Json"); solved it for the OP, and doing the same but with Xml solved it for me.

Maybe the docs should be updated to reflect that?

What I have now and what works for me is:

    $this->viewBuilder()
        ->setClassName("Xml")
        ->setOption('rootNode', 'urlset')
        ->setOption('serialize', ['@xmlns', 'url']);
    $this->set([
        // Define an attribute on the root node.
        '@xmlns' => 'http://www.sitemaps.org/schemas/sitemap/0.9',
        'url' => $urls,
    ]);
dereuromark commented 1 month ago

Are you using extension based routing? That would usually set the class names. So if you call it as /url/action.json or /url/action.xml it would then negotiate the type and therefore class as per docs

Note the top of the doc, that states the necessary part

public function viewClasses(): array
{
    return [JsonView::class, XmlView::class];
}

for this to work