How to dynamically show / hide a field in SilverStripe ModelAdmin

I have a Dataobject in ModelAdmin with the following fields:

class NavGroup extends DataObject { private static $db = array( 'GroupType' => 'Enum("Standard,NotStandard","Standard")', 'NumberOfBlocks' => 'Int' ); public function getCMSFields() { $groupTypeOptions = singleton('NavGroup')->dbObject('GroupType')->enumValues(); $fields = parent::getCMSFields(); $fields->addFieldToTab('Root.Main', new Dropdownfield('GroupType', 'Group Type', $groupTypeOptions)); $fields->addFieldToTab('Root.Main', new Numericfield('NumberOfBlocks', 'Number of Blocks')); return $fields; } } 

If GroupType == "Standard" , I want the NumberOfBlocks field NumberOfBlocks be hidden automatically, so it is hidden from the user. This should happen dynamically.

Is this functionality available in SilverStripe or do I need to add some kind of custom JavaScript?

+5
source share
2 answers

You need to use the DisplayLogic module ...

https://github.com/unclecheese/silverstripe-display-logic

Then your function can be written as ...

 public function getCMSFields() { $fields = parent::getCMSFields(); $fields->addFieldsToTab('Root.Main',array( Dropdownfield::create('GroupType', 'Group Type', singleton('NavGroup')->dbObject('GroupType')->enumValues())), Numericfield::create('NumberOfBlocks', 'Number of Blocks') ->displayIf('GroupType')->isEqualTo('Standard') )); return $fields; } 
+4
source

Each getCMSFields() request uses the current state of the object, so you can make a simple if statement for such cases:

 public function getCMSFields() { $groupTypeOptions = singleton('NavGroup')->dbObject('GroupType')->enumValues(); $fields = parent::getCMSFields(); $fields->addFieldToTab('Root.Main', new Dropdownfield('GroupType', 'Group Type', $groupTypeOptions)); if ($this->GroupType === 'Standard') { $fields->addFieldToTab('Root.Main', new Numericfield('NumberOfBlocks', 'Number of Blocks')); } else { $fields->addFieldToTab('Root.Main', new HiddenField('NumberOfBlocks', $this->NumberOfBlocks); } return $fields; } 

However, changing GroupType will not update the fields, and you need to save the form to start the update. unclecheese/silverstripe-display-logic solves this problem.

+1
source

Source: https://habr.com/ru/post/1246029/


All Articles