How to dynamically show/hide field in SilverStripe ModelAdmin
Asked Answered
D

2

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?

Detribalize answered 30/3, 2016 at 0:56 Comment(1)
This isn't a core function but Unclecheese made a module Display Logic that will solve this for you: github.com/unclecheese/silverstripe-display-logicHooper
H
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;
}
Herc answered 30/3, 2016 at 8:53 Comment(0)
I
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.

Idelson answered 30/3, 2016 at 22:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.