CakePHP Js Helper - 动态更新3个下拉菜单

时间:2015-02-11 14:21:36

标签: ajax cakephp drop-down-menu

我正在使用CakePHP 2.6.1

我有一个cakephp表单来处理这3个下拉菜单的访问: location-> facility-> department

我希望它们是动态填充的,所以我遵循了本教程http://marnienickelson.com/2014/10/11/dynamic-dropdowns-with-cakephp-2-x/

除了一个小问题外,它运作良好。如果我更改“位置”,正确填写“设施”下拉菜单,但“部门”菜单保持空白...

My AccessesController.php

public function add() {
    if ($this->request->is('post')) {
        $this->Access->create();
        if ($this->Access->save($this->request->data)) {
            $this->Session->setFlash(__('The access has been saved.'));
            return $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The access could not be saved. Please, try again.'));
        }
    }
    $titles = $this->Access->Title->find('list');
    $locations = $this->Access->Facility->Location->find('list');
    $systems = $this->Access->System->find('list');
    $this->set(compact('titles', 'locations', 'facilities', 'departments', 'systems'));
}

我的get_by_location.ctp(我有一个名为get_by_facility.ctp的相同文件)

<?php foreach ($facilities as $key => $value): ?>
<option value="<?php echo $key; ?>"><?php echo $value; ?></option>
<?php endforeach; ?>

在我的add.ctp结束时

<?php
$this->Js->get('#AccessLocationId')->event('change', 
$this->Js->request(array(
    'controller'=>'facilities',
    'action'=>'getByLocation'
    ), array(
    'update'=>'#AccessFacilityId',
    'async' => true,
    'method' => 'post',
    'dataExpression'=>true,
    'data'=> $this->Js->serializeForm(array(
    'isForm' => true,
    'inline' => true
    ))
    ))
);

$this->Js->get('#AccessFacilityId')->event('change', 
$this->Js->request(array(
    'controller'=>'departments',
    'action'=>'getByFacility'
    ), array(
    'update'=>'#AccessDepartmentId',
    'async' => true,
    'method' => 'post',
    'dataExpression'=>true,
    'data'=> $this->Js->serializeForm(array(
    'isForm' => true,
    'inline' => true
    ))
    ))
);

&GT;

我知道第二个事件“变化”并未被识别,这就是为什么我的第三次下拉保持空白......还有其他事件然后“改变”吗?或者我可以把这两个ajax请求放在一个?

1 个答案:

答案 0 :(得分:0)

这个博客帮助了我很多Euromarks blog

我刚刚更改了我的get_by_location.ctp文件:

    <?php
if (!empty($facilities)) {
    echo '<option value="">' . __('pleaseSelect') . '</option>';
    foreach ($facilities as $k => $v) {
        echo '<option value="' . $k . '">' . h($v) . '</option>';
    }
} else {
    echo '<option value="0">' . __('noOptionAvailable') . '</option>';
}

因此,如果第一个下拉列表被更改,第二个下拉列表将显示&#34;请选择&#34;。