0

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.

E_net4
  • 27,810
  • 13
  • 101
  • 139
Ya Basha
  • 1,902
  • 6
  • 30
  • 54

1 Answers1

0

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', ...];
    }
}
Joseph Oppegaard
  • 611
  • 5
  • 12
  • thanx for your answer but I needed to make it dynamic, I found a test plugin which shows this https://github.com/octoberrain/test-plugin – Ya Basha Jul 13 '20 at 05:57
  • That does make it dynamic- the getCountryOptions() and getStateOptions() in the example above is just an example with hard coded data. You can query the database or do whatever other calculations you might need to do to generate the array that you want to return. – Joseph Oppegaard Jul 13 '20 at 16:32