How to get client side portlet-id in liferay? - liferay

I'm using AlloyUI in my liferay portlet.
I want to use my <input>'s id in javascript. The problem is that the id of the elements are changed in client side.
For example:
If I set an <input>'s Id to "username" it is changed to _hospital_WAR_hospitalportlet_userName i.e. _hospital_WAR_hospitalportlet_ is appended to the Id, where Hospital is my portlet name.
How can I get client-side Id so that I can use it in jquery?

The string _hospital_WAR_hospitalportlet_ prepended to the Id of the <input> is nothing but the portlet-namespace.
This is only prepended to your <input>'s name & id attribute if you use <aui:input> tag and the name & id attributes are not changed if you just use plain-vanilla html <input> tag.
But as it is a good practice to use <aui:input> you can do the following to get the portlet-namespace in your javascript code:
If you are using javascripts inside a JSP i.e. using within <script> .. </script> or <aui:script> .. </aui:script> then you can use <portlet:namespace /> or <%= renderResponse.getNamespace() %> to get the string _hospital_WAR_hospitalportlet_ inside your javascript, something like.
jQuery("#<portlet:namespace />username").val();
// Or
jQuery("#<%= renderResponse.getNamespace() %>username").val();
But if you are using a *.js file then I suggest you pass the namespace as an argument to the javascript function in the js file:
function changeValues(portletNamespace) { // this function is in a js file
jQuery("#" + portletNamespace + "username").val("Lets change");
}
calling this function from the JSP:
<input type="button" onClick="changeValues('<portlet:namespace />')" />
Hope this helps. I don't know if there is a way to get the namespace or portletId directly through some javascript function defined by Liferay. If you get something like that you can post it here and that would be very helpful.

Try this:
Liferay.Portlet.ready(
/*
This function gets loaded after each and every portlet on the page.
portletId: the current portlet's id
node: the Alloy Node object of the current portlet
*/
function(portletId, node) {
}
);

Related

Shopware6 Loading options from twig template to Js plugin

I have been following https://developer.shopware.com/docs/guides/plugins/plugins/storefront/add-custom-javascript to create a javascript plugin. But, I am struggling with adding options through twig template. I have something like the following:
Twig file : product.html.twig:
{% set contentModalOptions = {
cmsContentId: "some-hash",
navigationUrl: path('frontend.cms.page'),
failSafeRedirectUrl: '/some-failsafe-url/'
} %}
<div>
<a target="_self" href="#" data-content-modal="true" data-content-modal-options="{{ contentModalOptions|json_encode|escape('html_attr') }}">
help text
</a>
</div>
plugin file : custom-plugin.js:
import Plugin from 'src/plugin-system/plugin.class';
export default class ContentModalPlugin extends Plugin {
static options = {
cmsContentId: '',
navigationUrl: '',
failSafeRedirectUrl: ''
};
init() {
console.log(this);
console.log(this.options); // empty values
}
}
Notes:
In the browser, I see that values set using twig as the HTML attribute.
Plugin has been registered and works with the template.
console.log() in the plugin doesn't print any values that are set from twig. It just shows the options object that has been initialized in the plugin.
Any help is appreciated.
I assume you register the plugin like this:
PluginManager.register('ContentModal', ContentModalPlugin, '[data-content-modal]');
Within the constructor of the Plugin class this.options = this._mergeOptions(options); should then called, which in turn parses the data-${dashedPluginName}-options attribute. It should throw an error if it can't parse the json:
`The data attribute "data-${dashedPluginName}-options" could not be parsed to json: ${e.message}`
Are the any errors when you look at the console of your browsers dev tools?
For further debugging you could also try calling super._mergeOptions(this.options); from your init method.
Now, I see what the problem was. When I registered my plugin, I had the following:
PluginManager.register('ContentModalPlugin', ContentModalPlugin, '[data-content-modal]');
So, I tried passing the options with data-content-modal-options attribute through twig but it seems that the resolved plugin name in _mergeOptions() at src/plugin-system/plugin.class takes the plugin name (i.e the string that is the first argument of the register function) and not the attribute definition in the register method.
So, adding a html attribute as data-content-modal-plugin-options based on my class name resolved the problem.

Add querystring to "asp-page" link in CORE razor pages

In CORE razor pages
<a asp-page="View" asp-route-ID="#item.ID" >View</a>
this creates a link to a page using a route to pass the ID and generates the following HTML
View
I want to add the contents of the querystring to this link so the generated HTML looks like
View
#Request.QueryString gets the entire querystring e.g. "?s=smith" but I can't find the way to add it to the end.
Any ideas.
This works for me (from https://www.learnrazorpages.com/razor-pages/tag-helpers/anchor-tag-helper):
<a asp-area="Identity" asp-page="/Account/Register" asp-route-view="personal">Text</a>
This routes you to: Identity/Account/Register?view=personal.
In "asp-route-view", the view can be anythin you need:
<a asp-area="Identity" asp-page="/Account/Register" asp-route-disco="party">Text</a>
routes you to Identity/Account/Register?disco=party.
Example Url :
https://localhost:44313/dados_pessoais?userid=1
Use: asp-route-youproperty="value"
Get user data sample
<a class="nav-link text-dark" asp-area="" asp-page="/dados_pessoais" asp-route-userid="1">Dados Pessoais</a>
c#
public void OnGet(int userid)
{
var usuario = Usuarios.Where(u => u.Id == userid).FirstOrDefault();
}
The asp router tag helpers will ensure the target page matches the format specified but assuming it does you can do something like the following:
<a asp-page="View" asp-route-ID="#item.ID" asp-route-s="#Request.Query["s"].ToString()">View</a>
The Request Query property can be used to access individual querystring parameters by name.

jsf render components with js

Let's say I have
<p:outputPanel/>
What I want to do is to specify rendered attr using js method not serverside.
This is for improving performance.
So I need something like :
<p:outputPanel rendered = "someJsFunction()"/>
What is the solution?
rendered propery is processed at server side and if it resolves to false, the element is not added into the html document. So javascript can't even find the element to display or hide because it is not created.
The only thing you can do is to remove the rendered property and change the display property of the element with javascript.
<div id="myDiv">My Content</div>
<button onclick="myFunction()">Click Me</button>
<script>
function myFunction() {
document.getElementById("myDIV").style.display = "none";
}
</script>
Well, you can have the same effect at page load cause rendered attribute is resolved at Server Side only , So using jQuery you can do it like
$(document).ready(function() {
document.getElementById("YourPanelIdHere").style.display = "none";
});
and it will be not displayed.

liferay change page title dynamically

I'm trying to change the title of the page, but the method PortalUtil.setPageTitle("title", request); is not working from the jsp. I also tried in the doView method.
My second attempt was throught servletrequest:
In doView I wrote
HttpServletRequest httpRequest = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(renderRequest));
httpRequest.setAttribute("hola", "hola");
And in the portal normal I tried with:
#set ($holas =$request.get('attributes').get('hola'))
#set ($holas2 = $request.getSession().getAttribute("hola"))
$holas
$holas2
but Velocity only shows $holas $holas2.
Looks like I got it wrong in my first attempt - thus I've replaced the previous answer with this one: Add this code to your JSP or doView:
<%
com.liferay.portal.util.PortalUtil.setPageTitle("Honk", request);
%>
In your jsp you should try
<%
layout.setTitle("title");
%>
layout is an Layout object generated by jsp.
Use below code,
String title = (String)renderRequest.getAttribute("title");
HtmlPageTitleUtil.setHtmlTitle(title, request, true);
Pass title attribute from the controller or you can use static text as well.
Import the above utility class as well as,
<portlet:defineObjects />
<theme:defineObjects />
this to jsp and its done.

How do you post data to CouchDB both with and without using JavaScript

I have a show which displays a form with fields populated from a document. I'd like to change the values in the field and then save the updated document.
I'm having trouble finding a clear, concise example of how to do this.
Seriously, just finishing this example would work wonders for so many people (I'm going to leave a lot of stuff out to make this concise).
Install Couchapp
This is outside the scope of my question, but here are the instructions for completeness.
Create a couchapp
Again, this is kind outside the scope of my question. Here is a perfectly concise tutorial on how to create a couchapp.
Create a template
Create a folder in the root of your couchapp called templates. Within the templates folder create an HTML page called myname.html. Put the following in it.
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<form method='post' action='#'>
<fieldset>
Hello <input type='text' name='name' value='{{ name }}'>
<input type='submit' name='submit' value='submit'>
</form>
</body>
</html>
Create a show
See the tutorial above for hwo to do this.
Add this code to a show called myname.
function(doc, req) {
if (doc) {
var ddoc = this
var Mustache = require("vendor/couchapp/lib/mustache");
var data = {
title: "The Name",
name: "Bobbert"
}
return Mustache.to_html(ddoc.templates.myname, data)
} else {
return ('nothing here baby')
}
}
Update the document with a new name by ...
So who can complete this step via both the client side and the server side?
Please don't point me to the guide, I need to read it in your words.
Thanks.
Edit:
Although the return value isn't pretty, just posting a form to the update handler will update the document.
You will probably want to look into update handler functions.
An update handler handles granular document transformations. So you can take 1 form, that has one distinct purpose, and only update the relevant fields in your document via the update handler.
Your update handler will need to take a PUT request from your form. A browser can't do this directly, so you'll need some javascript to handle this for you. If you're using jQuery, this plugin can take your form and submit it seamlessly via AJAX using PUT for you.
Inside the function, you can take the fields you are accepting, in this case name and apply that directly to the document. (input validation can be handled via the validate_doc_update function)
Update Handler (in your Design Document)
{
"updates": {
"name": function (doc, req) {
doc.name = req.form.name;
return [doc, "Name has been updated"];
}
}
}
HTML
<form id="myForm" action="/db/_design/ddoc/_update/name/doc_id">...</form>
JavaScript
$(document).ready(function() {
$('#myForm').ajaxForm({
type: "PUT",
success: function () {
alert("Thank you");
}
});
});
Once you've gotten this basic example up and running, it's not much more difficult to add some more advanced features to your update handlers. :)

Resources