ajaxcakephpmodel-associationscakephp-3.2

Update related list with change in list in CakePHP 3


I have two tables categories and subcategories where categories hasMany subcategories relation.

I have another table products which is related to categories and subcategories.

In add method of products I want to select category from the list and then subcategory associated with particular category 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');

As there is no js helper in CakePHP 3. How could I do this using Ajax.

I'm new to CakePHP and Ajax as well. And currently this show all subcategories in the list.


Solution

  • I get it working like this and its working fine.

    view file contain

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

    and myAjax.js file contain

    $('#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);
            }
        });
    });
    

    and ajaxSubcategories action inside 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;
    }
    

    Hope this might help someone.