使用 CakePHP 3 中的列表更改更新相关列表

Update related list with change in list in CakePHP 3

我有两个 tables categoriessubcategories 其中 categories 有许多 subcategories 关系。

我还有一个 table productscategoriessubcategories 有关。

productsadd 方法中,我想 select 列表中的类别,然后是与特定类别关联的子类别 selected.

echo $this->Form->input('category_id', ['options' => $categories, 'empty' => true]);
echo $this->Form->input('subcategory_id', ['options' => $subcategories]);
echo $this->Form->input('product_type_id', ['options' => $productTypes]);
echo $this->Form->input('title');

因为 CakePHP 3 中没有 js 助手。我怎么能用 Ajax.

做到这一点

我是 CakePHP 的新手,也是 Ajax。目前显示列表中的所有 subcategories

我让它像这样工作并且工作正常。

查看文件包含

<?= $this->Form->input('categories', ['options' => $categories, 'empty' => 'Select', 'id' => 'categories']) ?>
<?= $this->Form->input('subcategory_id', ['type' => 'select', 'id' => 'subcategories]) ?>

myAjax.js文件包含

$('#categories').change(function () {
    var dataSet = {category_id: $(this).val()};
    var requestUrl = appBaseUrl+'products/ajax-subcategories';
    $.ajax({
        type: "POST",
        url: requestUrl,
        data: dataSet,
        success: function(result) {
            $('#subcategories').html(result);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log(textStatus, errorThrown);
        }
    });
});

ajaxSubcategories 内的操作 ProductsController.php

public function ajaxSubcategories()
{
    $this->autoRender = false;
    $this->loadModel('Subcategories');
    $category_id = $this->request->data['category_id'];

    $subcategories = $this->Subcategories->find()
        ->where(['category_id' => $category_id, 'deleted' => false, 'status' => 0]);

    $data = '';
    foreach($subcategories as $subcategory) {
        $data .= '<option value="'.$subcategory->id.'">'.$subcategory->title.'</option>';
    }
    echo $data;
}

希望这可能对某人有所帮助。