How should I use requestAction in the view with CakePHP 3.x

南楼画角 提交于 2019-12-23 05:11:34

问题


My code:

// View/Activities/index.ctp
...
<div>
    <?php echo $this->requestAction('/Activities/ajax_list/'.$categoryId,['return']);?>
</div>
...

//View/Activitest/ajax_list.ctp
....
<?php echo $this -> Html -> image("/img/add1.jpg"); ?>
...
<?php echo $this->Html->link('add_project', array('controller'=>'projects', 'action'=>'add', $categoryId)); ?>
....

I want to include the view 'ajax_list' into the 'index',and it has been displayed but the url of image and link was wrong.

Then I debug the Cake/Routing/RequestActionTrait.php , "requestAction" function I find "$request = new Request($params);" the $request->base , $request->webroot are null.

Could some one tell me how should I fix it?


回答1:


The $base/$webroot properties not being set in the new request might be considered a bug, or maybe the docs are just missing a proper example solution, I can't tell for sure, you might want to report this over at GitHub and see what the devs say.

Use view cells instead of requestAction()!

Whenever applicable you're better off using view cells instead of requesting actions, as they avoid all the overhead that comes with dispatching a new request.

See Cookbook > Views > View Cells

No models involved? Use elements!

In case no models are involed, and all you are doing is generating HTML, then you could simply use elements.

See Cookbook > Views > Elements

Fixing requestAction()

A possible workaround would be to use a dispatcher filter that fills the empty $base/$webroot properties with the necessary values, something like

src/Routing/Filter/RequestFilterFix.php

namespace App\Routing\Filter;

use Cake\Event\Event;
use Cake\Routing\DispatcherFilter;

class RequestFixFilter extends DispatcherFilter
{
    public function beforeDispatch(Event $event)
    {
        $request = $event->data['request'];
        /* @var $request \Cake\Network\Request */

        if ($request->param('requested')) {
            $request->base = '/pro';
            $request->webroot = '/pro/';
            $request->here = $request->base . $request->here;
        }
    }
}

config/bootstrap.php

// ...

// Load the filter before any other filters.
// Must at least be loaded before the `Routing` filter.
DispatcherFactory::add('RequestFix');

DispatcherFactory::add('Asset');
DispatcherFactory::add('Routing');
DispatcherFactory::add('ControllerFactory');
// ...

See also Cookbook > Routing > Dispatcher Filters > Building a Filter



来源:https://stackoverflow.com/questions/30318793/how-should-i-use-requestaction-in-the-view-with-cakephp-3-x

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