Limit number of records that can be added to a SilverStripe GridField
Small module to limit number of records that can be added to a SilverStripe GridField.
Important - this module does not prevent records being added at an ORM/code-level in any way.
Instead, it manipulates the GridField
UI to allow developers to hide controls like GridFieldAddNewButton
once a set limit is reached, preventing CMS users from adding more records via that grid field.
GridFieldAddNewButton
, GridFieldAddExistingAutocompleter
and other GridFieldComponent
s you define, if the limit is reachedSilverStripe 4.2+
composer require fromholdio/silverstripe-gridfield-limiter
GridFieldLimiter
to your GridFieldConfig
, and define a target fragment (defaults to before
)limiter-before-left
and limiter-before-right
(before
comes from the defined target fragment)GridFieldAddNewButton
on the left and a GridFieldAddExistingAutocompleter
on the right, which will all be hidden (via css) from the CMS user once the grid field reaches its row limitPer the note above, this does not in anyway validate the number of objects in a relationship or prevent an object being added - it's just a cheeky way to implement a limit for CMS users managing a grid field.
We have a standard GridField
using a GridFieldConfig_RecordEditor
and will add a limit to it.
$gridField = GridField::create(
'Widgets',
'Widgets',
$this->Widgets(),
$gridConfig = GridFieldConfig_RecordEditor::create()
);
Remove the GridFieldAddNewButton
in preparation to add one within our GridFieldLimiter
:
$gridConfig->removeComponentsByType(GridFieldAddNewButton::class);
Add the GridFieldLimiter
$limit = 4; // We want to limit this gridfield to 4 objects
$targetFragment = 'before' // Set gridfield target fragment value
$showLimitReachedMessage = true // We want to show the user a note when the limit is reached
$gridConfig->addComponent(
new GridFieldLimiter($limit, $targetFragment, $showLimitReachedMessage)
);
Add a GridFieldAddNewButton
(and/or any other components) you would like displayed while under limit but hidden when limit is reached, using the limiter
target fragment.
$gridConfig->addComponent(
new GridFieldAddNewButton('limiter-before-left')
);
That should work!
$fields->addFieldToTab('Root.Testing', $gridField);
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