laraveloctobercmsoctobercms-pluginsoctobercms-backend

Displaying categories and thei subcategories in OctoberCMS backend form


I am developing a plugin using Builder plugin to display items and their categories and subcategories.

Item model have $belongsTo relations with Category and SubCategory models, also Category has $belongsToMany relation with SubCategory, and I created a form which has a relation widget to display the categories, but I don't know how to display the subcategories relation widget which are for the selected category and when user select new category a diffrent list of subcategories will be displayed in sub categories drop down box.


Solution

  • Well, my previous post was deleted because I simply included a link and a short description but not code.

    What you are looking for are "Field dependencies":

    https://octobercms.com/docs/backend/forms#field-dependencies

    You won't be able to do it all through the Builder plugin- you will have to write some code. Here is an example:

    The fields.yaml file for your model:

    country:
        label: Country
        type: dropdown
    
    state:
        label: State
        type: dropdown
        dependsOn: country
    

    Then, in the controller:

    public function getCountryOptions()
    {
        return ['au' => 'Australia', 'ca' => 'Canada'];
    }
    
    public function getStateOptions()
    {
        if ($this->country == 'au') {
            return ['act' => 'Capital Territory', 'qld' => 'Queensland', ...];
        }
        elseif ($this->country == 'ca') {
            return ['bc' => 'British Columbia', 'on' => 'Ontario', ...];
        }
    }