6

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 to automatically hide so it's hidden from the user. This should happen dynamically.

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

3dgoo
  • 15,716
  • 6
  • 46
  • 58
BaronGrivet
  • 4,364
  • 5
  • 37
  • 52
  • This isn't a core function but Unclecheese made a module `Display Logic` that will solve this for you: https://github.com/unclecheese/silverstripe-display-logic – colymba Mar 30 '16 at 07:56

2 Answers2

6

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;
}
Barry
  • 3,303
  • 7
  • 23
  • 42
1

Every request to getCMSFields() uses current object state, so you can do 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 won't update the fields, and you need to save the form to trigger the update. unclecheese/silverstripe-display-logic module solves this problem.

Greg Smirnov
  • 1,592
  • 9
  • 9