Is there a way to alter an Orchard content shape's display type before placement and rendering happens? - orchardcms

We are trying to implement a generic reusable paywall as a ContentPart in Orchard 1.10. The goal is to obscure certain content from non-paying users while keeping its detail page accessible as a teaser.
The original idea was to use a ShapeTableProvider to inspect every "Content" shape and change its display type according to the permissions of the user. Then it would be possible to customize what we want to show in placement on a per-content basis. e.g. only display the Layout_Summary instead of the full Layout if users don't have access to a news article.
Something along these lines:
builder.Describe("Content").OnDisplaying(displaying => {
if(displaying.Shape.Metadata.DisplayType == "Detail" && !_authorizer.Authorize(ViewPaidContent) {
displaying.Shape.Metadata.DisplayType == "DetailPaywall";
}
});
--
<Placement>
<Match DisplayType="DetailPaywall">
<Place Parts_Layout="-"/>
...
</Match>
</Placement>
However, it turns out that OnDisplaying happens too late, placement has already been decided and ContentDrivers get invoked. OnCreated happens too early and would be overridden again. I believe the relevant code that triggers these is the BuildDisplay method in Orchard.ContentManagement.DefaultContentDisplay. Whichever displayType parameter is passed here is the one that ends up getting used.
Is there any way to influence display type in code based on some condition, or a different approach we can use to achieve similar functionality?

The display type is usually determined by the driver for the part. What you should probably do instead is introduce an alternate:
builder.Describe("Content").OnDisplaying(displaying => {
if(displaying.Shape.Metadata.DisplayType == "Detail" && !_authorizer.Authorize(ViewPaidContent) {
displaying.Shape.Metadata.Alternates.Add("Content__Paywall");
}
});
You can then add a Content-Paywall.cshtml template override to your theme and you should be done.

Related

Alternate shape for EditorTemplate of Field is not being recognized

I need an alternate for the EditorTemplate of an Enumerator Field that's used when the Field has a particular name (PublishingMethod).
Based on the docs, I created a view with the pattern [ShapeType__FieldName] in the same folder as the original shape:
This is not working and still uses the original. I've thought of changing the Editor method in the Driver, but I think that defeats the purpose of alternates, which is that Orchard automatically detects the correct shape as I understand from the docs:
The Orchard framework automatically creates many alternates that you can use in your application. However, you can create templates for these alternate shapes.
Note: I can't use the Shape Tracing module, it never worked even with a clean Orchard install.
The editors in Orchard work different to how Display works. I guess it is so you get a MVC-style experience. Basically, the actual shape returned is of type EditorTemplate, which then binds your model and prefix then renders a partial view with the template name you gave it. What this means is alternates wont work as expected, or as the docs state. The alternates for your field name are actually added to the EditorTemplate shape. So what you can do is add a view called EditorTemplate-PublishingMethod.cshtml with contents like:
#{
var m = (Orchard.Fields.Fields.EnumerationField)Model.Model;
}
#Html.Partial("PublishingMethodEditor", m, new ViewDataDictionary {
TemplateInfo = new TemplateInfo { HtmlFieldPrefix = Model.Prefix }
})
Then add another view called PublishingMethodEditor.cshtml with the overrides you want for your editor. All these views should go in the root of your Views folder.
Another approach would be to implement the IShapeTableProvider interface and adjust the TemplateName property on a certain condition but, meh, that requires code...
Edit 1
If you have that field name on other content types that you don't want to override you can use the override EditorTemplate-ContentTypeName-PublishingMethod.cshtml

OrchardCMS: How to access Content Menu Item boolean field in cshtml view

In orchard, I've added a boolean field called "IsDone" to the built in Content Menu Item content part via that Admin interface. I've then picked an item in Navigation and set the option to "yes" for the corresponding field i added.
In my custom theme, I've copied over MenuItem.cshtml.
How would I get the value of my custom "IsDone" field here?
I've tried something like
dynamic item = Model.ContentItem;
var myValue = item.MenuItem.IsDone.Value;
but I'm pretty sure my syntax is incorrect (because i get null binding errors at runtime).
thanks in advance!
First i suggest you use the shape alternate MenuItemLink-ContentMenuItem.cshtml instead of MenuItem.cshtml to target the content menu item directly.
Secondly, the field is attached to the ContentPart of the menu item. The following code retrieves the boolean field from this content part:
#using Orchard.ContentManagement;
#using System.Linq;
#{
Orchard.ContentManagement.ContentItem lContentItem = Model.Content.ContentItem;
var lBooleanField = lContentItem
.Parts
.Where(p => p.PartDefinition.Name == "ContentMenuItem") // *1
.SelectMany(p => p.Fields.Where(f => f.Name == "IsDone"))
.FirstOrDefault() as Orchard.Fields.Fields.BooleanField;
if (lBooleanField != null)
{
bool? v = lBooleanField.Value;
if (v.HasValue)
{
if (v.Value)
{
#("done")
}
else
{
#("not done")
}
}
else
{
#("not done")
}
}
}
*1
Sadly you cannot simply write lContentItem.As<Orchard.ContentManagement.ContentPart>() here as the first part in the part list is derived from this type, thus you would receive the wrong part.
While #ViRuSTriNiTy's answer is probably correct, it doesn't take advantage of the power of the dynamic objects that Orchard provides.
This is working for me but is a much shorter version:
#Model.Text
#{
bool? IsDone = Model.Content.ContentMenuItem.IsDone.Value;
var IsItDoneThough = (IsDone.HasValue ? IsDone.Value : false);
}
<p>Is it done? #IsItDoneThough</p>
You can see that in the first line I pull in the IsDone field using the dynamic nature of the Model.
For some reason (I'm sure there is a good one somewhere) the BooleanField uses a bool? as its backing value. This means that if you create the new menu item and just leave the checkbox blank it will be null when you query it. After you have saved it as checked it will be true and then if you go back and uncheck it then it will have the value false.
The second line that I've provided IsItDoneThough checks if it has a value yet. If it does then it uses that, otherwise it assumes it to be false.
Shape Alternate
#ViRuSTriNiTy's other advice, to change it to use the MenuItemLink-ContentMenuItem.cshtml instead of MenuItem.cshtml is also important.
The field doesn't exist on other menu items so it will crash if you try to access it. Just rename the .cshtml file to fix this.
Dynamic Model
Just to wrap this up with a little bit of insight as to how I got there (I'm still learning this as well) the way I figured it out is as follows:
.Content is a way of casting the current content item to dynamic, so you can use the dynamic advantages with the rest of line;
When you add the field in the admin panel it looks like it should be right there on the ContentItem, however it actually creates an invisible ContentPart to contain them and calls it whatever the ContentItem's type is.
So if you had added this field to a Page content type you would have used Model.Content.Page.IsDone.Value. If you had made a new content type called banana it would be Model.Content.Banana.IsDone.Value, etc.
Once you are inside the "invisible" part which holds the fields you can finally get at IsDone. This won't give you the actual value yet though. Each Field has its own properties which you can look up in the source code. the IsDone is actually a BooleanField and it exposes its data via the Value property.
Try doing a solution-wide search for : ContentField to see the classes for each of the fields you have available.
Hopefully this will have explained things clearly but I have actually written about using fields in a blog post and as part of my getting started with modules course over on the official docs (its way down in part 3 if you're curious).
Using built-in features instead of IsDone
This seems like a strange approach to do it this way. If you have a Content Item like a Page then you can just use the "Show on a menu" setting on the page.
Go to admin > content > open the page > down near the bottom you will find "Show on a menu":
This will automatically put it into your navigation and then you can move it around to where you want:
After it "IsDone" you can just go back and untick the "Show on a menu" option.
Setting up the alternative .cshtml
To clarify your comments about how to use the alternative, you need to
Copy the file you have at Orchard.Core/Shapes/Views/MenuItem.cshtml over to your theme's view folder so its /Views/MenuItem.cshtml
Rename the copy in your theme to MenuItem-ContentMenuItem.cshtml
Delete probably everything in it and paste in my sample at the start of this post. You don't want most of the original MenuItem.cshtml code in there as it is doing some special tricks to change itself into a different shape which isn't what you want.
Reset your original Orchard.Core/Shapes/Views/MenuItem.cshtml back to the factory default, grab it from the official Orchard repository
Understanding the view names
From your comments you asked about creating more specific views (known as alternates). You can use something call the Shape Tracer to view these. The name of them follows a certain pattern which makes them more and more specific.
You can learn about the alternates on the official docs site:
Accessing and Rendering Shapes
Alternates
To figure out what shape is being used and what alternates are available you can use the shape tracing module which is documented here:
Getting Started with Shape Tracing

Orchard custom page renders default widgets?

Still getting to know Orchard, I've now managed to create a custom default page using a module and routing rules.
Although Orchard properly shows my page, it also renders three what seem to be default widgets, with the headings "First Leader Aside", "Second Leader Aside", "Third Leader Aside". Ok so apparantly you need to overwite that default behaviour or something like that, but I can't figure out how.
So is there something wrong / missing with my module, or do I need to provide a setting or something like that?
If a widget is in the default layer, it will appear on every single page in the site. See http://docs.orchardproject.net/Documentation/Managing-widgets
You will need to put these widgets in a different layer that is defined by a rule that fits what you want.

Magento :: Layout in Module

Is it possible to create a layout file inside of a module ? How ?
For what:
I want to add a some kind of statistics hit counter for products, and I don't want to override the products class, as that is already done by some module I'm using. Thus I thought it would be best to have a custom module with a block that would be called by a layout statement.
Of course I could easily edit my private local.xml or make changes to another layout-xml in the layout folder of my theme, but I want this feature to be available in all themes (independent of any selected theme).
Some constraints:
All code in one single module
... so that it is theme independent
... so that the module can be shared with others without them having to change anything (like theme files), so that the install/load of my module would be enough
I would also accept different approaches for my statistics hit counter loading (using the same constraints)
Yes it is possible. Just create your layout xml file in the following path: /design/frontend/default/default/layout/yourlayout.xml(or whatever your theme name is), and add a proper statement in your modules etc/config.xml:
<config>
<frontend>
<layout>
<updates>
<yourmoduleshortname>
<file>yourlayout.xml</file>
<yourmoduleshortname>
</updates>
</layout>
</frontend>
</config>
This sample is for frontend user, but adminhtml layouts can be updated in a similar manner. If something doesn't work, be sure to check if your layout is in the proper theme/package directory.
Edit:
Second approach:
You can use a controller of your own, which will extend the core functionality (one of the catalog controllers) - just rewrite it (or just product view action). Inside its action method add something like this:
$thiss->getLayout()->createBlock('namespacename/block','layout-block-name',
array('template' => 'relativepathtotemplate.phtml'));
$this->getLayout()->getBlock('content')->append($block);
run-original-parent-code();
Third approach:
Similar to the previous one, but you can use some event observer, and try Mage::getSingleton('core/layout'), and inject your block there. Not in all events the layout will be already available (try the post_dispatch family).
I don't really recommend the second and third approach, because if someone else wants to find where this 'magic' block comes from, it will most surely look int app/design/(...) directory. Finding it in your controller or model, may be very tricky...
If you don't want to display your statistic counter, you can also use events (like post_dispatch) to count the controller dispatches. Just create an observer attached to it, and store your data in the DB.

Magento _prepareLayout() called 5 times to many

** New EDIT **
so what I'm trying to do is this.
I want the to add new form elements generated by my module on the product view of the following url
http://magento.example.com/catalog/product/view/id/46
ultimately these elements will be determined to show up by a related table in my module
I expected that if I extended Mage_Catalog_Block_Product_View in my module as shown below I would be able to create a block in the product form that would contain such form fields, only if he are in the related table in my module
so I created a test.phtml file in
app/design/frontend/default/default/templates/<module>/test.phtml
then as you can see in my the View.php file described bellow I built the block and displayed it in the product view.
It did appear but 5 times too many. from the answers below this is normal so that answers the question as to why the it shows up five times but leaves the question what is the proper way to proceecd since this plan is not going to work
** End New Edit **
in my module I call _prepareLayout() and it does this 5 times when i pull up the page
here's my code
in
/app/code/local/Namespace/Module/Product/Veiw.php
class <Namespace>_<module>_Block_Product_View extends Mage_Catalog_Block_Product_View {
protected function _toHtml() {
return parent::_toHtml();
}
public function _prepareLayout() {
$block = $this->getLayout()->createBlock(
'Mage_Core_Block_Template',
'my_block_name_here',
array('template' => '<module>/test.phtml')
);
if ($block){
$this->getLayout()->getBlock('content')->insert($block)->toHtml();
}else{
echo "no block";
}
return parent::_prepareLayout();
}
}
NOTE:
I just noticed this also takes away the price availability qty and add to cart button. which is also a problem
EDIT
First I want to thank you all for your answers. Second i want to give you more context
the reason for choosing to do this in the module is that I don't want the block to show up on every product . What i have is a table of what I'll call custom options containing properties of the product sort of like hair color height weight etc and depending on what set of properties are attached to the product (if any) will depend on what html content will show up on the page.
so in one case it my get a drop down menu and in another case it may get an input box. the other very important piece is that this must be setup so that I can give the end result out as a module that can be installed and not worrry that it won't show up if someone upgrades there magento
that said does it still make sense to do this all in the xml file ?
It seems to me that your code is overriding a core Magento module in order to achieve what could be easily done in the layout xml configuration. I would strongly recommend the follwing:
Use the built-in configuration mechanisms (e.g. layout xml - read Alan's excellent tutorial here) instead of writing code whenever possible.
Don't override the core code
if you must change the behaviour of the core code, use an Observer rather than Rewrite/Override
if you absolutely must Override, always call parent::whatever()
For example, if you create a <module>.xml layout file in your theme (app/design/frontend/default/<theme>/layout), you could use the following code:
<catalog_product_view>
<reference name="content">
<block type="module/block" name"my_block_name_here" template="module/test.phtml"/>
</reference>
</catalog_product_view>
You would then need to use a getChildHtml('my_block_name_here'); call within your phtml to position the block.
So unless there is other functionality happening inside your _prepareLayout, there's no need to override the core, or even to override the default catalog.xml.
EDIT (small edit above)
So now in your Block (I would recommend that you call it Namespace_Module_Block_Product_Customattributes or something like that), you are not overriding the core Product_View block, but merely processing your logic for what html widgets to use to render your custom attributes. Leave the rest of the tier prices, add to cart, other generic product block code, etc to Magento to work out.
If you are worried about the upgrade path for your module's users, you should definitely NOT be overriding core code. Use the configuration approach and very selectively introduce code that "plays nice" with the system rather than try to boss it around with overrides.
I took a look at a stock Magento install of CE 1.4.1, and unmodified the _prepareLayout method is called six times when loading the URL
http://magento.example.com/catalog/product/view/id/46
That's because the class is instantiated six times. So that's the correct behavior.
As for the vanishing element, I can'y say for sure, but your override to _prepareLayout doesn't appear to either
Do the same things as Mage_Catalog_Block_Product_View::_prepareLayout
Call parent::_prepareLayout();
When you override a class in a Magento you're replacing an existing class with your own. If you change a method, you're responsible for that old code being run.
It's not clear what you're trying to accomplish here. You should consider breaking your problem down into smaller problems, and then posting one (or more) "I tried X, expected Y, and got Z" type questions. As written no one's going to be able to answer your question.

Resources