Liferay instanceable portlet does not work properly - liferay

I created a custom instanceable portlet, setting the instanceable property to true:
<portlet>
<portlet-name>portletFiltriPTF</portlet-name>
<instanceable>true</instanceable>
<header-portlet-javascript>/js/mediolanumadvice/portletFiltriPTF.js</header-portlet-javascript>
</portlet>
The problem is that I am able to insert the portlet multiple times inside the same page, but only in one of that the content is visible, as you can see in the following image:
Is there anything that I have to do in addition to set that property?
Thank you all,
Marco

Two things to check:
You might have a portlet on page that's (still) non-instanceable because you've added it before you've made your portlet instanceable. They now have different IDs and need to be removed from the page
You might use IDs that are conflicting - e.g. if both portlets create content with the same ID, they'll end up in the DOM. Use these for formatting or any treatment through JS and weird things happen.

I'm not sure if this will help the original poster, but in case anyone else comes across this...
My project is using React and we mount our React root to an element with a static id, referred to as the html root, in index.jsp.
When you try to instantiate multiple instances of the same portlet on one page, subsequent instances will not render because there are multiple elements with the same id.
The solution for this is to create an instance id of your own and create a new element to replace the html root, so that the html root becomes something of a placeholder. Since the html element is removed every time you add a portlet instance, you can reliably mount your React root multiple times without issue.
Here you can see a util I wrote to create a unique root and replace the placeholder (I call it RootUtil):
export default {
makeId: function(length) {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < length; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
},
renderRoot: function(placeholderId) {
// create unique id
var instanceId = this.makeId(10);
var id = "react-root-instance-" + instanceId;
// create unique root
var root = document.createElement("div");
root.setAttribute("id", id);
// find placeholder
const placeholder = document.getElementById(placeholderId);
// replace placeholder
//placeholder.replaceWith(root); **breaks in IE**
placeholder.parentElement.replaceChild(root, placeholder); //workaround
// return the new element
return document.getElementById(id);
}}
And I call it here:
ReactDOM.render(
<Provider store={Store}>
<div>
...
</div>
</Provider>,
RootUtil.renderRoot("html-root"));

Related

Orchard CMS - Extending Users with Fields - exposing values in Blog Post

I'd like to extend the users content definition to include a short bio and picture that can be viewed on every blog post of an existing blog. I'm unsure of what the best method to do this is.
I have tried extending the User content type with those fields, but I can't seem to see them in the Model using the shape tracing tool on the front end.
Is there a way to pass through fields on the User shape in a blog post? If so, what is the best way to do it?
I also have done this a lot, and always include some custom functionality to achieve this.
There is a way to do this OOTB, but it's not the best IMO. You always have the 'Owner' property on the CommonPart of any content item, so in your blogpost view you can do this:
#{
var owner = Model.ContentItem.CommonPart.Owner;
}
<!-- This automatically builds anything that is attached to the user, except for what's in the UserPart (email, username, ..) -->
<h4>#owner.UserName</h4>
#Display(BuildDisplay((IUser) owner))
<!-- Or, with specific properties: -->
<h1>#T("Author:")</h1>
<h4>#owner.UserName</h4>
<label>#T("Biography")</label>
<p>
#Html.Raw(owner.BodyPart.Text)
</p>
<!-- <owner content item>.<Part with the image field>.<Name of the image field>.FirstMediaUrl (assuming you use MediaLibraryPickerField) -->
<img src="#owner.User.Image.FirstMediaUrl" />
What I often do though is creating a custom driver for this, so you can make use of placement.info and follow the orchard's best practices:
CommonPartDriver:
public class CommonPartDriver : ContentPartDriver<CommonPart> {
protected override DriverResult Display(CommonPart part, string displayType, dynamic shapeHelper) {
return ContentShape("Parts_Common_Owner", () => {
if (part.Owner == null)
return null;
var ownerShape = _contentManager.BuildDisplay(part.Owner);
return shapeHelper.Parts_Common_Owner(Owner: part.Owner, OwnerShape: ownerShape);
});
}
}
Views/Parts.Common.Owner.cshtml:
<h1>#T("Author")</h1>
<h3>#Model.Owner.UserName</h3>
#Display(Model.OwnerShape)
Placement.info:
<Placement>
<!-- Place in aside second zone -->
<Place Parts_Common_Owner="/AsideSecond:before" />
</Placement>
IMHO the best way to have a simple extension on an Orchard user, is to create a ContentPart, e.g. "UserExtensions", and attach it to the Orchard user.
This UserExtensions part can then hold your fields, etc.
This way, your extensions are clearly separated from the core user.
To access this part and its fields in the front-end, just add an alternate for the particular view you want to override.
Is there a way to pass through fields on the User shape in a blog post?
Do you want to display a nice picture / vita / whatever of the blog posts author? If so:
This could be your Content-BlogPost.Detail.cshtml - Alternate
#using Orchard.Blogs.Models
#using Orchard.MediaLibrary.Fields
#using Orchard.Users.Models
#using Orchard.Utility.Extensions
#{
// Standard Orchard stuff here...
if ( Model.Title != null )
{
Layout.Title = Model.Title;
}
Model.Classes.Add("content-item");
var contentTypeClassName = ( (string)Model.ContentItem.ContentType ).HtmlClassify();
Model.Classes.Add(contentTypeClassName);
var tag = Tag(Model, "article");
// And here we go:
// Get the blogPost
var blogPostPart = (BlogPostPart)Model.ContentItem.BlogPostPart;
// Either access the creator directly
var blogPostAuthor = blogPostPart.Creator;
// Or go this way
var blogPostAuthorAsUserPart = ( (dynamic)blogPostPart.ContentItem ).UserPart as UserPart;
// Access your UserExtensions part
var userExtensions = ( (dynamic)blogPostAuthor.ContentItem ).UserExtensions;
// profit
var profilePicture = (MediaLibraryPickerField)userExtensions.ProfilePicture;
}
#tag.StartElement
<header>
#Display(Model.Header)
#if ( Model.Meta != null )
{
<div class="metadata">
#Display(Model.Meta)
</div>
}
<div class="author">
<img src="#profilePicture.FirstMediaUrl"/>
</div>
</header>
#Display(Model.Content)
#if ( Model.Footer != null )
{
<footer>
#Display(Model.Footer)
</footer>
}
#tag.EndElement
Hope this helps, here's the proof:

Customize the quick launch items for certain pages in sharepoint

I have requirement where client wants to customize the items in quick launch for only certain
pages.So, I want to change the items in the quick launch with some other items for a few pages.(Not about cahnging the style of quick launch. Its about the replacingthe content in quick launch)
I hope using CEWP, I can achive this.But I am not much aware how to do it.
You can have two approachs here:
1) creating a webpart to replace the quicklaunch: This way you can read the Navigation from SPWeb, and build it your own.
2) Using jQuery to change the html loading the page. In this approach, I would apply a 'display:none' to quicklaunch, make the changes in html, and then 'display:block' back. The con in this solution is that you must rely on the names/titles/urls of the items, so if an admin changes, it could break it.
I had followed following steps to achive the goal
1.. Added a CEWP in the page
Created a text file with Following script and added it to shared dcouments
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function startClock(){
var div= document.getElementById('s4-leftpanel-content');
var spans= div.getElementsByTagName('span');
for (index = spans.length - 1; index >= 0; index--) {
spans[index].parentNode.removeChild(spans[index]);
}
var urls= div.getElementsByTagName('a');
for (index = urls.length - 1; index >= 0; index--) {
urls[index].parentNode.removeChild(urls[index]);
}
var pTag = document.createElement('p');
pTag.innerHTML = "HR Report";
div.appendChild(pTag);
var aTag = document.createElement('ul');
div.appendChild(aTag);
var newLi = document.createElement('li');
aTag.appendChild(newLi);
var a= document.createElement('a');
a.setAttribute('href',"url");
a.innerHTML = "report2";
newLi.appendChild(a);
//do onload work
}
if(window.addEventListener){
window.addEventListener('load',startClock,false); //W3C
}
else{
window.attachEvent('onload',startClock); //IE
}
</script>
enter code here
Paste the url text file in shared documents in CEWP as content link(Edit web part >>content link>>paste url)
Now, existing items in the Quick Launch is removed and new items are added

Marionette, how to change view's template on fly

I'm doing a single page webApp with Marionette and RequireJs, basically it is a Layout view nested with a lots of ItemView and compositeView. I want the page change to a new design by one click, so I want to ask a best practice about changing the view's template.
say, I got my view like this, and its templates are included by requirejs's text plugin:
define([
'text!templates/designNo1/template.html'
], function(template) {
var MyView = Backbone.Marionette.ItemView.extend({
/*Template*/
template: template,
initialize: function() {
......
},
onRender: function() {
......
}
});
return SkillView;
});
every view and theirs subviews are defined like this. and their templates located in "template/designNo1" folder. now I got a set of new design located in "template/designNo2", and I want apply it to the page, but I found there is no chance to do this, because the views are already loaded by RequireJs and the template's path are hard-coded. of course, I can override the view's template when create the view's instance, but if I do so, I must load all the new design in the upper-module which create the instance, that looks bad, and the new design are keep coming, it gonna be a mess soon.
so, any advice?
From what I can tell, it sounds like you are wanting to change the template on a view depending on different circumstances. Marionette's ItemView has a getTemplate() function that is called when rendering it. You can specify a function that determines which template to render from there.
Another approach might be to simply change the template of the view and re-render it. You could do that on a click event easily:
HTML
<div class="content"></div>
<button class="btn">Change Template</button>
Javascript
var template1 = '<div>Template 1</div>';
var template2 = '<div>Template 2</div>';
var ItemView = Backbone.Marionette.ItemView.extend({
template: template1
});
var itemView = new ItemView({ el: '.content' });
itemView.render();
$('.btn').click(function(e) {
e.preventDefault();
itemView.template = template2;
itemView.render();
});

Accessing HTML controls inside iFrame

How do you access html controls inside an iframe from javascript in CRM?
I have:
var height = document.getElementById("IFRAME_TransactionProduct_RA").contentWindow.document.getElementById("txt").value;
but that results in "Error on page" and the content is not loaded.
The element I want to access is an html input with id of 'txt':
<input id="txt" type="hidden" />
Here's an example how you copy a value from a CRM field to a control in an embedded HTML control in an IFRAME. I'm assuming the names of the web resource and the field. You'll have to adapt those. You also might throw in a try-catch in case CRM throws in en exception (got the joke?) and please mind that I'm typing the code on my phone so there might be a typo somewhere (auto-correction, yey).
var source = Xrm.Page.data.entity.attributes.get("oneCoolField")
var information = source.getValue();
var customHtml = Xrm.Page.ui.controls.get("WebResource_EmbeddedHtmlContent");
var destination = customHtml.getObject().contentWindow.document;
if(destination) {
var customControl = destination.getElementById("elementToAccess");
if(customControl) {
customControl.value = information;
}
}
EDIT:
This gets you to the web resource.
var customHtml = Xrm.Page.ui.controls.get("WebResource_EmbeddedHtmlContent");
This gets you to the DOM of the IFRAME.
var destination = customHtml.getObject().contentWindow.document;
This gets you to the control on the custom page.
var customControl = destination.getElementById("elementToAccess");
This gets you the contents of the control.
var contents = customControl.innerHTML;
Which part fails on your computer?
With jQuery:
$(Xrm.Page.ui.controls.get('IFRAME_TransactionProduct_RA').getObject()).contents().find('#txt').val();
Pure JS:
Xrm.Page.ui.controls.get('IFRAME_TransactionProduct_RA').getObject().contentWindow.document.getElementById('txt').value;
http://msdn.microsoft.com/en-us/library/gg334266.aspx#BKMK_getObject

How to extend Orchard navigation module to add images to menu items

UPDATE: I've changed the original question drastically based on Bertrand's suggestions and my own findings. Now it provides an incomplete solution in its text instead of my own blind meanderings and commentary on Orchard, which were completely WRONG!
I need to display a menu using images instead of text, one standard, and another for when hovered/selected. The requirements for the site states that the end-user should be able to manage the menu item images. The standard navigation module now provides an HTML menu item, which is not what the end user wants. The customer wants a very simple, intuitive interface for configuring the sites many menus, and all menus are image-based.
Based on Bertrand's advice, and after realizing that Content Menu Item IS A CONTENT TYPE, I've created a new Content Part in the Admin Interface (not by code, I only want to write code for parts and content types when ultimately needed... I really want to see how far I can go with Orchard just by using the admin interface and templating/CSSing).
So, I've created a Menu Image Part, with two Content Picker fields added to it: Image and Hover Image. Then I've added this part to the Content Menu Item in the Manage Content Items admin interface.
Since I didn't write a Driver for it, the Model passed to the menu item template does not have an easily accessible property like #Model.Href... I've overriden the MenuItemLink-ContentMenuItem.cshtml with the following code so far:
#using Orchard.Core.Common.Models
#using Orchard.ContentManagement
#{
var contentManager = WorkContext.Resolve<IContentManager>();
var itemId = Model.Content.ContentItem.ContentMenuItemPart.Id;
ContentItem contentItem = contentManager.Get(itemId);
ContentField temp = null;
var menuImagePart = contentItem.Parts.FirstOrDefault(p => p.PartDefinition.Name == "MenuImagePart");
if (menuImagePart != null)
{
temp = menuImagePart.Fields.First();
}
}
<span>#temp</span>
#Model.Text
This yields the expected title for the Menu in a link, with a span before it with the following text:
Orchard.Fields.Fields.MediaPickerField
So all the above code (get the current content manager and the id of the ContentItem representing the ContentMenuItemPart, then use the content manager to get ContentItem itself, then linqing over its Parts to find the MenuImagePart (I can't use Get to get it because it requires a type and the MenuImagePart is not a type, it was created in the admin interface), then finally getting the first field for debugging purposes (this should be the Image field of the MenuImagePart I've created...)... all the above code actually got me to the Media Picker Field on my Meny Image Part...
What I'm not being able to do, and what makes me certainly a lot obtuse and stupid, is to find a way to read the MediaPickerField URL property! I've tried casting it to MediaPickerField, but I can't access its namespace from inside my template code above. I don't even know which reference to add to my theme to be able to add the following directive to it:
#using Orchard.Fields.Fields
I've finally succeeded in this task (thanks to Bertrand's direction).
UPDATE: And thanks again to Bertrand I've polished the solution which was running in circles, querying content items from the content manager when they were already available on the Model... now I'm leveraging the dynamic nature of content item, etc. And I'm finally satisfied with this solution.
It was necessary to create a new Content Part called Menu Image, then add this to the Content Type named Content Item Menu, and finally overriding the Content Item Menu template. This last part was the really tricky one. If it was not for Bertrand's directions the code bellow would have been smelly and daunting. The template ended up as follow:
#using Orchard.Utility.Extensions;
#using System.Dynamic
#{
/* Getting the menu content item
***************************************************************/
var menu = Model.Content.ContentItem;
/* Creating a unique CSS class name based on the menu item
***************************************************************/
// !!! for some reason the following code throws: 'string' does not contain a definition for 'HtmlClassify'
//string test = menu.ContentType.HtmlClassify();
string cssPrefix = Orchard.Utility.Extensions.StringExtensions.HtmlClassify(menu.ContentType);
var uniqueCSSClassName = cssPrefix + '-' + Model.Menu.MenuName;
/* Adds the normal and hovered styles to the html if any
***************************************************************/
if (menu.MenuImagePart != null)
{
if (!string.IsNullOrWhiteSpace(menu.MenuImagePart.Image.Url))
{
using(Script.Head()){
<style>
.#uniqueCSSClassName {
background-image: url('#Href(menu.MenuImagePart.Image.Url)');
width: #{#menu.MenuImagePart.Image.Width}px;
height: #{#menu.MenuImagePart.Image.Height}px;
display: block;
}
</style>
}
}
if (!string.IsNullOrWhiteSpace(menu.MenuImagePart.HoverImage.Url))
{
using(Script.Head()){
<style>
.#uniqueCSSClassName:hover {
background-image: url('#Href(menu.MenuImagePart.HoverImage.Url)');
width: #{#menu.MenuImagePart.HoverImage.Width}px;
height: #{#menu.MenuImagePart.HoverImage.Height}px;
}
</style>
}
}
}
}
<a class="#uniqueCSSClassName" href="#Model.Href">#Model.Text</a>
The only thing that I didn't understand is why I can't use HtmlClassify as an extension method with menu.ContentItem.HtmlClassify() and have to resort to calling the method as a standard static method (see the line with the comment `// !!! for some reason the following code throws´...)
Thanks again Bertrand!

Resources