cakephp 3 中动态 drop-down 列表的问题

Problems with dynamic drop-down lists in cakephp 3

朋友们,我有 3 个 tables:产品、类别和子类别。我正在尝试注册产品并通过表单上的两个相关 drop-down 列表(类别和子类别)。也就是说,在选择类别时,子类别会加载到另一个列表中,但即使查阅文档我也遇到了困难!如果有人能指出方法,我将不胜感激!我会总结字段!

这是我的 table:


产品:id,名称,category_id,子category_id

类别:身份证、姓名

子类别:id, name, category_id


我正在这样注册新产品:

 public function add()
    {
        $product = $this->Products->newEntity();
        if ($this->request->is('post')) {
            $product = $this->Products->patchEntity($product, $this->request->getData());
            if ($this->Products->save($product)) {
                $this->Flash->success(__('The produto has been saved.'));
                return $this->redirect('/admin/products/');
            }
            $this->Flash->error(__('The produto could not be saved. Please, try again.'));
        }
        $categories = $this->Products->Categories->find('all')->contain(['Subcategories']);    
        $subcategories = $this->Products->Subcategories->find('list', ['limit' => 200]);
        $this->set(compact('product', 'categories', 'subcategories'));
    }

ProductTable.php

.
.
$this->belongsTo('Categories', [
            'foreignKey' => 'category_id',
            'joinType' => 'INNER',
        ]);
        $this->belongsTo('Subcategories', [
            'foreignKey' => 'subcategory_id',
            'joinType' => 'INNER',
        ]);
.
.

CategoriesTable.php

.
$this->hasMany('Product', [
      'foreignKey' => 'category_id',
]);
.

SubcategoriesTable.php

.
 $this->belongsTo('Categories', [
            'foreignKey' => 'category_id',
            'joinType' => 'INNER',
]);
$this->hasMany('Product', [
            'foreignKey' => 'subcategory_id',
]);
.

产品 => add.ctp

<php
$categories_list = [];
$subcategories_list = [];

foreach($categories as $category){

   $categories_list[$category->id] = $category->name; 

   foreach($category->subcategories as $subcategory){
     $subcategories_list[$category->id][$subcategory->id] = $subcategory->name;
   }
}

?>


<div class="produtos form large-9 medium-8 columns content">
    <?= $this->Form->create($product, ['class' => 'ajax_page']) ?>
    <fieldset>
        <legend><?= __('Add Produto') ?></legend>
        <?php

          echo $this->Form->select('category_id', ['options'=>$categories_list,'id'=>'category']);

         echo $this->Form->select('subcategory_id', ['options'=>[], 'id'=>'subcategory']);
?>

  </fieldset>
    <?= $this->Form->button(__('Submit')) ?>
    <?= $this->Form->end() ?>
</div>
<script>

var subCategories = <?= json_encode($subcategories_list);  ?>;

$(document).ready(function(){
         $('#category').change(function(){

  var categoryId = $(this).val();

  var subCategoriesObject = subCategories[categoryId];

  $('#subcategory option:gt(0)').remove();
  var subCategoriesSelect = $('#subcategory');

  $.each(subCategoriesObject, function(key,value) {
     subCategoriesSelect.append($("<option></option>").attr("value", key).text(value));
 });

});
});

</script>

此更新没有错误,但不会加载子类别的名称。

类别:

子类别:

我也是这样测试的,但是子类别没有显示任何值:

<script>
    $(document).ready(function () {
        var subCategories = {
            '0': [
                'cat0.0', 'cat0.1', 'cat0.2',
            ],
            '1': [
                'cat1.0', 'cat1.1', 'cat1.2',
            ],
            '2': [
                'cat2.0', 'cat2.1', 'cat2.2',
            ],
        };
        $('#category').change(function () {

            var categoryId = $(this).val();
            var subCategoriesObject = subCategories[categoryId];

            $('#subcategory option:gt(0)').remove();
            var subCategoriesSelect = $('#subcategory');

            $.each(subCategoriesObject, function (key, value) {
                subCategoriesSelect.append($("<option></option>").attr("value", key).text(value));
            });

        });
    });

</script>

日志 JS:

感谢任何评论或示例!

您不必像列表一样获取,您可以通过只获取类别及其子类别然后从那里构建您的 HTML/JS 来完成工作。

像这样:

$categories = $this->Products->Categories->find('all')
->contain(['Subcategories']);

在 HTML/CTP:

<php
$categories_list = [];
$subcategories_list = [];

foreach($categories as $category){

   $categories_list[$category->id] = $category->name; 

   foreach($category->subcategories as $subcategory){
     $subcategories_list[$category->id][$subcategory->id] = $subcategory->name;
   }
}

?>

所以你现在有一个包含所有子类别的数组,类别 ID 用作键。

<?php

echo $this->Form->select('category_id', ['options'=>$category_list, 'id'=>'category']);

echo $this->Form->select('subcategory_id', ['options'=>[], 'empty'=>'...', 'id'=>'subcategory']);
?>

现在Js

<script>

var subCategories = <?= json_encode($subcategories_list);  ?>;

$(document).ready(function(){
         $('#category').change(function(){

  var categoryId = $(this).val();

  var subCategoriesObject = subCategories[categoryId];

  $('#subcategory option:gt(0)').remove();
  var subCategoriesSelect = $('#subcategory');

  $.each(subCategoriesObject, function(key,value) {
     subCategoriesSelect.append($("<option></option>").attr("value", key).text(value));
 });

});
});

</script>

我没有测试过代码或其他任何东西,但我已经多次这样做了,你明白了。