fromholdio / silverstripe-dependentgroupeddropdownfield
A silverstripe groupeddropdown field that has it's options populated via ajax, based on the value of the field it depends on
Installs: 1 587
Dependents: 2
Suggesters: 0
Security: 0
Stars: 1
Watchers: 2
Forks: 0
Open Issues: 1
Language:JavaScript
Type:silverstripe-vendormodule
Requires
- php: >=7.4
- silverstripe/framework: ~5.0
- silverstripe/vendor-plugin: ~2.0
README
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
.
Requirements
SilverStripe 4
Installation
composer require fromholdio/silverstripe-dependentgroupeddropdownfield
What exactly is this?
See user guide for usage screenshots.
Usage example
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 ] );