Cakephp 2.9 passing a variable from Controller to Layouts View - cakephp

The question i am asking is very similar and already asked question.But It is working for me.
ViewReportsController.php
class ViewReportsController extends AppController {
public function index() {
$count_table = 10;//sample variable that is available in view
$this->set('count_tablen',$count_table);
}
}
APP/View/Layouts/default.ctp
pr($count_tablen);
Now i am getting the error says- Undefined variable: count_tablen [APP/View/Layouts/default.ctp, line 228]

You are using a variable in your main layout template which is likely used by multiple controller actions. Therefore, the code example you've provided would only work on /view_reports/index. If you want to set variables to be used in the layout templates you need to do this in the beforeRender callback of AppController so that it can be used everywhere:-
public function beforeRender() {
parent::beforeRender();
$count_table = 10;
$this->set('count_tablen', $count_table);
}
If you use multiple layout templates you can check which template will be used in beforeRender before setting the variable:-
public function beforeRender() {
parent::beforeRender();
if ($this->layout === 'default') {
$count_table = 10;
$this->set('count_tablen', $count_table);
}
}

Related

Call Specific Function From Behavior CakePHP 2.10.12 Not Working

Hay. Currently I'm creating a function in Behaviour in CakePHP 2.10.12 as shown below :
<?php
App::uses('CakeTime', 'Utility');
App::uses('CakeNumber', 'Utility');
class ConverterBehavior extends ModelBehavior {
private $timezone;
private $locale;
private $currency;
function hellow() {
return "Hellow from behavior";
}
function initConverter($locale, $timezone, $currency) {
$this->locale = $locale;
$this->timezone = $timezone;
$this->currency = $currency;
setlocale(LC_ALL, $locale);
}
public function getCurrentLocale() {
return $this->locale;
}
function convertCurrency($currencyAmount) {
return CakeNumber::currency($currencyAmount, $this->currency);
}
function convertDate($date) {
return CakeTime::i18nFormat($date, null, false, $this->timezone);
}
}
?>
Then above behavior is used by my model as shown below :
<?php
class Test extends AppModel {
public $actsAs = array('Converter');
}
And then I call the function that I created from behavior in my Controller as shown below :
public function converterModel() {
$this->Test->initConverter('ja_JP', 'Asia/Tokyo', 'JPY');
$temp = $this->Test->convertCurrency(23456789901.123456);
debug($this->Test->hellow());
// $this->set('jpDate', $this->Test->convertDate(new DateTime));
}
The problem is initConverter cannot be initialized. I check the variabel that are inputed from controller and all of those variabel are null (it's weird). But when I call the hellow() (function in behavior), the result is displayed in my view. So is there something missing here ?
Thank you
Note :
This is the error message displayed in my view :
Look at the warning/notice, you are receiving an object where you expect a string/number.
The first argument of an externally invoked behavior method will always be the instance of the model that the behavior is attached to, ie your method signatures should be like:
function initConverter(Model $model, $locale, $timezone, $currency)
function convertCurrency(Model $model, $currencyAmount)
// etc...
See also
Cookbook > Models > Behaviors > Creating Behaviors
Cookbook > Models > Behaviors > Creating behavior methods

How to properly save self reference with ES6 classes?

Honestly, I'm not sure of what is the cause for the behavior: systemjs, babel or my own fault. I'm using class for custom control controller and saving class reference in self variable. Apparently that gets overriden by any subsequent controller instances.
I created a simple repository to demonstrate:
clone, install, run live-server or your preferred server. You will see 2 buttons, each is a custom control. Clicking on a button only affects one control.
https://github.com/alexkolt/selfIsThis
How can I get this working with ES6 class?
I should have posted the code, sorry.
The reason you'd want to save reference to self is for example in callbacks calling this might result in a different reference.
I was trying to do this:
var self;
class Test {
constructor(dependency) {
self = this;
self.dependency = dependency;
}
method() {
self.dependency().then(value => self.property = value);
}
}
Like it was mentioned before the self becomes shared when declared outside of the module. I didn't realize that would happen as files would be wrapped in a closure. Joe Clay answer is correct, but to do what I was trying to do self needs to be declared in every method that needs it.
class Test {
constructor(dependency) {
this.dependency = dependency;
}
method() {
var self = this;
this.dependency().then(value => self.property = value);
}
}
You're not really using ES6 classes right. You don't need to save a reference to this - just access it directly in class methods. The way you have it at the minute, all your instances of CustomControlController are sharing a single self variable.
class CustomControlController {
constructor() {
this.value = 0;
}
click() {
var newValue = this.value * 2;
this.value = newValue;
}
}
export default CustomControlController;

Bind static variable (out of scope) to html in Angular / typescript

I created a little test typescript/angularjs website.
I have this module with a static variable which I want to bind to the html-document so that I can see the current logged-in user.
module mytest.constants {
export class CurrentSession {
public static CURRENT_USER: string = "Tobi";
}
}
the problem is:
the current scope is a controller which is separated from my CurrentSession-class.
I would like to do something like
<div class="label" style="color:green">
Logged in as: {{mytest.constants.CurrentSession.CURRENT_USER}}
</div>
Another way I could do is to add a class-member to the controller and set it in constructor like:
this.CurrentUSer = mytest.constants.CurrentSession.CURRENT_USER
but I would prefer to bind the static-variable directly to the html-file.
is this possible?
You can't bind static properties like this, Angular just doesn't check those in its digest cycle. You can however create a scope/this reference to the class itself. Something like this:
module mytest.constants {
export class CurrentSession {
public static CURRENT_USER: string = "Tobi";
CurrentSession = CurrentSession;
}
}
So basically it will create own property like this.CurrentSession = CurrentSession.
Then in template (assuming you are using controllerAs syntax with session refer to controller instance) you would be able to bind CURRENT_USER as
<div>{{session.CurrentSession.CURRENT_USER}}</div>
thank you dfsq for your quick answer.
I finally found another solution.
I first set a variable called "CurrentSession" in my app.ts and set the value to a new Instance of my Object
angular.module("app", [])
.constant("CurrentSession", new mytest.constants.CurrentSession())
then I can just inject this Constant in my controller like this:
export class MainCtrl {
public static $inject = ["$state", "$http", "CurrentSession"];
constructor($state, $http, private CurrentSession) {
...
}
the good thing here is, that I can use the "private CurrentSession" which will automatically set the a member-variable "CurrentSession".
The html looks like this:
<button ng-click="main.logOut()">Log out {{main.CurrentSession.CURRENT_USER.Name}}</button>

callback functions for cakephp elements?

This might be a naive question since I am new to cakephp.
I am working on a project where there are many layouts, helpers and elements. Because this is a mutli-language site, I am intercepting the final rendered output to do some language conversion(so each visitor only sees his native language on the site including user input).
I've managed to convert most of the layouts and helpers by adding code in two places: AppController's afterFilter() and AppHeler's afterRender() function. But I can't figure out a centralized way to handle the elements and there are dozens of them.
So here are my questions: do all elements in cakephp have a common ancestor class? If so, does this ancestor class have callback functions like afterRender()?
Many thanks!
I'm not sure such a callback exists specific for 'elements', but looking at the source code, View::element() renders an element using the same _render() method as the View itself, and should trigger beforeRender() and afterRender()
Creating a custom View Class and Custom Callbacks
You may use a custom 'View' class and override the element() method, for example to have your own 'custom' callbacks being triggered in helpers
Something like this;
app/view/app_view.php
class AppViewView extends View {
/**
* custom 'element()' method, triggers custom
* before/aferRenderElement callbacks on all loaded helpers
*/
public function element($name, $params = array(), $loadHelpers = false)
{
$this->_triggerHelpers('beforeRenderElement');
$output = parent::element($name, $params, $loadHelpers);
$this->_triggerHelpers('afterRenderElement');
}
/**
* Names of custom callbacks
*/
protected $_customCallBacks = array(
'beforeRenderElement',
'afterRenderElement',
);
function _triggerHelpers($callback)
{
if (!in_array($callback, $this->_customCallbacks)) {
// it's a standard callback, let the parent class handle it
return parent::_triggerHelpers($callback);
}
if (empty($this->loaded)) {
return false;
}
$helpers = array_keys($this->loaded);
foreach ($helpers as $helperName) {
$helper =& $this->loaded[$helperName];
if (is_object($helper)) {
if (
is_subclass_of($helper, 'Helper')
&& method_exists($helper, $callback)
) {
$helper->{$callback}();
}
}
}
}
}
Then, in your AppController specify the 'view' class to use;
class AppController extends Controller {
public $view = 'AppView';
}

Variables in CakePHP's models: how to acces them from another controller?

What I want to do is the following:
I have a model called "Control":
class Control extends AppModel {
var $name = 'Control';
var $myVariable:
function getMyVariable() {
$this->$myVariable = 'hello';
return ($this->$myVariable);
}
function getMyVariable2() {
$myVariable2 = 'hello';
return ($myVariable2);
}
}
Then, from another controller I do:
class TestsController extends AppController {
var $name = 'Tests';
var $uses = array('Test','Control');
function index() { //whatever }
function doStuff() {
$aux = $this->Control->getMyVariable(); //not working, variable not declared
$aux2 = $this->Control->getMyVariable2(); //works
}
I assumed (probably wrong) that I could declare a variable as a property (or atribute) in a model Class like in any other OO languaje, and access it from other places of the aplication, but I guess it doesn't work like this in CakePHP. Am I missing something? Is there any other way to do this? I mean, to having a variable in a model (which content doesn't come from a table) and acces it from other controllers/views?
$this->$myVariable is the syntax for "variable variables" (or in this case, variable properties). The correct syntax is $this->myVariable. CakePHP does not alter the basics of PHP OOP.
Setting a variable in a getter is pretty weird though, you should not do that.
Also, if you are using getters, you should make the property protected or private, otherwise it's somewhat pointless.

Resources