SSbits - Home page
Site by Carbon Crayon
Submit a Post >

Snippets - Little bits of code to make you happy

Create a CMS Field in 'Page' but not it's Descendants

Sometimes you may want a field to appear in pages of type Page but not in the other PageTypes which extend Page. To limit a field added via the function getCMSFields() is a simple case of adding an if() statement to test the current pages class.

public function getCMSFields()
	if($this->ClassName == "Page")
		$fields->addFieldToTab("Root.Content.Main", new TextField("PageField"));

This kind of conditional field including can be extended to create dynamic forms in the CMS, for example, here we are only including the ImageField if we are on the top level of the tree

public function getCMSFields()
		$fields->addFieldToTab("Root.Content.Main", new ImageField("Banner"));
Aram Balakjian avatar

Aram Balakjian

Aram is a web developer running London based agency Aab Web. He has a strong passion for developing attractive, usable sites around the SilverStripe CMS.

  • Pete Bacon Darwin
    12/05/2011 2:00pm (6 years ago)

    While this is an effective method of achieving what you suggest, it worries me.

    First, you are only really hiding it from the admin pages. The field is still going to be available on each of the derived classes. This seems a bit wasteful.

    Second, it is a bit of hidden magic, which increases complexity and makes it harder to maintain the software. Normally one expects fields to be inherited from the parent classes. This is one of the main reasons to inherit.

    Assuming we do actually have control over the Page class, I would feel more happy if one were to move common fields that should be inherited into an abstract parent class, e.g. PageBase, and then have Page derive from this and implement these special one-off fields. Page types that should not inherit these special fields should then derive directly from PageBase. In this way the inheritance model is not subverted and the classes are more self documenting without having to trawl through what is going on in getCMSFIelds.

    Your inheritance hierarchy would then look a bit like this:

    - PageBase
    - Page
    - NormalPage
    - SpecialPage

Post a comment ...

You cannot post comments until you have logged in. Login Here.


Site of the Month

Find SSbits on

Top Contributers

Rank Avatar Name
1 article image Aram Balakjian
2 article image wfacewomens
3 article image Daniel Hensby
4 article image Marcus Dalgren
5 article image ryduhartchas
6 article image Hamish Campbell
7 article image Ty Barho
8 article image Martijn van Nieuwenhoven
9 article image Darren-Lee
10 article image Roman Schmid

View full leaderboard