Calling function in view of cakephp

喜欢而已 提交于 2019-12-10 10:38:10

问题


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.


回答1:


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



回答2:


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



回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/3446851/calling-function-in-view-of-cakephp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!