Snippets - Little bits of code to make you happy
Create a CMS Field in 'Page' but not it's Descendants
Tweet26 April 2009 | |
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()
{
...
if(!$this->ParentID)
{
$fields->addFieldToTab("Root.Content.Main", new ImageField("Banner"));
}
...
}
1 Comments
RSS feed for comments on this page RSS feed for all comments
Pete Bacon Darwin
12/05/2011 2:00pm (2 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:
SiteTree
- PageBase
- Page
- NormalPage
- SpecialPage
Post a comment ...
You cannot post comments until you have logged in. Login Here.