Hi, I have one team array and want that team name every where to show team name.It is possible to built a global function which can return team name and I call that function from my view means ctp file.
A:
You can add in your /app/config/bootstrap.php file something like:
Configure::write('teams', array('team1', 'team2'));
Then everywhere you can get that array with:
$teams = Configure::read('teams');
and use it.
Nik
2010-08-10 11:27:32
Is there a reason you're writing it to the configuration object? I usually just define things in the bootstrap file as constants, e.g., define( TEAMS, array(...) );
Travis Leleu
2010-08-10 16:28:28
I don't think it's possible to define array as a constant - Constants may only evaluate to scalar values (warning on the screen). Read the description here http://book.cakephp.org/view/42/The-Configuration-Class and you will see that the cake team encourage to use it instead of variables and constants.
Nik
2010-08-10 16:59:15
A:
There are multiple approaches to this. What I cannot tell from your description is exactly what you are looking for. If it is simply to create an array of items that is accessible in your views, I would put it in app_controller.php
var $teams = array('team1', 'team2', 'team3');
beforeFilter() {
$this->set('teams', $this->teams);
}
Then in your view, you can access the array by the variable: $teams
If you only want to call teams on certain views, it may not be a good idea to set this variable for EVERYTHING. You can get around it by setting up a function in app controller.
function get_teams_array() {
$teams = array('team1', 'team2', 'team3');
return $teams;
}
Then put together an element that will call this function: views/elements/team.ctp
<?php
$teams = $this->requestAction(
array('controller' => 'app', 'action' => 'teams'),
array('return')
);
/** process team array here as if it were in the view **/
?>
Then you can just call the element from your view:
<?php echo $this->element('team'); ?>
cdburgess
2010-08-10 19:01:56