OctoberCMS. Variable disappears after ajax request

一曲冷凌霜 提交于 2019-12-12 04:59:46

问题


My component template code:

default.htm:

<div id="filter_variations" style="//display: none;">
{{ form_ajax('onAjaxVariations') }}
    <input type="text" id="var_id" name="Filter[id]" value="">
    <input type="submit">
{{ form_close() }}
</div>
<div id="partial_service">
    {% partial __SELF__ ~ '::service' %}
</div>

in partial i try display "service" variable, and dynamic "variations" variable:

<h1>{{service.name}}</h1>
<span>Selected variation: variation[0].name</span>

and it works

Component: but if I make a ajax request, variable "service" not display in partial. Why is this happening? And how to avoid this?


回答1:


Ajax handler is working differently from page life cycle in October.

so when you call page it will initialize page with all the data and all components with its life-cycle methods.

in-short all data is not initialized in ajax request

you want service object inside partial so you are using

$this->page['service']

but its not been initialized so it will not available in ajax,

to make it available in page code section you need to use onInit method.

function onInit() {
    $this['service'] = // your logic to get service and assign it;
}

now this service will available inside your ajax handler

public function onAjaxVariations() { // $this->page['service'] will be available and can be passed to view now; }

on normal page refresh it works because all page-cycle function executes, all component life-cycle functions are executed so $this->page['service'] will be available here.

all component life-cycle functions means your onRender function => which calls prepareVars => which assigns $this->page['service'] (this things are not executed in ajax call)

{ update Preferred solution }

If your code is dependent on page code (page lifeCycle)

in-short code is written inside page markup or in code section and you want to execute it first

inside your ajax handler method you can use this

$this->controller->pageCycle();

it will automatically execute all the page code and your all variable will be available now.

public function onAjaxVariations() {
    $this->controller->pageCycle();
    // $this->page['service'] will be available
} 


来源:https://stackoverflow.com/questions/48199529/octobercms-variable-disappears-after-ajax-request

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