A silverstripe groupeddropdown field that has it's options populated via ajax, based on the value of the field it depends on
A SilverStripe grouped dropdown field that has its options populated via ajax, based on the value of the dropdown field it depends on.
N.b. This is basically a direct port of Shea Dawson's silverstripe-dependentdropdownfield that applies the ajax to a GroupedDropdownField
rather than a DropdownField
.
SilverStripe 4
composer require fromholdio/silverstripe-dependentgroupeddropdownfield
See user guide for usage screenshots.
First, create the DropdownField
that your new field's values will be dependent on.
$typeField = DropdownField::create(
'ProductType',
'Product Type',
[
'animal' => 'Animal',
'food' => 'Food'
]
);
$typeField->setEmptyString('Please select a product type');
Note: it is not necessary for the original dropdown field to have an empty string. If it doesn't, its first value will be used to auto-load the optgroups/options into your dependent field.
Second, create a callable function that returns an array suitable for the $source parameter of GroupedDropdownField. (A two dimensional array; the first level is used for the optgroup, and the second level for the of each group.)
$productFieldSource = function($value) {
if ($value === 'animal') {
return [
'Fun' => [
'puppy' => 'Puppy',
'dog' => 'Dog'
],
'Evil' => [
'cat' => 'Cat'
]
];
}
if ($value === 'food') {
return [
'Fruit' => [
'apple' => 'Apple',
'orange' => 'Orange'
],
'Vegetables' => [
'carrot' => 'Carrot',
'celery' => 'Celery'
]
];
}
return [];
};
Now, create your DependentGroupedDropdownField
, setting the source as the callable function created above.
$productField = DependentGroupedDropdownField::create(
'Product',
'Product',
$productFieldSource
);
Ensure that you connect the fields:
$productField->setDepends($typeField);
And now you're ready to go.
$fields->addFieldsToTab(
'Root.Testing',
[
$typeField,
$productField
]
);
Module rating system helping users find modules that are well supported. For more on how the rating system works visit Module standards
Score not correct? Let us know there is a problem