Getting Value and Storing data through CK Editor - java

In a form I have a field called Description. Through CKEditor I need to pass that value and store it in my database. Can anyone help me out? Here is my code:
<div id="descriptionMore" style="margin-bottom:20px;margin-top: 38px;margin-left: 101px;">
<aui:layout>
<aui:column columnWidth="240">
<liferay-ui:input-editor width="880" cssClass="richText" />
</aui:column>
</aui:layout>
</div>

First of all, make sure you are using aui:form.
Link which will be useful for you.
Save Content of CKeditor via "aui:form"
Add HTML Editor to Portlet
CK editor in Liferay 6.0
Adding CK Editor in Liferay
This will defiantly be useful for you.

<%
Content content = (Content) request.getAttribute(ApplicationConstants.CONTENT);
%>
<portlet:actionURL var="saveOrUpdateContentUrl" name="saveOrUpdateContent">
<portlet:param name="redirect" value="<%=currentURL%>" />
</portlet:actionURL>
<liferay-ui:header title='<%= (content==null) ? "new-content" : "edit-content" %>' backURL="<%=redirect %>" />
<aui:form method="post" name="content_fm" onSubmit='<%= "event.preventDefault(); " + renderResponse.getNamespace() + "saveEntry();" %>'>
<aui:fieldset>
<aui:field-wrapper label="product-content">
<liferay-ui:input-editor />
<aui:input name="content" id="content" type="hidden" />
</aui:field-wrapper>
<aui:button-row>
<aui:button type="submit" />
</aui:button-row>
</aui:fieldset>
</aui:form>
<script type="text/javascript">
function <portlet:namespace />initEditor() {
return '<%= UnicodeFormatter.toString((content==null)? StringPool.BLANK : content.getContent()) %>';
}
function <portlet:namespace />getContent() {
return window.<portlet:namespace />editor.getHTML();
}
function <portlet:namespace />saveEntry() {
document.<portlet:namespace />content_fm.action = '<%=saveOrUpdateContentUrl%>';
document.<portlet:namespace />content_fm.<portlet:namespace />content.value = <portlet:namespace />getContent();
alert(<portlet:namespace />getContent());
submitForm(document.<portlet:namespace />content_fm);
}
</script>
This above code is properly working in Liferay 6.2. You should fetch CKEditor content using alloy script or javascript and set in hidden parameter for storing the value.

Related

NanoHTTPD unable to process POST parameters

I have downloaded newest NanoHTTPD from link:
https://raw.githubusercontent.com/NanoHttpd/nanohttpd/master/core/src/main/java/fi/iki/elonen/NanoHTTPD.java
When processing very basic POST example, calling session.getParms() returns empty map. My code is:
#Override
public Response serve(IHTTPSession session) {
System.out.println( session.getMethod() + " " + session.getParms() );
return newFixedLengthResponse("Some response.");
}
Which returns:
{}
HTML code triggering nanoHTTPD is:
<html>
<body>
<form action="http://localhost:3388" method="POST">
<input type="text" name="username" value="a" />
<input type="submit" />
</form>
</body>
</html>
That all looks good. Do you see anything suspicious in my code, or just nanoHTTPD is not mature enough?
You should do parseBody before get parameters when you handle a POST request.
In your code, just like this:
#Override
public Response serve(IHTTPSession session) {
session.parseBody(new HashMap<String, String>());
System.out.println( session.getMethod() + " " + session.getParms() );
return newFixedLengthResponse("Some response.");
}
session.parseBody() only needed if you upload one or more files. Your codes are fine except you must provide enctype="multipart/form-data" in your html form tag. So your html code should be:
<html>
<body>
<form action="http://localhost:3388" enctype="multipart/form-data" method="POST">
<input type="text" name="username" value="a" />
<input type="submit" />
</form>
</body>
</html>

Struts2 Repopulate form information when validation fails

I have a page with a form that is prepopulated with user information. It is a user profile page. I have validation for some of the fields in place but currently my validation method is just hard coded to execute addFieldError("exp", "Cats"); where exp is a variable that is being validated and Cats is a random message. The form has selects and a doubleselect which I am repopulating by executing actions in the jsp. (Seen Below)
This is the entire form:
<s:form action="%{formAction}" method="post" enctype="multipart/form-data">
<div id="buttons">
<s:submit value="Save" />
</div>
<div id="left_column" class="divStyle">
<div id="picture">
<div id="picture_border">
Picture should go here 150px x 150px
</div>
<s:file name="upload" label="File" />
</div>
<hr />
<div id="contact" class="divPad">
<h3>Contact Information</h3>
<s:textfield name="email" value="%{profile.email}" required="true" />
</div>
<hr />
<div id="availabilityDuration" class="divPad">
<h3>When Available</h3>
<s:textfield name="whenAvailable" value="%{profile.whenAvailable}" />
<h3>Availability Length</h3>
<s:textfield name="availabilityLength" value="%{profile.availabilityLength}" />
<h3>Desired Credit</h3>
<s:action name="CreditSelectAction" executeResult="true" />
</div>
</div>
<div id="right_column" class="divStyle">
<div id="basic_info" class="divPad">
<h4>College & Major</h4>
<s:action name="CollegeMajorsSelectAction" executeResult="true" />
<hr />
<h4>Years of Work Experience</h4>
<s:action name="ExpYearsSelectAction" executeResult="true" /> <hr />
<h4>Undergrad</h4>
<s:action name="UndergradSelectAction" executeResult="true" /> <hr />
<h4>Graduation Year</h4>
<s:action name="GradYearSelectAction" executeResult="true" />
</div>
<hr />
<div id="aboutDescription" class="divPad">
<h3>About Me</h3>
<s:textarea name="comments" value="%{profile.comments}" cols="40" rows="10" />
</div>
<hr />
<div id="skillsNeeds" class="divPad">
<h3>Skills</h3>
<div id="userSkillList">
<s:iterator value="profile.skills" status="status">
<div>
<h5 class="formLabels">Skill Description</h5>
<s:textfield name="userSkillDescription_%{#status.count}" value="%{description}" />
<h5 class="formLabels">Years of Experience</h5>
<s:textfield name="userSkillExperience_%{#status.count}" value="%{experience}"/>
<h5 class="removeSkillLink" onclick="removeUserSkill(this);">Remove Skill</h5>
</div>
</s:iterator>
<h5 class="addSkillLink" id="addSkill" onclick="addUserSkill();">Add New Skill</h5>
</div>
</div>
</div>
</s:form>
The dropdowns are populating alright. The problem is that the values that I thought would be saved in the value stack and retained upon reloading the jsp (%{formAction}, %{profile.email}, etc.) are not being retained when I reload the jsp. How do I capture these values and present them when the page is reloaded after the failed validation? I have tried adding them to the session, but that tends to get messy and I'm not sure how to get that to work with the formAction.
Code from struts.xml:
<action name="updateProfile" class="profiles.actions.UpdateProfileAction" method="execute">
<!-- <interceptor-ref name="basicStack"/>
<interceptor-ref name="fileUpload">
<param name="allowedTypes">image/jpeg,image/gif,image/png,image/jpg</param>
</interceptor-ref>
<interceptor-ref name="validation"/>
<interceptor-ref name="workflow"/> -->
<result name="success">/index.jsp</result>
<result name="input">/jsp/editProfile.jsp</result>
</action>
Code snippet from the Action that loads the form:
public String execute()
{
// get the user profile
String result = "success";
//If the profile is null, then the user is new and does not yet have a profile
//NOTE: If the user's profile doesn't exist, when trying to view someone else's
//profile, they will be redirected to edit their own.
if(user.intValue() == 0)
{
logger.info("New User Detected. Returning Failure.");
result = "failure";
}
else
{
//If the userid is null, we are loading the user's profile
//Otherwise, we are viewing someone else's profile
if(userid == null)
userid = user.toString();
profile = dao.selectCurUserById(Integer.parseInt(userid));
// get all of my projects
this.setMyProjects(projectDAO.selectMyProjects(Integer.parseInt(userid)));
// get all of the projects i've been invited to
this.setJoinedProjects(projectDAO.selectJoinedProjects(Integer.parseInt(userid)));
}
return result;
}
Code snippet from that Action that updates the user profile:
public String execute()
{
// request that sent from the client
HttpServletRequest request = ServletActionContext.getRequest();
Map<String, Object> session = ActionContext.getContext().getSession();
profile = new UserProfile();
id = ((authentication.beans.User) session.get("currentUser")).getId();
profile.setId(id);
profile.setEmail(email);
profile.setAvailabilityLength(availabilityLength);
profile.setComments(comments);
profile.setUndergrad(Integer.parseInt(undergrad));
profile.setWhenAvailable(whenAvailable);
profile.setYear(year);
profile.setCredit(credit);
profile.setMajor(Major.getMajor(major));
profile.setCollege(College.getCollege(college));
profile.setExp(exp);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy");
profile.setModify(sdf.format(new GregorianCalendar().getTime()));
//If file is not null, then the user is uploading an image for his/her
//profile
if(file != null)
{
byte[] b = new byte[(int) file.length()];
try
{
new FileInputStream(file).read(b);
b = Base64.encode(b);
}
catch (IOException e)
{
// TODO Auto-generated catch block
profile.setComments(profile.getComments() + "\n" + e.getMessage());
}
profile.setPic(b);
}
// get all of the params and then process the user skills
HashMap<String,String[]> params = (HashMap<String,String[]>)request.getParameterMap();
// process the user skills
profile.setSkills(processSkills(params));
// add the userid to the skills
for(int i = 0; i < profile.getSkills().size(); i++){
profile.getSkills().get(i).setUserID(profile.getId());
}
//TODO: Check the result and do error handling
boolean result = dao.updateProfile(profile);
return "success";
}
UPDATE
The problem was pretty much what coding_idiot said. In the action for loading the form, I needed to have getters for the information to initially populate the form (had this). In the action for updating the information, I needed to have setters for the information put into the form AND a getter for where to get the new information if the form should be repopulated after a failed validation. I fixed this by populating the profile object in the validate() function in the update action with the data I got from the form and then providing a setter for the profile object. I did not have to make any changes to my .jsp
I don't know what you've written in your action, but from above I can infer that this is a slight misunderstanding about functionality issue. You are having fields with names - email, whenAvailable etc. but their value is fetched from profile object.
How can you expect to set it from something that doesn't exist ?
To make it more clear :
Values that go from JSP to action is email, but what comes back is profile.email, instead it
should have been just email, or you can simply skip the value attribute or you can change your
field-name to profile.email
Let me know if that helps.
[EDIT]
Reading your question again, the getters and setters for profile won't help, because what
is going into the action is just primitive fields (email etc.) So you should have getters/setters for these fields instead and then to re-populate the fields into the JSP
you can simply use for e.g. :
<s:textfield name="whenAvailable" value="%{whenAvailable}" />
OR
<s:textfield name="whenAvailable"/>

How to change a form value dynamically and submit during onclick

I am using onclick event in anchor tag. when i clcik the anchor, I am invoking a java script function where I change the value of one input element and submit the form. The value is changed but the form does not submit the value. Please help me on this. FYI that if i create an element and add in the form before submission, it works. Why is not working in the first scenario.
<form name="form" >
<input type="hidden" name="input" value="test"/>
<a onclick='testMethod("test")'>click </a>
</form>
script used is
function testMethod(value)
{
if(serviceName != null && jQuery('#form') != null)
{
document.forms['form'].getElementById('input').value = value;
document.forms['form'].action = jQuery('#newAction').val();
document.forms['form'].submit();
}
}
The main problem here is you're trying to access the input by id when it doesn't have one set:
(Added id to form and id to input so we can select them easily):
<form name="form" id="form">
<input type="hidden" name="input" id="input" value="test" />
<a onclick='testMethod("test")' >click</a>
</form>
And the javascript to match (updating to use jQuery's selectors since you indicated you have jQuery support available):
function testMethod(value)
{
var form = $('#form');
if(serviceName != null && form.length)
{
$('#input').val(value);
form.attr('action', $('#newAction').val());
form.submit();
}
}
You can also update your code such that you aren't including the binding to the onclick method in the DOM, but attaching to it directly in javascript:
Changing the a element to have an ID:
<form name="form" id="form">
<input type="hidden" name="input" id="input" value="test" />
<a id="submitLink">click</a>
</form>
The javascript could now look like this:
$(document).ready(function() {
$('#submitLink').on('click', function(event) {
event.preventDefault();
var form = $('#form');
if(serviceName != null && form.length)
{
$('#input').val(value);
form.attr('action', $('#newAction').val());
form.submit();
}
});
});

Liferay doesn't catch form in portlet, and doesn't process

I have .jsp in liferay, and use javascript with applet, but after the form sent to the portlet, on the server side, portlet doesn't catch the form, and do not show in logs additional messages.
jsp page's snippet:
<script type="text/javascript">
function processSigning(){
var applet = document.applets["SignApplet"];
var path_to_certificate = document.getElementById("certificate").value;
var pass = document.getElementById("password").value;
var filePath = document.getElementById("documentSign").value;
applet.filePath = document.getElementById("documentSign").value;
applet.profileTestPKCS12(path_to_certificate, pass);
document.getElementById("file").value = applet.getDocumentString(filePath);
document.getElementById("sign").value = applet.getSignString();
document.getElementById("cert").value = applet.getCertificateString();
document.getElementById("mainForm").submit();
}
</script>
<form id="mainForm" action="<portlet:actionURL>
<portlet:param name="COMMAND" value="LOAD"/>
</portlet:actionURL>">
<hidden id="file" value="asdf"></hidden>
<hidden id="cert" value="asdf"></hidden>
<hidden id="sign" value="asdf"></hidden>
<input type="button" onClick="processSigning();" value="click here!" >
</form>
portlets snippet:
public void processAction(ActionRequest request, ActionResponse response) throws PortletException {
session = request.getPortletSession(true);
String command = request.getParameter("COMMAND");
System.out.println("command=" + command);
log.info("command=" + command);
if ("LOAD".equals(command)) {
{
System.out.println("file");
log.info("file");
String fileBase64 = request.getParameter("file");
System.out.println(request.getParameter("file"));
log.info(request.getParameter("file"));
}
}
}
Check your portlet.xml if the portlet-class is pointing to MVCPortlet or your custom portlet class. It should point to the custom portlet class.
Try this form and see if it works for you:
<portlet:actionURL var="myActionURL"></portlet:actionURL>
<form id="mainForm" action="${myActionURL}" method="post">
<input type="hidden" name="COMMAND" id="COMMAND" value="LOAD" />
<input type="hidden" name="file" id="file" value="asdf" />
<input type="hidden" name="cert" id="cert" value="asdf" />
<input type="hidden" name="sign" id="sign" value="asdf" />
<input type="button" onClick="processSigning();" value="click here!" >
</form>
Hope this helps.
There is method for the form must be specified, because Liferay Portal works with "post" method, also the names of hidden parameters must be used with "name" attribute, because request works with name, not ids

Multiple method calling using single servlet [duplicate]

This question already has answers here:
How do I call a specific Java method on a click/submit event of a specific button in JSP?
(4 answers)
Closed 7 years ago.
I am new to JavaEE and have a query regarding a servlet that has multiple methods.
I want to know how I can call a specific method on a servlet, when I click "Submit" button in JSP.?
Someone have suggested to use HTML hidden fields but I have no idea on how to implement them in Jsp.
You can just give the submit button a specific name.
<input type="submit" name="action1" value="Invoke action 1" />
<input type="submit" name="action2" value="Invoke action 2" />
<input type="submit" name="action3" value="Invoke action 3" />
The name-value pair of the pressed button is available as request parameter the usual way.
if (request.getParameter("action1") != null) {
// Invoke action 1.
}
else if (request.getParameter("action2") != null) {
// Invoke action 2.
}
else if (request.getParameter("action3") != null) {
// Invoke action 3.
}
Hidden fields in a JSP are the same as in HTML:
<input type="hidden" name="name" value="value">
Then in your servlet you can do
if (request.getParameter("name").equals("value")) { /* do something */ }
Depends on which method you want to call. Assuming that the URL Pattern declared for your servlet in web.xml is /myservlet*,
For doGet, just use a URL
http://localhost:8080/myservlet?name=value
For doPost, use a form.
<form action="/myservlet" method="post">
<input type="text" value="value" name="name" />
</form>
i dont think having 3 buttons is the best solution,basis on the logic and parameters method asked,
i believe this can be an accurate solution-
On the basis of parameters passed ,we can have 2 methods to access different actions via javascript-
1)getting values from user,checking them in javascript.
2)getting values from user,checking them in javascript,assigning values to hidden variables accordingly,calling servlets and using those hidden values.i have elaborated method1.
<html>
<head>
<script type="text/javascript">
function nawab() {
param = document.getElementById('param1').value;
alert('in nawab');
if (param != "") {
if (param === 'abc') {
alert('abc');
document.forms[0].action = "nawabServlet";
document.forms[0].submit();
}
if (param === 'def') {
alert('def');
document.forms[0].action = "nawabServlet2";
document.forms[0].submit();
}
}
else{
alert('empty');
document.forms[0].action = "nawabServlet";
document.forms[0].submit();
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>nawab has come</title>
</head>
<body>
<form>
param1:<input type="text" name="param1" id="param1"></select>
<input type="submit" onclick="nawab()">
</form>
</body>
</html>

Categories