how to create action url for hyperlink in liferay? - liferay

i have a requirement that when i click on hyperlink i will send one parameter course id it has to go to action method in portlet class.then i need to display the success and as well as failure message on after operation done on to browser!
public void DeleteCourses(ActionRequest request,ActionResponse response) throws IOException,PortletException
{
String cid=request.getParameter("courseId");
long courseId = Long.parseLong(cid);
try {
CourseLocalServiceUtil.deleteCourse(courseId);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
can any one tell me how to create action url for hyperlink?

You could write it on your JSP like the following:
<portlet:actionURL name="DeleteCourses" var="DeleteCoursesURL">
<portlet:param name="courseId" value="the_course_id"></portlet:param>
</portlet:actionURL>
Delete Course
And Since your portlet class inherits from MVCPortlet the name of the your method DeleteCourses should be the same as the name of the actionURL
You could check a full example here
And for the Success and Error message you could simply use liferay built-in feature for this like that:
<liferay-ui:success key="success" message="Course deleted successfully!" />
And for the errors:
<liferay-ui:error key="error" message="Course could not be deleted" />
You could check an example here

Related

How to do edit, modify , add & save the tags for a particular user

I have a requirement that once user logged in,there will be a page and custom portlet where user can see all the tags assigned to you and user has to edit, modify , add & save the tags.I googled it and tried some of the ways but i didn't get any idea.if anybody knows please guide me to do this.
This functionality already there in User-> My Account ->Categorization. By using below tag we can have a feature to add tags
<liferay-ui:asset-tags-selector />
But at the same time already tags are there in DB by bulk upload. I need to show those tags as pre-populated by using this tag.Then automatically it gives solution for my requirement.
We can do the above requirement by simple three tags as follows.i.e power of liferay.Very awesome!!!
JSP:
<aui:form action="<%=updateTagsURL%>" method="post"
name="updateTagsForm">
<aui:model-context bean="<%=user%>" model="<%=User.class%>" />
<h3>
<liferay-ui:message key="tags" />
</h3>
<aui:fieldset>
<aui:input name="" type="assetTags" label="" />
</aui:fieldset>
<aui:input type="Submit" name="" value="Submit" lable=""></aui:input>
</aui:form>
Action Class:
public void addTags(ThemeDisplay themeDisplay,String emailAddress,String[] tagNames){
User user;
try {
user = UserLocalServiceUtil.getUserByEmailAddress(themeDisplay.getCompanyId(), emailAddress);
AssetEntryLocalServiceUtil.updateEntry(user.getUserId(), themeDisplay.getScopeGroupId(),"com.liferay.portal.model.User", user.getUserId(),null, tagNames);
} catch (PortalException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Show error and change doneLabel of rich:fileUpload in upload listener method

I have to upload CSV file and I have to validate some values of file, for example does not allow negative value. Then, I need validate it and that file does not apear like "done" or "uploaded". I need handle an error on display it.
<rich:fileUpload
fileUploadListener="#{configClientBean.listener}"
ontyperejected="alert('some error');"
maxFilesQuantity="1"
onuploadcomplete="#{rich:component('waitPanelInterno')}.hide();"
onfilesubmit="#{rich:component('waitPanelInterno')}.show();"
render="pnlMensajes, idTableClients, scrollRegistros, outputPanelDetalle"
autoclear="true">
<rich:message for="uploadConfigClient" />
<a4j:ajax event="uploadcomplete" execute="popupFileLoad"
render="panelCarga, pnlMensajes" />
</rich:fileUpload>
In the Backing bean I can validate some things, but I cant show errors or change the behavior of "rich:fileUpload" compoment for example doneLable can not be displayed.
public void listener(FileUploadEvent event) throws Exception {
try {
UploadedFile file = event.getUploadedFile();
ByteArrayInputStream bais = new ByteArrayInputStream(file.getData());
InputStreamReader is = new InputStreamReader(bais, getMessage("iso"));
BufferedReader bufRead = new BufferedReader(is);
while ((registro = bufRead.readLine()) != null) {
if(cvsLine[1].isEmpty()){
// stop process
// Throw error
}
}
}
Thanks for your time.
To add extra behavior to the rich:fileUpload component that is not default is by creating your own file upload component (ex. myown:fileUpload) based on the rich:fileUpload source code and the use of the Component Development Kit.
A second solution could be by adding one extra message field that is described in this post: RichFaces fileupload and h:message problem

Navigate after successfull action on commandButton

I am building a JSF application using Primefaces mobile (0.9.3 with Primefaces 3.5).
I hava a login page, on this login page there is a login button defined as followed:
<p:commandButton value="#{msg['label.login']}" action="#{loginBean.login}" update="usernameMsg" />
The loginBean.login method is defined as followed:
public String login() {
try {
//do login
return "#loggedInTarget?transition=fade";
} catch (UserNotValidException e) {
//User not valid, display exception
FacesContext
.getCurrentInstance()
.addMessage(
"loginForm:username",
new FacesMessage(
FacesMessage.SEVERITY_ERROR,
"",
messageService
.getMessage("error.message.loginNotSuccessfull")));
}
return null;
}
In my main xhtml (the same in which the button is defined), I have defined the following addtional views:
<pm:view id="registerTarget">
<ui:include
src="/WEB-INF/c52bc19d58a64ae4bd12dec187a2d4b7/register.xhtml" />
</pm:view>
<pm:view id="loggedInTarget">
TEST
</pm:view>
I do it that way because I want to use transitions within Primefaces mobile. To get to the register page I use a p:button which works fine:
<p:button value="#{msg['label.register']}"
href="#registerTarget?transition=fade" />
Why is my login button not working? I also tried to put in "#loggedInTarget?transition=fade" directly as action, but this didn't work either :(
I need the action, because I have to check if the user credentials are valid. If they are valid I want to display my loggedInTarget.
How can I achieve it?
Thanks in advance!
EDIT:
The button is inside a form.
The navigation case outcome value must represent a view ID, not an URL (for sure not a hash fragment). Try with <p:button outcome="...">, and you'll see that it fails over there as well.
Your closest bet is sending a redirect.
public void login() throws IOException {
// ...
externalContext.redirect("#loggedInTarget?transition=fade");
// ...
}
This is also exactly what the <p:button href="..."> does under the covers: causing a GET request on the given URL.

AdxStudio CrmEntityFormView Swallowing Microsoft.Xrm.Sdk.SaveChangesException

I posted this on the AdxStudio forum and got exactly zero response, so I'm hoping ya'll can help me debug this.
I'm using a CrmEntityFormView to create a new contact in CRM, like so:
<adx:CrmDataSource ID="FormViewDataSource" runat="server" />
<adx:CrmEntityFormView runat="server" ID="UserCreateForm" EntityName="contact" FormName="User Edit Form" DataSourceID="FormViewDataSource"
RecommendedFieldsRequired="true" ValidationGroup="NewUser" ValidationText="* This field is required" EnableValidationSummaryLinks="false"
OnItemInserting="UserCreateForm_ItemInserting" OnItemInserted="UserCreateForm_ItemInserted">
<InsertItemTemplate></InsertItemTemplate>
</adx:CrmEntityFormView>
<asp:Button ID="SubmitButton" Text='Create User' CssClass="button" ValidationGroup="NewUser" runat="server" OnClick="SubmitButton_Click" />
I'm using the SubmitButton_Click handler to handle some other fields on the form at the same time like so:
protected void SubmitButton_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
{
return;
}
# Handle other form fields not on the FormView ...
UserCreateForm.InsertItem();
}
Nothing happens in my database when I submit a valid form. So I debugged the ItemInserted event, putting a breakpoint on the single line of the handler
protected void UserCreateForm_ItemInserted(object sender, CrmEntityFormViewInsertedEventArgs e)
{
Contact newUser = XrmContext.ContactSet.Where(c => c.ContactId == e.EntityId).FirstOrDefault();
}
Turns out, in this event, e.Exception is not null, but an instance of the SaveChangesException from the title, with the message "An error occured while processing this request." and e.ExceptionHandled == true, which I guess is why I never saw anything.
This exception has an InnerException, an instance of System.ServiceModel.FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>
with a message that always just contains the submitted value of the first field in the FormView. I have absolutely no idea why this isn't working, and I'm unclear how to debug this further and can use some pointers.
The System.ServiceModel.FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> eats the stack trace. Refer to this blog as a method to actually log the stacktrace to be able to find where your error is occurring.

How to set the exception message in a <h:message>?

I am trying to set an exception message in the <h:message>.
Here is the relevant view code:
<h:inputText id="titleId" value="#{bookController.book.title}"/>
<h:message for="titleId"/>
<h:commandButton value="Create a book" actionListener="#{bookController.doCreateBook}" action="listBooks"/>
I need a message to be displayed when the titleId is empty. My #Stateless EJB method throws an exception when the title is empty:
public Book createBook(Book book) throws CustomException {
if(book.getTitle().isEmpty()) {
throw new CustomException("Please, type a Title !");
}
else {
em.persist(book);
return book;
}
}
My backing bean catches it and sets a message:
public void doCreateBook() {
FacesContext ctx = FacesContext.getCurrentInstance();
try {
book = bookEJB.createBook(book);
bookList = bookEJB.findBooks();
} catch (CustomException e) {
ctx.addMessage("titleId", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", e.getMessage()));
}
}
What I except is, when the exception occurs, an error message must be displayed near the input text tag, but it isn't the case, the execution displays the page with list of books and the "Error" message displayed under the list, as shown below:
How can I get the full exception message to show up next to the input field?
Apart from the erroneous message handling which Thinksteep has already answered, your other mistake is that you're doing validation in an action method. This is not right. You should be using JSF builtin validation facilities instead. Whenever the JSF builtin validation fails, then the action method will not be invoked and the page will also not navigate. The enduser sticks to the current form and the message will appear in the therefor specified <h:message> tag.
In your particular case, you just need to set the required attribute.
<h:inputText id="titleId" value="#{bookController.book.title}" required="true" />
<h:message for="titleId" />
If you want to customize the default required message, use requiredMessage attribute.
<h:inputText id="titleId" value="#{bookController.book.title}"
required="true" requiredMessage="Please, type a Title !" />
<h:message for="titleId" />
Remove that input validation from the EJB method. It doesn't belong there. The EJB isn't responsible for that, the caller (which is in your case thus your JSF code) is responsible for that.
ctx.addMessage("titleId", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", e.getMessage()));
Your message text is Error and you are getting same. Change "Error" here to what ever you want.
PUT <h:messages showDetail="true" />

Resources