0

In my PhotoalbumsController I am trying to load a different layout when the action imgToAlbum is called.

<?php
namespace App\Controller\Admin;

use App\Controller\AppController;
use Cake\ORM\TableRegistry;
use Cake\Http\ServerRequest;
use Cake\Event\Event;

class PhotoalbumsController extends AppController 
{
    public function initialize()
    {
        parent::initialize();
    }

    ...

    public function imgToAlbum()
    {
        ...        
        $this->viewBuilder()->setLayout('ajax');
        $content = 'test';
        $this->set(compact($content));
    }

I am getting this error:

Error: The view for PhotoalbumsController::imgToAlbum() was not found.

Confirm you have created the file: "Admin/Photoalbums/img_to_album.ctp" in one of the following paths

I've also tried $this->viewBuilder()->setTemplate('ajax'); and $this->viewBuilder()->template('ajax');. But these don't work either.

I use the same trick in my AppController for my backend, ie, this works:

public function beforeRender(Event $event) 
{
    parent::beforeRender($event);
    if($this->request->getParam('prefix') and $this->request->getParam('prefix') == 'admin') {
        $this->viewBuilder()->setLayout('admin');
    }
}

What am I missing here.

tereško
  • 58,060
  • 25
  • 98
  • 150
GreyRoofPigeon
  • 17,833
  • 4
  • 36
  • 59
  • Maybe there's code running after the action and before the "before render" stage that changes the layout/template, for example the request handler component!? – ndm Apr 12 '18 at 07:44
  • Error is clear. Did you create the file: "Admin/Photoalbums/img_to_album.ctp"? – danny3b Apr 12 '18 at 08:41
  • @danny3b, you are right, the error is clear. But I should be able to load the ajax.ctp file inside `src/Template/Layout`. While I want to use this file on other controllers too. And it is madness to create a separate file for every controller. – GreyRoofPigeon Apr 12 '18 at 09:09
  • @ndm, is there a way to check that? – GreyRoofPigeon Apr 12 '18 at 09:10
  • You could add breakpoints in the view builder. However, as @danny3b pointed out, the error is about a missing (action) template, not about a missing layout, so you may want to rephrase your question, and add information about what filepath exactly you expect to be loaded. – ndm Apr 12 '18 at 09:19
  • 1
    I don't know what exactly you would like to achieve. Do you need 'ajax' template for ajax calls only? In that scenario the view shouldn't be renderer at all, by setting `$this->autoRender = false;` – danny3b Apr 12 '18 at 09:41
  • @danny3b, thanks, disabling the autorender works like a charm. Add is as answer please. – GreyRoofPigeon Apr 12 '18 at 10:22

1 Answers1

0

This should do a trick:

$this->autoRender = false;
danny3b
  • 313
  • 5
  • 17