开发者

Calling function in view of cakephp

开发者 https://www.devze.com 2023-01-10 18:07 出处:网络
I have one team array an开发者_StackOverflowd 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 vi

I have one team array an开发者_StackOverflowd 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.


please try this for west:

<?php
// controller name like app,users
// action name like getdata should be in controller
// and you can send parameter also
$output = $this->requestAction('controllerName/actionName/'.$parameter);
?>


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'); ?>


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.


In CakePHP 3.*, you can use Helpers.

https://book.cakephp.org/3.0/en/views/helpers.html#creating-helpers

1 - Create your helper inside src/View/Helper:

/* src/View/Helper/TeamHelper.php */
namespace App\View\Helper;

use Cake\View\Helper;

class TeamHelper extends Helper
{
    public function getName($id)
    {
        // Logic to return the name of them based on $id
    }
}

2 - Once you’ve created your helper, you can load it in your views.
Add the call $this->loadHelper('Team'); inside /src/View/AppView.php:

/* src/View/AppView.php */
class AppView extends View
{
    public function initialize()
    {
        parent::initialize();
        $this->loadHelper('Team');
    }
}

3 - Once your helper has been loaded, you can use it in your views:

<?= $this->Team->getName($id) ?>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号