CakePHP pages_controller always uses default layout - cakephp

I have a static page that I want to serve so I made a .ctp in the /views/pages/ directory. The problem is that it's using the default layout which I do not want to use. I tried making my own pages_controller and passing the $layout var but that does not work. There has to be a way to tell a /pages/ to use another layout.ctp. No?

I was having a similar issue, thought i'd report my solution in case others are facing the same thing.
I wasn't using pages, but had a controller "members":
<?php
class MembersController extends AppController {
var $name = 'Members';
var $helpers = array('Html','Javascript','Form','Time');
var $uses = array();
function index() {
// Works, will load the ajax.ctp layout
// http://localhost/members/index
$this->layout = 'ajax';
}
function signup() {
// Does not work, loads the default.ctp layout
//http://localhost/members/signup
$this->layout = 'ajax';
}
}
?>
function index() was properly loading the ajax layout, but signup() kept loading default. Turns out the mistake was I did not have a view/signup.ctp. Once I added that it loaded the proper layout. Was an absentminded mistake but left me barking up the wrong tree because signs were pointing towards a layout issue rather than a view issue.

few things to check
make a custom pages_controller.php
define variable $layout and set it to the layout you want.
make sure the layout exists in
views/layout/

goes to the following link "lib\Cake\Controller" open CakeErrorController.php add your layout .
public function __construct($request = null, $response = null) {
parent::__construct($request, $response);
$this->constructClasses();
$this->Components->trigger('initialize', array(&$this));
$this->_set(array('cacheAction' => false, 'viewPath' => 'Errors'));
$this->layout='student';
}

I had this same issue and all errors were misleading.
What my problem ended up being is that I was trying to use a controller that didn't have a backing table/model so I was trying to reuse some other name in the controller's $name member variable because otherwise it would say that model didn't exist.
Long story short make sure that your controller name has a backing model object with the same naming convention.

Related

use unassociate model in another model with condition in cakephp [duplicate]

Can I use another Model inside one model?
Eg.
<?php
class Form extends AppModel
{
var $name='Form';
var $helpers=array('Html','Ajax','Javascript','Form');
var $components = array( 'RequestHandler','Email');
function saveFormName($data)
{
$this->data['Form']['formname']=$data['Form']['formname'];
$this->saveField('name',$this->data['Form']['formname']);
}
function saveFieldname($data)
{
$this->data['Attribute']['fieldname']=$data['Attribute']['fieldname'];
}
}
?>
Old thread but I'm going to chime in because I believe the answers to be incomplete and lacking in "why". CakePHP has three ways to load models. Though only two methods work outside of a Controller, I'll mention all three. I'm not sure about version availability but this is core stuff so I believe they'll work.
App::import() only finds and require()s the file and you'll need to instantiate the class to use it. You can tell import() the type of class, the name and file path details.
ClassRegistry::init() loads the file, adds the instance to the object map and returns the instance. This is the better way to load something because it sets up "Cake" things as would happen if you loaded the class through normal means. You can also set an alias for the class name which I've found useful.
Controller::loadModel() uses ClassRegistry::init() as well as adds the Model as a property of the controller. It also allows $persistModel for model caching on future requests. This only works in a Controller and, if that's your situation, I'd use this method before the others.
You can create instances of other models from within any model/controller using one of these two methods.
If you're using Cake 1.2:
App::import('model','Attribute');
$attr = new Attribute();
$attr->save($dataYouWantToSavetoAttribute);
If you're using Cake 1.1:
loadModel('Attribute');
$attr = new Attribute();
$attr->save($dataYouWantToSavetoAttribute);
An obvious solution everyone missed is to create an association between two models, if appropriate. You can use it to be able to reference one model from inside another.
class Creation extends AppModel {
public $belongsTo = array(
'Inventor' => array(
'className' => 'Inventor',
'foreignKey' => 'inventor_id',
)
);
public function whoIsMyMaker() {
$this->Inventor->id = $this->field('inventor_id');
return $this->Inventor->field('name');
}
}
In CakePHP 1.2, it's better to use:
ClassRegistry::init('Attribute')->save($data);
This will do simply
<?php
class Form extends AppModel
{
//...
$another_model = ClassRegistry::init('AnotherModel');
//...
}
?>
In CakePHP 3 we may use TableRegistry::get(modelName)
use Cake\ORM\TableRegistry;
$itemsOb = TableRegistry::get('Items');
$items = $itemsOb->find("all");
debug($items);
If you want to use Model_B inside Model_A, add this line at the beginning of Model_A file:
App::uses('Model_B_ClassName', 'Model');
and then you will be able to use it inside Model_A. For example:
$Model_B = new Model_B_ClassName();
$result = $Model_B->findById($some_id);
var $uses = array('ModeloneName','ModeltwoName');
By using $uses property, you can use multiple models in controller instead of using loadModel('Model Name').
App::import('model','Attribute');
is way to use one model into other model. Best way will be to used association.

CakePHP doesn't load model

I'm new to cakePhp development. I've stuck on following problem:
I've made few models, controllers and views - it works great. The problem is that after production, I have to made new table(Transactionaltemp table and corresponding model and controller ) in the db that logically is "connected" to other tables, but technically does not needs to - for ex. it holds temporary info on user_id, time, ip and similar. So, other tables doesn't need to be directly connected to that.
The problem is when I try (in some other controller than transactionaltemps_controller):
$this->loadModel('Transactionaltemp');
I get error - the model is not found (it is true because the model is missing in the cache). Interesting enough transactionaltempls_controller is in the cache (in the cake_controllers_list file).
I tried following stuff to resolve the problem:
clear cache
disable cache
tried using uses={..} code in the controller that I would like to use mymodels_controller
tried using init('Transactionaltemp')
with no success. Here is corresponding code:
The model:
<?php
class Transactionaltemp extends AppModel
{
var $name = 'Transactionaltemp';
function beforeSave() {
return true;
}
}
?>
The controller:
<?php
class TransactionaltempsController extends AppController
{
var $name = 'Transactionaltemps';
var $scaffold;
}
?>
I'll very grateful to any help!!!
App:Import('Model','Transactionaltemp');
$this->Transactionaltemp= new Transactionaltemp;
I hope this may work
If you are connecting to a table name with different name than your model, you must specify the table name in it:
<?php
class Transactionaltemp extends AppModel
{
var $uses = 'Transactional';
var $name = 'Transactionaltemp';
function beforeSave() {
return true;
}
}
Try
App::Import('Model', 'YourModelName');
in your controller (or where you want).

How to add helper or component on-the-fly with the controller action method

i don't want to add it as below cause i needed them only once in certain action method
(so do not useless load the memory)
class UsersController extends AppController {
var $name = 'Users';
var $helpers = array('Html', 'Session');
var $components = array('Session', 'Email');
class UsersController extends AppController {
public function method_name() {
$this->helpers[] = 'MyHelper'
}
}
More on this in the documentation.
Hope that helps.
You can load helpers using
$this->helpers[] = 'MyHelper';
as Rob mentioned above, but this won't work for controllers because they have their initialize and startup methods that need to be called in order for them to work.
I've come across a bit of code on the web for loading components inside of a controller action: ComponentLoaderComponent
Yes, it is a component but it isn't very big so it shouldn't be a problem to include it in your controllers.
Either that or you can just study it to see how the component loading works and then write your own controller action to do the same.
I use a component for adding helpers and components on the fly:
$this->Common->addHelper('Tools.Datetime');
$this->Common->addHelper(array('Text', 'Number', ...));
$this->Common->addComponent('RequestHandler');
$this->Common->addLib(array('MarkupLib'=>array('type'=>'php'), ...));
etc
The complete code to this can be seen in the cakephp enhancement ticket I just opened:
http://cakephp.lighthouseapp.com/projects/42648-cakephp/tickets/1277
Or with php markup:
http://www.dereuromark.de/2010/11/10/loading-classes-on-the-fly/
It also fixes some minor problems with the solution posted by mtnorthrop.
Plugins as well as passed options are now possible. Have fun.

CakePHP Time Helper Problem

I think I might be making a mistake here.
I am getting the following error when trying to use a simple function in the time helper in my controller. I don't get an error when using the same function call in the view.
Below is the error from the controller.
Followed by the controller code that is failing.
Followed by the view code that is working.
Any help is appreciated!
Error:
Notice (8): Undefined variable: time [APP/controllers/temp_users_controller.php, line 25]
Code $checkTime = $time->gmt();
Fatal error: Call to a member function gmt() on a non-object in /var/www/studydeck/app/controllers/temp_users_controller.php on line 25
Controller:
class TempUsersController extends AppController {
var $name = 'TempUsers';
var $scaffold;
var $components = array('Auth');
var $helpers = array('Time');
function beforeFilter() {
//list of actions that do not need authentication
$this->Auth->allow('userCleanUp');
}
//this function will delete TempUser accounts which have not been activated
function userCleanUp() {
$checkTime = $time->gmt();
$this->set('checkTime',$checkTime);
}
}
View:
echo $time->gmt();
Update:
I tried $time = new TimeHelper();
I received the error
Fatal error: Class 'TimeHelper' not found in /var/www/studydeck/app/controllers/temp_users_controller.php on line 23
I do have var $helpers = array('Time')
Also not that echo $time->gmt(); works in the view with out instantiating time anywhere.
Helpers are thought to be used in views, not in controllers, hence the error. If you really have to use the helper in your controller, you have to instantiate it yourself:
$time = new TimeHelper();
You generally don't use a helper from the controller.
The array you assign in the controller is used to load and instantiate the helper classes before the view is parsed and rendered.
To use the helper in your controller you need to make sure the file is loaded ( included ) correctly and that you have an instance of it to work with. You can also use many of them statically from within a controller, expecially those helpers that don't need access to the controller object.
Cake provides you with a core function that you can use to safely include the files. It will even handle where the file gets loaded from automagically so you don't need to deal with paths.
An example to get you started.
<?php
class TempUsersController extends AppController
{
public $name = "TempUsers";
public function userCleanUp( ){
// include the time helper
App::import( 'Helper', 'Time' );
$time = new TimeHelper;
$checkTime = $time->gmt( );
$this->set( 'checkTime',$checkTime );
}
}
?>
On this line:
$checkTime = $time->gmt();
The $time variable is not defined and is automatically set to null. The error states that it is not an object (which is correct). Did you initialize it properly? I cannot see any initialisation done for the $time variable.

Can I use one model inside of a different model in CakePHP?

Can I use another Model inside one model?
Eg.
<?php
class Form extends AppModel
{
var $name='Form';
var $helpers=array('Html','Ajax','Javascript','Form');
var $components = array( 'RequestHandler','Email');
function saveFormName($data)
{
$this->data['Form']['formname']=$data['Form']['formname'];
$this->saveField('name',$this->data['Form']['formname']);
}
function saveFieldname($data)
{
$this->data['Attribute']['fieldname']=$data['Attribute']['fieldname'];
}
}
?>
Old thread but I'm going to chime in because I believe the answers to be incomplete and lacking in "why". CakePHP has three ways to load models. Though only two methods work outside of a Controller, I'll mention all three. I'm not sure about version availability but this is core stuff so I believe they'll work.
App::import() only finds and require()s the file and you'll need to instantiate the class to use it. You can tell import() the type of class, the name and file path details.
ClassRegistry::init() loads the file, adds the instance to the object map and returns the instance. This is the better way to load something because it sets up "Cake" things as would happen if you loaded the class through normal means. You can also set an alias for the class name which I've found useful.
Controller::loadModel() uses ClassRegistry::init() as well as adds the Model as a property of the controller. It also allows $persistModel for model caching on future requests. This only works in a Controller and, if that's your situation, I'd use this method before the others.
You can create instances of other models from within any model/controller using one of these two methods.
If you're using Cake 1.2:
App::import('model','Attribute');
$attr = new Attribute();
$attr->save($dataYouWantToSavetoAttribute);
If you're using Cake 1.1:
loadModel('Attribute');
$attr = new Attribute();
$attr->save($dataYouWantToSavetoAttribute);
An obvious solution everyone missed is to create an association between two models, if appropriate. You can use it to be able to reference one model from inside another.
class Creation extends AppModel {
public $belongsTo = array(
'Inventor' => array(
'className' => 'Inventor',
'foreignKey' => 'inventor_id',
)
);
public function whoIsMyMaker() {
$this->Inventor->id = $this->field('inventor_id');
return $this->Inventor->field('name');
}
}
In CakePHP 1.2, it's better to use:
ClassRegistry::init('Attribute')->save($data);
This will do simply
<?php
class Form extends AppModel
{
//...
$another_model = ClassRegistry::init('AnotherModel');
//...
}
?>
In CakePHP 3 we may use TableRegistry::get(modelName)
use Cake\ORM\TableRegistry;
$itemsOb = TableRegistry::get('Items');
$items = $itemsOb->find("all");
debug($items);
If you want to use Model_B inside Model_A, add this line at the beginning of Model_A file:
App::uses('Model_B_ClassName', 'Model');
and then you will be able to use it inside Model_A. For example:
$Model_B = new Model_B_ClassName();
$result = $Model_B->findById($some_id);
var $uses = array('ModeloneName','ModeltwoName');
By using $uses property, you can use multiple models in controller instead of using loadModel('Model Name').
App::import('model','Attribute');
is way to use one model into other model. Best way will be to used association.

Resources