How to limit Content Types for a given Page Type in Experience Manager - tridion

Experience Manager (XPM) (user interface update for SDL Tridion 2011 SP1) lets administrators create Page Types, which have component presentations just like pages, but also add rules on how to create and allow additional content types.
For a given page type, I'd like to simplify an author's options by limiting content type choices.
I understand we can:
Limit the content types, so that for a given page type authors can only create certain predefined content types
In the Dashboard, completely restrict the above to just predefined content types, by un-selecting Content Types Already Used on the Page
Use regions which specify combinations of schemas and templates along with quantity restrictions. Authors can only add (drag-and-drop) certain types and quantity of components to these region. For example, we can output the following on Staging to create a region:
<div>
<!-- Start Region: {
title: "Promos",
allowedComponentTypes: [
{
schema: "tcm:2-42-8",
template: "tcm:2-43-32"
},
],
minOccurs: 1,
maxOccurs: 3
} -->
<!-- place the matching CPs here with template logic (e.g. TemplateBeginRepeat/ TemplateBeginIf with DWT) -->
</div>
Authors may still see components they might want to insert (image below), but won’t be able to add them if regions control what’s allowed
However, folder permissions can reduce what components authors can see/use in the Insert Content library
Did I get them all? Any other ways in XPM functionality or possible extensions to consider on how to limit the allowed content for a given Page Type?

Alvin, you pretty much provided most of the options in your question. Another option, if a custom error message is desired or even finer level of control is to use the Event System. Subscribe to a Page's save event Initiated phase and write some validation code that throws an exception if an unwanted component presentation is on the page.
Since Page Types are really a combination of a page template, any metadata on the page and the types of component presentations on the page, we would need to check that we are dealing with the wanted page type and if encounter an CP that doesn't match what we desire, we can simply throw the exception. Here is some quick code:
[TcmExtension("Page Save Events")]
public class PageSaveEvents : TcmExtension
{
public PageSaveEvents()
{
EventSystem.Subscribe<Page, SaveEventArgs>(ValidateAllowedContentTypes, EventPhases.Initiated);
}
public void ValidateAllowedContentTypes(Page p, SaveEventArgs args, EventPhases phases)
{
if (p.PageTemplate.Title != "My allowed page template" && p.MetadataSchema.Title != "My allowed page metadata schema")
{
if (!ValidateAllowedContentTypes(p))
{
throw new Exception("Content Type not allowed on a page of this type.");
}
}
}
private bool ValidateAllowedContentTypes(Page p)
{
string ALLOWED_SCHEMAS = "My Allowed Schema A; My Allowed Schema B; My Allowed Schema C; etc"; //to-do put these in a parameter schema on the page template
string ALLOWED_COMPONENT_TEMPLATES = "My Allowed Template 1; My Allowed Template 2; My Allowed Template 3; etc"; //to-do put these in a parameter schema on the page template
bool ok = true;
foreach (ComponentPresentation cp in p.ComponentPresentations)
{
if (!(ALLOWED_SCHEMAS.Contains(cp.Component.Schema.Title) && ALLOWED_COMPONENT_TEMPLATES.Contains(cp.ComponentTemplate.Title)))
{
ok = false;
break;
}
}
return ok;
}
}

Related

Accessing context from a custom View

When configuring the views of a calendar, view specific options can be specified. But the documentation about custom views says nothing on how to retrieve these options.
Is there any way to get these options here and so to make the custom view to behave function of them ?
Is there even a way to access the view object from a custom view callback ? (maybe the options are available on it)
One solution I've used, but I think that should be part of the core behavior, is to use the undocumented viewPropsTransformers option when creating a custom view through a call to createPlugin :
class MorePropsToView {
transform(viewProps, calendarProps) {
return {
...viewProps,
options: calendarProps.viewSpec.optionOverrides,
calendar: calendarProps.calendarApi,
}
}
}
export const myPlugin = createPlugin({
views: {
custom: CustomView,
},
viewPropsTransformers: MorePropsToView,
})
So the two extra props are available in the custom view :
const CustomView = function CustomView({
eventStore,
dateProfile,
options,
calendar,
}) {
console.log(options, calendar)
}

What is 'Template.instance().view'?

I read [Template.instance().view]1 at Blaze docs.
Also I read Blaze.view().
I even saw the view object in the console log.
But I can't understand.
Could anyone explain it more intuitively and smoothly, please? :)
If you want to understand Views more deeply, you need to understand the relationship between Templates, TemplateInstances, and Views. Views are just reactive parts of the DOM. Template instances contain one View, but templates can create more views through functions that create renderable content like Blaze.with ({{#with}}) or Blaze.if ({{#if}}). These "child" views will will then store a parent pointer, which you can use to reconstruct the View tree.
What might help your understanding is playing around with how Templates and Views interact in Chrome tools. You can find a template instance by using any DOM element. Here is an example to get you started:
templateInstance = Blaze.findTemplate($('<some component in dom>')[0])
view = templateInstance.view
You can extend Blaze to contain findTemplate like this:
Blaze.findTemplate = function(elementOrView) {
if(elementOrView == undefined) {
return;
}
let view = Object.getPrototypeOf(elementOrView) === Blaze.View.prototype
? elementOrView
: Blaze.getView(elementOrView);
while (view && view.templateInstance === undefined) {
view = view.originalParentView || view.parentView;
}
if (!view) {
return;
}
return Tracker.nonreactive(() => view.templateInstance());
};

Displaying dynamic content in Meteor using Dynamic Templates

I've read through the (somewhat sparse) documentation on Dynamic Templates but am still having trouble displaying dynamic content on a user dashboard based on a particular field.
My Meteor.users collection includes a status field and I want to return different content based on this status.
So, for example , if the user has a status of ‘current’, they would see the 'currentUser' template.
I’ve been using a dynamic template helper (but have also considered using template helper arguments which may still be the way to go) but it isn’t showing a different template for users with different statuses.
{{> Template.dynamic template=userStatus}}
And the helper returns a string to align with the required template as required
userStatus: function () {
if (Meteor.users.find({_id:Meteor.userId(), status: 'active'})){
return 'isCurrent'
}
else if (Meteor.users.find({_id:Meteor.userId(), status: ‘isIdle'})) {
return 'isIdle'
} else {
return ‘genericContent'
}
}
There may be much better ways to go about this but it seems a pretty common use case.
The few examples I've seen use Sessions or a click event but I’d rather use the cursor if possible. Does this mean what I’m missing is the re-computation to make it properly reactive? Or something else incredibly obvious that I’ve overlooked.
There is a shortcut for getting the current user object, Meteor.user(). I suggest you get this object and then check the value of the status.
userStatus: function () {
if(Meteor.user()) {
if (Meteor.user().status === 'active') {
return 'currentUserTemplate'; // this should be the template name
} else if (Meteor.user().status === 'isIdle') {
return 'idleUserTemplate'; // this should be the template name
}
} else {
return ‘notLoggedInTemplate'; // this should be the template name
}
}
Ended up using this approach discussed on the Meteor forums which seems a bit cleaner.
{{> Template.dynamic template=getTemplateName}}
And the helper then becomes:
getTemplateName: function() {
return "statusTemplate" + Meteor.user().status;
},
Which means you can then use template names based on the status:
<template name="statusTemplateActive">
Content for active users
</template>
(though keep in mind that Template helpers don't like hyphens and the data context needs to be set correctly)

Orchard Custom Widget with Form

I built a custom module that manages appointments for a service-based company. All of the current functionality is contained in the admin section. I have not used a single ContentItem or ContentPart. All the models are just plain records.
I'm looking to create a widget to expose the ability to sign up for an appointment from the front end. I have a partial view and a controller that handles the display and form submit, but I'm not sure how to tie that into a widget that can be placed in one of the content zones of the front-end.
I've spent quite a bit of time researching this, and can't find a good path to follow. (I've tried a few and got sub-optimal results)
Any suggestions?
The best answer for me was to create a widget Type definition in the migration.cs file of the module:
ContentDefinitionManager.AlterTypeDefinition("CreateAppointmentWidget",
cfg => cfg
.WithPart("WidgetPart")
.WithPart("CommonPart")
.WithSetting("Stereotype", "Widget"));
Then create a handler for that widget at /MyModule/Handlers/CreateAppointmentWidgetHandler.cs:
public class CreateAppointmentWidgetHandler : ContentHandler
{
private readonly IRepository<FieldTechRecord> _repository;
public CreateAppointmentWidgetHandler(IRepository<FieldTechRecord> repository)
{
_repository = repository;
}
protected override void BuildDisplayShape(BuildDisplayContext context)
{
base.BuildDisplayShape(context);
if (context.ContentItem.ContentType == "CreateAppointmentWidget")
{
CreateAppointmentViewModel model = new CreateAppointmentViewModel(_repository.Fetch(x => x.IsActive));
context.Shape.AppointmentModel = model;
}
}
}
Then create a matching widget template at /MyModule/Views/Widget-CreateAppointmentWidget.cshtml that inserts the Partial View:
#Html.Partial("CreateAppointment", (MyModule.Models.Views.CreateAppointmentViewModel)Model.AppointmentModel)
The above code grabs the partial view /MyModule/Views/CreateAppointment.cshtml.
Thanks to Giscard's suggestion, I was able to correct the links rendered from CreateAppointment.cshtml by using #Url.RouteUrl() and defining named routes to point where I needed the action and ajax requests to go.
The nice thing about this solution is that it provided a way to create the widget without having to rework my models to use Orchards ContentPart functionality.
Something is not connecting in my head, because I have been able to create a theme with zones, and then dispatch a shape from my module into that zone without much more than doing #Display.Shape(). So I am curious if it's absolutely necessary to use a handler to override the BuildDisplayShape.
Again, this is in the scenario where you have models as plain records (not using ContentItem or ContentPart - and even if not using them, you've shown an example of creating one through migrations).
Something like this - Controller:
public ShapeResult MyShape()
{
var shape = _orchardServices.New.MyPath1_MyShape();
return new ShapeResult(this, shape);
}
Then create a MyShape.cshtml shape with whatever code I have (no need for example).
NOTE: I use a custom IShapeTemplateHarvester file which adds paths where I can store my shapes (instead of using "Views", "Views/Items", "Views/Parts", "Views/Fields", which is the stock in Orchard). It goes something like this:
NB: I hate that code doesn't automatically wrap in SO.
[OrchardSuppressDependency("Orchard.DisplayManagement
.Descriptors.ShapeTemplateStrategy.BasicShapeTemplateHarvester")]
public class MyShapeTemplateHarvester : BasicShapeTemplateHarvester,
IShapeTemplateHarvester
{
public new IEnumerable<string> SubPaths()
{
var paths = base.SubPaths().ToList();
paths.Add("Views/MyPath1");
paths.Add("Views/MyPath2");
return paths;
}
}
Say I have Index.cshtml in my Theme. I have two choices (I use both and use the Theme as the default presentation).
Index.cshtml in Theme folder:
#*Default Content*#
Index.cshtml in Module folder:
#*Special Content overriding Theme's Index.cshtml*#
Display.MyPath1_MyShape()
Even better for me is that I can do this in the Index.cshtml in Theme folder:
#*Whatever content*#
Display.MyPath1_MySecondShape()
There is no ~/MyPath1/MySecondShape.cshtml in the Theme, but there is one in the Module, which the Theme displays! This is great because I can have a special Theme and have multiple modules (that are placed on separate sites) go back and forth with the theme (think Dashboard for different services in the same profession on different sites).
NOTE: The above may only be possible with IThemeSelector implementation such as:
public class MyThemeSelector : IThemeSelector
{
public ThemeSelectorResult GetTheme(RequestContext context)
{
if (MyFilter.IsApplied(context))
{
return new ThemeSelectorResult { Priority = 200,
ThemeName = "MyDashboard" };
}
return null;
}
}
Just my two bits.

Can I enable users on Plone4 to show/hide the Portlet column on-the-fly

The Portlets in Plone are quite handy but I'd like to be able to provide some method to users to be able to temporarily hide/show the portlets column. That is, by clicking a button, the portlets column should collapse and you see the content page in full width. Then clicking again and the portlets panel on the left expands and the main content page width shrinks to accommodate.
I've observed the HTML ID of the portlets column is "portal-column-one" and I tried adding a button to the page that runs javascript to set the visibility property of that element to "hidden" but this seemed to have no effect. I was able to go into Firebug and add style="visibility:hidden;" to the "portal-column-one" element and it had the effect of making the region invisible w/o resizing the page.
I am using Plone 4.1. I have the site configured with navigation portlet on all pages except the main page which has Navigation, Review List and Recent Changes.
So it seems it must be possible to embed some javascript in the page (I was thinking of adding this to the plone.logo page which I've already customized). But I guess its more complicated than the few stabs I've made at it.
Thanks in advance for any advice.
Solution (Thanks to input from Ulrich Schwarz and hvelarde):
The solution I arrived at uses JavaScript to set CSS attributes to show/hide the Portlets Column (Left side) and expand the content column to fill the space the porlets column filled.
I started by customizing the Plone header template to add a link for the user to toggle the view of the Porlets column. I also put the necessary javascript functions in this header.
To customize the header, go to the following page (need to be logged in as Admin of your Plone site):
http://SERVER/SITE/portal_view_customizations/zope.interface.interface-plone.logo
Where:
SERVER is the address and port of your site (e.g. localhost:8080)
SITE is the short name of your Plone Site
To create this page:
Go to Site Setup (as Admin)
Go to Zope Management Interface
Click on "portal_view_customizations"
Click on "plone.logo" (or at least this is where I choose to put the button so it would be located just above the navigation Portlet)
Add the following to the page:
<script>
function getById(id) {
return document.getElementById(id);
}
function TogglePortletsPanel() {
var dispVal = getById('portal-column-one').style.display
if( dispVal == "none") { // Normal display
SetPortletsPanelState("inline");
} else { // Full Screen Content
SetPortletsPanelState("none");
}
}
function SetPortletsPanelState(dispVal) {
var nav = getById('portal-column-one');
var content = getById('portal-column-content');
if( dispVal == "none") { // Normal display
nav.style.display='none';
content.className='cell width-full position-0';
// Set cookie to updated value
setCookie("portletDisplayState","none",365);
} else { // Full Screen Content
nav.style.display='inline';
content.className='cell width-3:4 position-1:4';
// Set cookie to updated value
setCookie("portletDisplayState","inline",365);
}
}
function InitializePortletsPanelState() {
var portletDisplayState=getCookie("portletDisplayState");
//alert("portletDisplayState="+portletDisplayState)
if (portletDisplayState!=null) SetPortletsPanelState(portletDisplayState);
}
function setCookie(c_name,value,exdays) {
//alert(c_name+"="+value);
// cookie format: document.cookie = 'name=value; expires=Thu, 2 Aug 2001 20:47:11 UTC; path=/'
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var exp= ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + escape(value) + exp + "; path=/";
}
function getCookie(c_name) {
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++) {
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name) return unescape(y);
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {oldonload(); }
func();
}
}
}
addLoadEvent(InitializePortletsPanelState);
</script>
<a style="font-size:50%;" href="javascript:TogglePortletsPanel();">Toggle Portlets Panel</a>
6. Save the page
Notes:
I got the names of the plone div elements using Firebug.
I also used Firebug to experiment with different settings to speed up prototyping. For example, editing the HTML inline to verify settings do as expected.
There is a slight but of delay until the Left Portlet panel is hidden. This is only obvious on Safari for me (which is probably due to how fast it is) but not on Firefox or IE.
Maybe it's just a matter of setting the right property: you want display:none, not visibility:hidden.
But even then, the content area will probably not reflow automatically, you'll need to (dynamically) change the class on it as well.
Specifically, you'll need to put classes width-full and position-0 on portal-column-content, instead of width-1:2 and position-1:4.
This must be achieved client side by javascript (jquery).
You must first read documentation about the css grid framework used by plone: deco.gs. The website is down so, git clone this repo: https://github.com/limi/deco.gs and open pages in a webbrowser
Note: you just have to change css classes on the containers.
Try adi.fullscreen, it respects Plone's css-structure as Ulrich Schwarz thoughtfully mentioned.

Resources