How to clear all the md-input fields at once inside a md-form using an external button in Angular 2/2+/4 - material-design

I want to clear all the fields inside a md-form at once using an external clear button like you do in normal HTML Forms. The problem with md-form is that it contains md-input fields instead of regular input fields. So the simple reset function won't trigger that.
I've set the type of each field to 'search' that gives some kind of control but it's like u have to manually click and remove each value of the filed. I want to erase them all at once.
Is there a proper way to to this?
Thanks in advance.
Form Code
<form class="formwidth" (ngSubmit)="searchClass()" #myForm="ngForm">
<table class="fullwidth" cellspacing="0">
<tr>
<td>
</td>
<td>
<md-input-container div="addClassName" *ngIf="classClicked === true">
<input [(ngModel)]="message.className" mdInput placeholder="Class Name" id="className" name="classname" type="search" >
</md-input-container>
<md-input-container div="addJarName" *ngIf="jarFileClicked === true">
<input [(ngModel)]="message.jarName" mdInput placeholder="Jar File Name" id="jarName" name="jarname" type="search" >
</md-input-container>
<md-input-container div="addVersion" *ngIf="versionClicked === true">
<input [(ngModel)]="message.version" mdInput placeholder="Version" id="versionNumber" name="versionnumber" type="search" >
</md-input-container>
<md-input-container div="addDirectory" *ngIf="directoryClicked === true">
<input [(ngModel)]="message.directory" mdInput placeholder="Directory" id="directoryName" name="directoryname" type="search" >
</md-input-container>
<md-input-container div="addDependentClass" *ngIf="dependentClicked === true">
<input [(ngModel)]="message.dependentClass" mdInput placeholder="Dependent Class Name" id="dependentClassName" name="dependentclassname" type="search" >
</md-input-container>
</td>
</table>
<br>
<p *ngIf="classClicked === true || jarFileClicked === true || versionClicked === true || directoryClicked === true || dependentClicked === true">
<button md-raised-button color="accent" type="submit" id="submitButton">Submit</button>
<button md-raised-button id="clearButton" (click)="setAllToFalse() && clearFields()">Clear</button>
</p>
</form>
P.S : I tried something like this with typescript as well. But it don't work
clearFields(){
this.message.jarName="";
this.message.className="";
this.message.version="";
this.message.directory="";
this.message.dependentClass="";
}

Simply calling the clearFields() method inside another method worked.
setAllToFalse(){
this.classClicked = false;
this.jarFileClicked = false;
this.versionClicked = false;
this.directoryClicked = false;
this.dependentClicked = false;
this.condition_1 = false;
this.condition_2 = false;
this.condition_3 = false;
this.condition_4 = false;
this.condition_5 = false;
this.condition_6 = false;
this.condition_7 = false;
this.clearFields();
}

Related

when server's down, datas on board table disappear in Liferay

i'm on 7.2.
i've been making board with configurationPid function of liferay, but it's not working what i think.
here's the thing
I set up three types of board to use preferences function of liferay.
From divCd information of preferences releated with board portlet keys, i can search boards specific datas.
But the problem is that when i shut down the server, datas diappear only for notice board! (divCd - 1 : NOTICE , divCd - 2 : FAQ, divCd -3 : QNA)
This phenomenon only happend to board table. 
I didn't notice there's problem in my code because in dev server (local server) i've never seen this before.
This only happen in published server. When published server's down, datas of notice board disappear! (not happend to other table yet. :) ) Blow away for real!
I guess anyone in my company have never seen this (disappearing problem!).
So, because i used configurgationPid function to make reusable board
(Notice board, FAQ board, QNA board), configurationPid is quite suspicious for me. But I couldn't find this trouble shooting cases.
I'm gonna show you all my codes that used for this!
If you know any reasons why board data deleted, Please somebody help me. 
Minor helps can alse be helpful for me! 
flow
register board types
image => enter image description here
Board types can be defined here! and JSP file show theses
configuration.jsp
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# page import="com.liferay.portal.kernel.util.Constants"%>
<%# page import="com.osp.board.constants.OSPBoardWebPortletKeys" %>
<%# page import="com.osp.board.constants.OSPBoardWebActionKeys" %>
<%# page import="java.util.Map"%>
<%# include file="../../init.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Board Configuration</title>
</head>
<body>
<liferay-portlet:actionURL portletConfiguration="<%= true %>" var="boardDivActionURL">
<liferay-portlet:param name="target" value="boardDiv"/>
</liferay-portlet:actionURL>
<liferay-portlet:actionURL portletConfiguration="<%= true %>" var="boardActionURL">
<liferay-portlet:param name="target" value="board"/>
</liferay-portlet:actionURL>
<liferay-portlet:actionURL portletConfiguration="<%= true %>" var="boardRemoveURL">
<liferay-portlet:param name="target" value="boardRemove"/>
<liferay-portlet:param name="targetedDivCd" value=""/>
</liferay-portlet:actionURL>
<%
long divCd = Long.parseLong(portletPreferences.getValue("divCd", "0"));
String originalBoardPlid = portletPreferences.getValue("originalBoardPlid", "");
boolean mainListYn = Boolean.parseBoolean(portletPreferences.getValue("mainListYn",""));
String originalBoardPortletName = portletPreferences.getValue("originalBoardPortletName", "");
%>
<c:set var="divCd" value="<%= divCd %>"/>
<c:set var="originalBoardPlid" value="<%= originalBoardPlid %>"/>
<c:set var="mainListYn" value="<%= mainListYn %>"/>
<c:set var="originalBoardPortletName" value="<%= originalBoardPortletName %>"/>
<div class="sheet sheet-lg panel-group panel-group-flush my-5">
<div class="panel">
<form action="${boardActionURL}" method="POST">
<aui:input name="<%= Constants.CMD %>" type="hidden" value="<%= Constants.UPDATE %>" />
<div class="panel-heading">
<a class="collapse-icon sheet-subtitle" data-toggle="collapse" href="#portletInfoContentBody" aria-expanded="false" aria-controls="portletInfoContentBody">
Portlet Information
<span class="collapse-icon-closed">
<svg class="lexicon-icon lexicon-icon-angle-right" focusable="false" role="presentation" viewBox="0 0 512 512">
<path class="lexicon-icon-outline" d="M396.394 255.607c-0.22-6.936-2.973-13.81-8.272-19.111l-227.221-227.221c-11.026-11.059-28.94-11.059-39.999 0-11.058 11.026-11.058 28.941 0 39.999l206.333 206.333c0 0-206.333 206.333-206.333 206.333-11.058 11.058-11.058 28.973 0 39.999 11.059 11.059 28.972 11.059 39.999 0l227.221-227.221c5.3-5.3 8.053-12.175 8.272-19.111z"></path>
</svg>
</span>
<span class="collapse-icon-open">
<svg class="lexicon-icon lexicon-icon-angle-down" focusable="false" role="presentation" viewBox="0 0 512 512">
<path class="lexicon-icon-outline" d="M256 384c6.936-0.22 13.81-2.973 19.111-8.272l227.221-227.221c11.058-11.026 11.058-28.941 0-39.999-11.026-11.058-28.94-11.058-39.999 0l-206.333 206.333c0 0-206.333-206.333-206.333-206.333-11.059-11.058-28.973-11.058-39.999 0-11.059 11.058-11.059 28.972 0 39.999l227.221 227.221c5.3 5.3 12.174 8.053 19.111 8.272z">
</path>
</svg>
</span>
</a>
</div>
<div id="portletInfoContentBody" class="panel-body collapse show">
<div class="alert alert-info">
PortletKey : ${portletKey}
<br/>
Plid : ${plid}
</div>
<c:choose>
<c:when test="${empty boardDivs}">
<aui:select name="divSort" label="board-config-property-name-divsort" helpMessage="board-config-property-explain-divsort" disabled="true">
</aui:select>
</c:when>
<c:otherwise>
<aui:select name="preferences--divCd--" label="board-config-property-name-divsort" helpMessage="board-config-property-explain-divsort">
<option value="0"> </option>
<c:forEach items="${boardDivs}" var="boardDiv">
<c:if test="${boardDiv.divCd eq divCd}">
<option value="${boardDiv.divCd}" selected="selected">${boardDiv.divName}</option>
</c:if>
<c:if test="${boardDiv.divCd ne divCd}">
<option value="${boardDiv.divCd}">${boardDiv.divName}</option>
</c:if>
</c:forEach>
</aui:select>
</c:otherwise>
</c:choose>
<div class="form-group">
<label>
<input type="hidden" name="<portlet:namespace/>preferences--mainListYn--" id="<portlet:namespace/>preferences--mainListYn--" value="${mainListYn}"/>
<input class="toggle-switch" type="checkbox" id="mainListYn" ${mainListYn ? 'checked="true"' : ''}>
<span class="toggle-switch-label">
<liferay-ui:message key="board-config-property-name-mainlistyn"/>
<liferay-ui:icon-help message="board-config-property-explain-mainlistyn"/>
</span>
<span aria-hidden="true" class="toggle-switch-bar">
<span class="toggle-switch-handle" data-label-off="no" data-label-on="yes">
</span>
</span>
</label>
</div>
<aui:input name="preferences--originalBoardPortletName--" label="board-config-property-name-originalboard-portletname" helpMessage="board-config-property-explain-portletname" value="${originalBoardPortletName}">
</aui:input>
<aui:input name="preferences--originalBoardPlid--" label="board-config-property-name-originalboard-plid" helpMessage="board-config-property-explain-plid" value="${originalBoardPlid}">
</aui:input>
<div class="d-flex justify-content-end">
<button type="submit" class="btn btn-primary"><liferay-ui:message key="save"/></button>
</div>
</div>
</form>
</div>
</div>
<div class="sheet sheet-lg panel-group panel-group-flush my-5">
<div class="panel">
<form action="${boardDivActionURL}" method="POST" id="boardTypeList">
<div class="panel-heading">
<a class="collapse-icon sheet-subtitle" data-toggle="collapse" href="#boardDivContentBody" aria-expanded="false" aria-controls="boardDivContentBody">
<liferay-ui:message key="board-config-property-boarddiv-title"/>
<span class="collapse-icon-closed">
<svg class="lexicon-icon lexicon-icon-angle-right" focusable="false" role="presentation" viewBox="0 0 512 512">
<path class="lexicon-icon-outline" d="M396.394 255.607c-0.22-6.936-2.973-13.81-8.272-19.111l-227.221-227.221c-11.026-11.059-28.94-11.059-39.999 0-11.058 11.026-11.058 28.941 0 39.999l206.333 206.333c0 0-206.333 206.333-206.333 206.333-11.058 11.058-11.058 28.973 0 39.999 11.059 11.059 28.972 11.059 39.999 0l227.221-227.221c5.3-5.3 8.053-12.175 8.272-19.111z"></path>
</svg>
</span>
<span class="collapse-icon-open">
<svg class="lexicon-icon lexicon-icon-angle-down" focusable="false" role="presentation" viewBox="0 0 512 512">
<path class="lexicon-icon-outline" d="M256 384c6.936-0.22 13.81-2.973 19.111-8.272l227.221-227.221c11.058-11.026 11.058-28.941 0-39.999-11.026-11.058-28.94-11.058-39.999 0l-206.333 206.333c0 0-206.333-206.333-206.333-206.333-11.059-11.058-28.973-11.058-39.999 0-11.059 11.058-11.059 28.972 0 39.999l227.221 227.221c5.3 5.3 12.174 8.053 19.111 8.272z">
</path>
</svg>
</span>
</a>
</div>
<div id="boardDivContentBody" class="panel-body collapse show">
<div class="form-group">
<div class="table-responsive-md">
<table class="table table-bordered">
<!-- <colgroup>
<col width="5%">
<col width="16.5%">
<col width="25.5%">
<col width="10%">
<col width="23%">
<col width="6%">
<col width="8%">
</colgroup> -->
<thead>
<tr>
<th scope="col" class="text-center"><liferay-ui:message key="table-index"/></th>
<c:forEach items="${locales}" var="locale">
<th scope="col" class="text-center">Title(${locale})</th>
</c:forEach>
<th scope="col" class="text-center"><liferay-ui:message key="board-config-property-boarddiv-column-content"/></th>
<th scope="col" class="text-center"><liferay-ui:message key="board-config-property-boarddiv-column-name"/></th>
<th scope="col" class="text-center"><liferay-ui:message key="board-config-property-boarddiv-column-fileuse"/></th>
<th scope="col" class="text-center"><liferay-ui:message key="board-config-property-boarddiv-column-popupuse"/></th>
<th scope="col" class="text-center"><liferay-ui:message key="board-config-property-boarddiv-column-replyuse"/></th>
<th scope="col" class="text-center"></th>
</tr>
</thead>
<tbody data-entity="boardDiv">
<c:choose>
<c:when test="${empty boardDivs}">
<tr data-nodata="true">
<td class="text-center text-danger" colspan="8">
<liferay-ui:message key="board-config-property-boarddiv-result-noboarddiv"/>
</td>
</tr>
</c:when>
<c:otherwise>
<c:forEach items="${boardDivs}" var="boardDiv" varStatus="vs">
<tr>
<input type="hidden" name="<portlet:namespace/>idx" value="${vs.count}"/>
<input type="hidden" name="<portlet:namespace/>divCd" value="${boardDiv.divCd}"/>
<td scope="col" class="text-center">${vs.count}</td>
<c:forEach items="${locales}" var="locale">
<c:set var="titleKey" value="title_${locale}"/>
<td scope="col" class="text-center">
<input type="text" class="form-control" name="<portlet:namespace/>title_${locale}_${vs.count}" value="${boardDiv[titleKey]}" maxlength="30"/>
</td>
</c:forEach>
<td scope="col" class="text-center">
<input type="text" class="form-control" name="<portlet:namespace/>content_${vs.count}" value="${boardDiv.content}" maxlength="30"/>
</td>
<td scope="col" class="text-center">
<input type="text" class="form-control" name="<portlet:namespace/>divName_${vs.count}" value="${boardDiv.divName}" maxlength="30"/>
</td>
<td scope="col" class="text-center">
<input type="checkbox" name="<portlet:namespace/>fileUploadUseYn_${vs.count}" ${boardDiv.fileUploadUseYn ? 'checked="true"' : ''}/>
</td>
<td scope="col" class="text-center">
<input type="checkbox" name="<portlet:namespace/>popupYn_${vs.count}" ${boardDiv.popupYn ? 'checked="true"' : ''}/>
</td>
<td scope="col" class="text-center">
<input type="checkbox" name="<portlet:namespace/>replyYn_${vs.count}" ${boardDiv.replyYn ? 'checked="true"' : ''}/>
</td>
<td scope="col" class="text-center">
<button class="btn btn-default" type="button" data-target-entity="remove" data-event="remove" data-div-cd="${boardDiv.divCd}">
<i class="icon-trash"></i>
</button>
</td>
</tr>
</c:forEach>
</c:otherwise>
</c:choose>
</tbody>
</table>
</div>
</div>
<div class="d-flex d-flex justify-content-between">
<button type="button" class="btn btn-outline-dark" data-target-entity="boardDiv">
<i class="icon-plus"></i>
Board Type
</button>
<button type="submit" class="btn btn-primary"><liferay-ui:message key="save"/></button>
</div>
</div>
</form>
</div>
</div>
</body>
</html>
<script type="text/javascript">
$(function(){
$('#mainListYn').on('change', function(){
$('#<portlet:namespace/>preferences--mainListYn--').val($(this).prop('checked'));
});
$(document).on('click','[data-target-entity]', function(){
var target = $('[data-entity="'+$(this).data('targetEntity')+'"]');
if($(target).find('[data-nodata="true"]').length > 0){
$(target).empty();
}
var targetType = $(this).data("targetEntity") || "";
if(targetType == "remove"){
var targetedDivCd = $(this).data('divCd') || '';
if(targetedDivCd != ""){
$.ospConfirm({
modalDialogClass : 'modal-md',
title : '<liferay-ui:message key="board-app-delete-modal-title"/>',
confirmText : '<liferay-ui:message key="board-app-notice-delete-modal-btn"/>',
body : '<liferay-ui:message key="board-app-delete-modal-body"/>',
closeText : '<liferay-ui:message key="board-app-delete-cancel"/>',
onSubmit : function(result){
if(result){
var actionURL = "${boardRemoveURL}";
actionURL +="&_com_liferay_portlet_configuration_web_portlet_PortletConfigurationPortlet_targetedDivCd=" + targetedDivCd;
window.location = actionURL.toString();
}
}
});
}else{
$(this).closest("tr").remove();
}
return;
}
var idx = $(target).find('tr').length + 1;
if('content' in document.createElement('template')){
var tmpl = document.querySelector('#boardDivTmpl');
var clone = document.importNode(tmpl.content, true);
$(clone).find("tr").prepend(
$('<input/>').attr({
type : 'hidden',
name : '<portlet:namespace/>idx',
value : idx
}),
$('<input/>').attr({
type : 'hidden',
name : '<portlet:namespace/>divCd',
value : 0
})
);
var tds = clone.querySelectorAll("td");
tds.forEach( (td, i) => {
if(i == 0){
$(td).text(idx);
}else{
if($(tds).eq(i).find('input').length > 0){
var input = $(td).find('input:eq(0)');
var bName = $(input).attr('name');
var aName = bName.replace('_idx', '_'+idx);
$(tds).eq(i).find('input:eq(0)').attr('name', aName);
}
}
});
$(target).append(clone);
} else{
var input = $('<input/>').addClass('form-control'),
checkbox = $('<input/>').attr('type', 'checkbox'),
appendTd = $('<td/>').addClass('text-center');
$('<tr/>').append(
$('<input/>').attr({
type : 'hidden',
name : '<portlet:namespace/>idx',
value : idx
}),
$(appendTd).clone()
.text(idx),
$(appendTd).clone()
.append(
$(input).clone().attr('name', '<portlet:namespace/>title_ko_KR_'+idx)
),
$(appendTd).clone()
.append(
$(input).clone().attr('name', '<portlet:namespace/>title_en_US_'+idx)
),
$(appendTd).clone()
.append(
$(input).clone().attr('name', '<portlet:namespace/>content_'+idx)
),
$(appendTd).clone()
.append(
$(input).clone().attr('name', '<portlet:namespace/>divName_'+idx)
),
$(appendTd).clone()
.append(
$(checkbox).clone().attr('name', '<portlet:namespace/>fileUploadUseYn_'+idx)
),
$(appendTd).clone()
.append(
$(checkbox).clone().attr('name', '<portlet:namespace/>popupYn_'+idx)
),
$(appendTd).clone()
.append(
$(checkbox).clone().attr('name', '<portlet:namespace/>replyYn_'+idx)
)
).appendTo(target);
}
});
});
</script>
<template id="boardDivTmpl">
<tr>
<td scope="col" class="text-center"></td>
<c:forEach items="${locales}" var="locale">
<td scope="col" class="text-center">
<input type="text" class="form-control" name="<portlet:namespace/>title_${locale}_idx"/>
</td>
</c:forEach>
<td scope="col" class="text-center">
<input type="text" class="form-control" name="<portlet:namespace/>content_idx"/>
</td>
<td scope="col" class="text-center">
<input type="text" class="form-control" name="<portlet:namespace/>divName_idx"/>
</td>
<td scope="col" class="text-center">
<input type="checkbox" name="<portlet:namespace/>fileUploadUseYn_idx"/>
</td>
<td scope="col" class="text-center">
<input type="checkbox" name="<portlet:namespace/>popupYn_idx"/>
</td>
<td scope="col" class="text-center">
<input type="checkbox" name="<portlet:namespace/>replyYn_idx"/>
</td>
<td>
<button class="btn btn-default" type="button" data-target-entity="remove">
<i class="icon-trash"></i>
</button>
</td>
</tr>
</template>
If you save for delete, you can see if they exists on my table!
image => enter image description here
but, It was not simple if i need to use OSP_BoardDiv.
In main page, I must know exact plid to get to the right board type.
For this, I should set plid, divCd before you main page for preview of
notice board. And i set it on html tags.
image => enter image description here
If board types are set, i can read information from BoardRender.
And the next thing is all the same. Controlling data with action,
render, resources ... but i can't find any problem on my codes!
I must get plId infos to nevigate user to get to the right board. So, I access to xml datas of the PortletPreferences table. If portletId is same with board portlet and divCd is same, get datas!
BoardRender.java
package com.osp.board.web.board.command;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.model.PortletPreferences;
import com.liferay.portal.kernel.portlet.bridges.mvc.MVCRenderCommand;
import com.liferay.portal.kernel.service.PortletPreferencesLocalServiceUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.theme.ThemeDisplay;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.LocaleUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.PortalUtil;
import com.liferay.portal.kernel.util.WebKeys;
import com.osp.board.constants.ConstantsPagePath;
import com.osp.board.constants.OSPBoardWebPortletKeys;
import com.osp.board.model.Board;
import com.osp.board.model.BoardDiv;
import com.osp.board.service.BoardDivLocalServiceUtil;
import com.osp.board.service.BoardLocalServiceUtil;
import com.osp.constants.CustomRoleConstants;
import com.osp.constants.MessageConstants;
import com.osp.constants.SiteNameConstants;
import com.osp.search.constants.OSPSearchPortletKeys;
import com.osp.util.CustomUtil;
import com.osp.util.OSPPropertiesUtil;
import com.osp.util.OSPUsersUtil;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.osgi.service.component.annotations.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
#Component(
immediate = true,
property = {
"javax.portlet.name=" + OSPBoardWebPortletKeys.BOARD_PORTLET_KEY,
"mvc.command.name=/",
"javax.portlet.version=3.0"
},
service = MVCRenderCommand.class
)
public class BoardRender implements MVCRenderCommand {
private static final Log _log = LogFactoryUtil.getLog(BoardRender.class);
#Override
public String render(RenderRequest renderRequest, RenderResponse renderResponse) throws PortletException {
ThemeDisplay themeDisplay = (ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
String isMainPage = renderRequest.getPreferences().getValue("mainListYn", "false");
String jspPage = ConstantsPagePath.OSP_BOARD_LIST;
String escapeTag = "<(/)?([a-zA-Z]*)(\\\\s[a-zA-Z]*=[^>]*)?(\\\\s)*(/)?>";
long divCd = Long.parseLong(renderRequest.getPreferences().getValue("divCd", "0"));
try {
if(divCd > 0) {
BoardDiv boardDiv = BoardDivLocalServiceUtil.getBoardDiv(divCd);
Map<String, Object> boardDivMap = new HashMap<String, Object>();
boardDivMap.put("title", boardDiv.getTitle(themeDisplay.getLanguageId()));
// permission check start.
String divName = GetterUtil.getString(boardDiv.getDivName(), "FAQ").toUpperCase();
boolean permission = false;
if(isMainPage.equals("true")) {// write only portal, site admins.
List<PortletPreferences> searchPreferences = null;
String searchNamespace = "";
String siteName = CustomUtil.strNull(OSPPropertiesUtil.getPortalSiteName(),"1");
renderRequest.setAttribute("siteName", siteName);
if(siteName.equals(SiteNameConstants.BIO)) {
searchPreferences = PortletPreferencesLocalServiceUtil.getPortletPreferences().stream().filter(pp -> pp.getPortletId().equals(OSPSearchPortletKeys.TOTAL_LIST_SEARCH_PORTLET_KEY)).collect(Collectors.toList());
searchNamespace = PortalUtil.getPortletNamespace(OSPSearchPortletKeys.TOTAL_LIST_SEARCH_PORTLET_KEY);
}else {
searchPreferences = PortletPreferencesLocalServiceUtil.getPortletPreferences().stream().filter(pp -> pp.getPortletId().equals(OSPSearchPortletKeys.MATERIAL_LIST_SEARCH_PORTLET_KEY)).collect(Collectors.toList());
searchNamespace = PortalUtil.getPortletNamespace(OSPSearchPortletKeys.MATERIAL_LIST_SEARCH_PORTLET_KEY);
}
if(searchPreferences != null) {
long searchPlid = searchPreferences.get(0).getPlid();
renderRequest.setAttribute("searchPlid", searchPlid);
renderRequest.setAttribute("searchNamespace", searchNamespace);
}
List<PortletPreferences> boardPrefereneces = PortletPreferencesLocalServiceUtil.getPortletPreferences().stream().filter(pp -> pp.getPortletId().equals(OSPBoardWebPortletKeys.BOARD_PORTLET_KEY)).collect(Collectors.toList());
Map<String, Map<String, Object>> resultMap = new HashMap<String, Map<String,Object>>();
List<BoardDiv> boardTypeList = BoardDivLocalServiceUtil.getBoardDivListWithBoardName();
for(PortletPreferences pp : boardPrefereneces) {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
InputSource is = new InputSource();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
is.setCharacterStream(new StringReader(pp.getPreferences()));
Document document = docBuilder.parse(is);
document.getDocumentElement().normalize();
if(document.getElementsByTagName("value").getLength() > 0 ) {
NodeList valueList = document.getElementsByTagName("value");
String nodeValue = "";
for(BoardDiv bdiv : boardTypeList) {
for(int i = 0; valueList.getLength() > i; i++) {
Node valueNode = valueList.item(i);
nodeValue = valueNode.getTextContent();
if(String.valueOf(bdiv.getDivCd()).equals(nodeValue)) {
Map <String, Object> dataMap = new HashMap<>();
dataMap.put("plid",pp.getPlid());
dataMap.put("portletId",pp.getPortletId());
dataMap.put("divCd", nodeValue);
resultMap.put(bdiv.getContent().toUpperCase(), dataMap);
break;
}
}
}
}
}
List<Board> boardListForMainNotice = new ArrayList<Board>();
List<Board> boardListForMainFaq = new ArrayList<Board>();
for(BoardDiv bdiv : boardTypeList) {
if("NOTICE".equals(bdiv.getContent().toUpperCase())) // notice
boardListForMainNotice = BoardLocalServiceUtil.getBoardListByDivcdSiteGroupIdsForMain(bdiv.getDivCd(), themeDisplay.getScopeGroupId(), 0, 3, themeDisplay.getLanguageId());
if("FAQ".equals(bdiv.getContent().toUpperCase())) // faq
boardListForMainFaq = BoardLocalServiceUtil.getBoardListByDivcdSiteGroupIdsForMain(bdiv.getDivCd(), themeDisplay.getScopeGroupId(), 0, 4, themeDisplay.getLanguageId());
}
for(Board board : boardListForMainNotice) {
board.setTitle(board.getTitle(LocaleUtil.KOREA));
board.setCreateDate(board.getCreateDate());
board.setContent(board.getContent(LocaleUtil.KOREA).replaceAll(escapeTag, ""));
}
for(Board board : boardListForMainFaq){
board.setTitle(board.getTitle(LocaleUtil.KOREA));
board.setCreateDate(board.getCreateDate());
board.setContent(board.getContent(LocaleUtil.KOREA).replaceAll(escapeTag, "").replaceAll(" ", "<br>").replaceAll("<br>", ""));
}
renderRequest.setAttribute("boardInfos", resultMap);
renderRequest.setAttribute("boardListForMainNotice", boardListForMainNotice);
renderRequest.setAttribute("boardListForMainFaq", boardListForMainFaq);
jspPage = ConstantsPagePath.OSP_MAIN_BOARD_LIST;
}else if("QNA".equals(divName)) {// admins or writer.
permission = themeDisplay.getPermissionChecker().isSignedIn();
}else if("FAQ".equals(divName)||divName.equals("NOTICE")) {
permission = OSPUsersUtil.isRegularRole(themeDisplay.getUser(), CustomRoleConstants.ADMINISTRATOR);
if(!permission) permission = OSPUsersUtil.isSiteRole(themeDisplay.getUser(), themeDisplay.getScopeGroupId(), CustomRoleConstants.SITE_ADMINISTRATOR);
}else {
_log.debug("##### DivName '"+divName+"' is not supported yet.");
_log.debug("##### Check role like FAQ(Write only admins.).");
permission = OSPUsersUtil.isRegularRole(themeDisplay.getUser(), CustomRoleConstants.ADMINISTRATOR);
if(!permission) permission = OSPUsersUtil.isSiteRole(themeDisplay.getUser(), themeDisplay.getScopeGroupId(), CustomRoleConstants.SITE_ADMINISTRATOR);
}
renderRequest.setAttribute("permission", permission);
// permission check end.
renderRequest.setAttribute("boardDiv", boardDivMap);
}else {
SessionErrors.add(renderRequest, MessageConstants.SEARCH_ERROR);
}
} catch (Exception e) {
_log.error(e);
jspPage = ConstantsPagePath.OSP_MAIN_BOARD_LIST;
renderRequest.setAttribute("permission", false);
SessionErrors.add(renderRequest, MessageConstants.SEARCH_ERROR);
}
// session message print.
String msgType = ParamUtil.getString(renderRequest, "msgType", "");
if(msgType.equals("error")) {
SessionErrors.add(renderRequest, ParamUtil.getString(renderRequest, "ssMsg", ""));
}else if(!msgType.equals("")) {
SessionMessages.add(renderRequest, ParamUtil.getString(renderRequest, "ssMsg", ""));
}
SessionMessages.add(renderRequest, PortalUtil.getPortletId(renderRequest) + SessionMessages.KEY_SUFFIX_HIDE_DEFAULT_ERROR_MESSAGE);
return jspPage;
}
public static void main(String[] args) {
}
}
BoardConfig.java
package com.osp.board.web.board.config;
import com.liferay.portal.configuration.metatype.annotations.ExtendedObjectClassDefinition;
import com.osp.board.constants.OSPBoardWebPortletKeys;
import aQute.bnd.annotation.metatype.Meta;
#ExtendedObjectClassDefinition(
category = "board",
scope = ExtendedObjectClassDefinition.Scope.SYSTEM
)
#Meta.OCD(
id = OSPBoardWebPortletKeys.BOARD_CONFIG_PORTLET_KEY
)
public interface BoardConfig {
}

Show more comments using ajax with Django

With Django I made a Show more comments button using ajax. This system works, but the problem is that there are form fields in the comments I brought in this way, and when I click the more button, csrf_token does not appear in this comment field. As such, I get a csrf_token error when I submit the form. I leave my codes below.
To solve this problem, I ran the form with the get method, but as such, the function in the views directs me to the page with JsonResponse. Another solution was to give the header information csrf_token, but that didn't solve the problem either.
blog_detail.html
<script>
$(document).ready(function(){
$('#load_form').submit(function(e){
e.preventDefault();
var limit = $(this).attr('limit')
var page = document.getElementById('pagination')
var blog_comment_list = $('#blog-comment-list')
var serializedData = $(this).serialize();
$.ajax({
type:'GET',
url: "{% url 'load-more-comments' %}",
data : serializedData,
success: function(response){
blog_comment_list.html(response.comment_html)
if (page.value >= limit){
$('#submit_button').hide()
}
page.value = parseInt(page.value)+1
},
})
})
})
</script>
<div id="blog-comment-list">
{% include 'front_end/blog/comment/partial-comment.html' %}
</div>
<form method="GET" id="load_form" limit="{{num_pages}}">
<input type="hidden" name="pk" value="{{details.id}}">
<input type="hidden" name="page" value="2" id="pagination">
<input type="submit" name="load" value="Load More" id="submit_button">
</form>
partial-comment-html
<div class="media-holder mt-5">
<h3 class="title mb-3">All Comments</h3>
{% for item in comments %}
<div class="infinite-container">
<div class="media mb-5">
<img class="img-fluid rounded-circle box-shadow mr-4" alt="image" src="{{item.owner.get_image_or_default}}" style="width: 100px;height: 100px;">
<div class="media-body">
<h6>{{item.owner.name}} {{item.owner.surname}}</h6>
<br>
<small><span style="font-size:14px;" class="stars-container stars-{% widthratio item.rate.rate 1 20 %}" id="stars">★★★★★</span></small>
<div class="comment-date"> <span class="date">{{item.created_date|naturaltime}}</span>
</div>
<p>{{item.content}} </p>
<div align="center">
{% if item.comments.all %}Cevapları Görüntüle ({{item.comments.count}}){% else %}Cevap Ver{% endif %}
</div>
<div class="generic-comment" id="generic-comment-id-{{item.id}}" style="display:none;">
<!-- -->
<div class="infinite-generic-comment">
<form action="{% url 'comment-answer' %}" method="POST" id="answer_form">
{% csrf_token %}
<input type="hidden" name="comment_id" value="{{item.id}}">
<div class="row">
<div class="col-9">
<input type="text" placeholder="Cevap Ver" name='generic_comment' class="form-control">
</div>
<div class="col-2">
<input type="submit" value="Cevap Ver" class="btn btn-outline-primary">
</div>
</div>
</form>
{% for comment in item.comments.all %}
<div class="media mb-2">
<img class="img-fluid rounded-circle box-shadow mr-4" alt="image" src="{{item.owner.get_image_or_default}}" style="width: 100px;height: 100px;">
<div class="media-body">
<h6>{{comment.owner.name}} {{comment.owner.surname}}</h6>
<div class="comment-date"> <span class="date">{{comment.created_date|naturaltime}}</span>
</div>
<p>{{comment.content}} </p>
</div>
</div>
{% endfor %}
</div>
<!-- -->
</div>
</div>
</div>
</div>
{% endfor %}
</div>
<script>
var aTag = document.getElementsByClassName('show-answers')
for (let i = 0; i< aTag.length; i++){
aTag[i].addEventListener('click', (event) => {
var generic = document.getElementById(`generic-${event.target.id}`)
if (generic.style.display == 'none'){
$(`#generic-${event.target.id}`).slideDown('slow')
}
else{
$(`#generic-${event.target.id}`).slideUp('slow')
}
})
}
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$(document).ready(function(){
$('#answer_form').submit(function(e){
e.preventDefault()
var serializedData = $(this).serialize()
var url = $(this).attr('action')
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
//headers: { "X-CSRFToken": getCookie("csrftoken") }
});
$.ajax({
type:'POST',
url: url,
data:serializedData,
success: function(response){
if (response.success){
$('#answer_form').trigger('reset')
Swal.fire(
'Başarılı!',
'Cevap onaya gönderildi',
'success'
)
}
}
})
})
})
</script>
views.py
def answer_comment(request):
if request.method=='POST':
comment = Comment.objects.get(id=request.POST.get('comment_id'))
comment.comments.create(owner=request.user, content=request.POST.get('generic_comment'))
return JsonResponse({'success':True},status=200)
return JsonResponse({'success':False}, status = 403)
Note: I tried the csrf_exempt decorator function, but still could not solve the problem.
The methods I use are available in the script tag in partial-comment-html. How can I solve this problem. As I said, when I press the load more button, the necessary form fields to respond to a comment are just below these comments and when load more with ajax, the csrf_token information is deleted in these form fields, and nothing happens in new comments.
Note 2: When {{csrf_token}} is entered, I added the hidden input field with javascript myself, but Django realized that I added it and prevented me.

Image upload in a form

I have an angular form with text fields and want to add am option for uploading image in the same form. I'm stuck with the latter.
The angular form contains html tag to upload the file. Once the file is uploaded the uploaded file's name is displayed in the input field.
<!--blog.html-->
<!--form to create new blog-->
<form #blogForm="ngForm" (ngSubmit)="Save(blogForm);">
<div class="form-group">
<label>Blog Title</label>
<input type="text" class="form-control input-text" maxlength="45" name="title" ngModel #blogtitle="ngModel" required placeholder="Blog Title">
<span class="required" *ngIf="blogtitle.errors?.required && (blogtitle.dirty||blogtitle.touched||blogtitle.untouched)">*required</span>
</div>
<div class="form-group">
<label>Blog </label>
<textarea class="textarea form-control" maxlength="150" name="summary" [(ngModel)]="summary">
Blog</textarea>
</div>
<div class="form-group">
<label>Blog Desc</label>
<textarea class="textarea form-control" name="description" ngModel #blogdescription="ngModel" required>Blog Description</textarea>
<span class="required" *ngIf="blogdescription.errors?.required && (blogdescription.dirty||blogdescription.touched||blogdescription.untouched)">*required</span>
</div>
<div class="form-group">
<label>HashTags</label>
<input type="text" class="form-control input-text" name="hashtag" [(ngModel)]="hashtag" placeholder="hashtags">
</div>
<div class="form-group">
<div class="custom-file">
<!--file upload -->
<input type="file" class="custom-file-input form-control-lg" name="file" id="customFile"
value="imageFile.name" (change)="handleImageFileInput($event)">
<input type="text" readonly="true" [value]="imageFile" class="custom-file-label" >
<button type="button" (click)="upload()">Upload</button>
</div>
</div>
<input type="button" class="btn-default" (click)="Save(blogForm)" value="Create">
</form>
//blog.ts
//function to create new blog
Save(blogForm: any) {
if (blogForm.valid === true) {
blogForm = blogForm.value;
blogForm.userId = this.user_id;
blogForm.author = this.display_name;
window.confirm('Want to Publish?');
this.blogservice.Save(blogForm).subscribe(response => {
window.alert('Blog published successfully');
this.router.navigate(['/dashboard']);
});
}
}
//function to display selected image in the input field
handleImageFileInput(event) {
const img1 =event.target.files[0];
const img =event.target.files[0].name;
const fileList: FileList = event.target.files;
const fileCount = fileList.length;
if (fileCount > 0) {
const file = fileList.item(0);
console.log(` image file: ${file.name}`);
console.log(img1);
if(img == undefined) {
this.imageFile = 'Upload an image';
} else {
this.imageFile = img;
}
}
}
Need to save file along with form submission
Here's a JavaScript script which will read your data from input and display it :
<input type='file' accept='image/*' onchange='openFile(event)'><br>
<img id='output'>
<script>
var openFile = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var dataURL = reader.result;
var output = document.getElementById('output');
output.src = dataURL;
};
reader.readAsDataURL(input.files[0]);
};
</script>
It come from the documentation of FileReader.
With that you should be able to store the input wherever you want and store the path inside of your MongoDB collection.
Else if you want to use Angular plugins, here's one that could be useful for you :
angular-file-upload

hide pop up based on message under browser's Response tab

in pop up box, we are displaying login form. once user enter wrong email id or password, we are displaying message : Invalid login/pw , but once they enter correct details and click on login button, than user will be logged in.
but issue is pop up box will remain until we close the pop up manually with help of close button as in below image, but i want to hide the pop up box if login is successfull.
enter image description here
Once we click on login, under Response tab, if there is no message, than i want to hide the pop up, if there is message as success":false,"error":"Invalid login or password." , than i don't want to hide the pop up
enter image description here
I tried below code :
Html
<form>
//code for email and pw
<button onclick = "hideWindow()">Login</button>
</form>
Ajax
function hideWindow()
{
var username=jQuery( "#customusername" ).val();
var password=jQuery( "#custompassword" ).val();
url="";
new Ajax.Request(url, {
method: 'POST',
onFailure: function(response){
},
parameters: {
username: username,
password:password
},
onSuccess: function(response)
{
if(response.responseText=="")
{
//trigger to close popup
document.getElementById('something').style.display = 'none';
document.getElementById('ajaxlogin-mask').style.display = 'none';
}
}
});
}
edit
<div class="ajaxlogin-window" id="something">
<form>
<div class="content">
<ul class="form-list">
<li>
<input type="hidden" id="likeproduct_id" name="product_id" value=""/>
<label for="email" class="required"><em>*</em>Email</label>
<div class="input-box">
<input type="text" name="login[username]" value="<?php echo $this->htmlEscape($this->getUsername()) ?>" id="email" title="<?php echo $this->__('Email Address') ?>" />
</div>
</li>
<li>
<label for="pass" class="required"><em>*</em><?php echo $this->__('Password') ?></label>
<div class="input-box">
<input type="password" name="login[password]" id="pass" title="<?php echo $this->__('Password') ?>" />
</div>
</li>
<?php echo $this->getChildHtml('form.additional.info'); ?>
</ul>
</div>
<div class="buttons-set">
<button onclick = "hideWindow()" type="submit" class="button" title="<?php echo $this->__('Login') ?>" name="send" id="send2" ><span><span><?php echo $this->__('Login') ?></span></span></button>
</div>
</div>
As I can see there is some thing wrong with your ajax function try this out:
onSuccess: function(response)
{
document.getElementById('something').style.display = 'none';
document.getElementById('ajaxlogin-mask').style.display = 'none';
}
function hideWindow()
{
var db_username = 'ankit';
var db_password = 'password';
var username=jQuery( "#customusername" ).val();
var password=jQuery( "#custompassword" ).val();
if(username = db_username && password == db_password) {
jQuery('#something').hide();
}
else{
jQuery('#something').prepend('Wrong Cred ');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ajaxlogin-window" id="something">
<form>
<div class="content">
<ul class="form-list">
<li>
<input type="hidden" id="likeproduct_id" name="product_id" value=""/>
<label for="email" class="required"><em>*</em>Email</label>
<div class="input-box">
<input type="text" name="login[username]" value="" id="email" title="Email Address" />
</div>
</li>
<li>
<label for="pass" class="required"><em>*</em>Password</label>
<div class="input-box">
<input type="password" name="login[password]" id="pass" title="Password" />
</div>
</li>
</ul>
</div>
<div class="buttons-set">
<button onclick = "hideWindow()" type="submit" class="button" title="Login" name="send" id="send2" ><span><span>Login</span></span></button>
</div>
Please check the code instead of ajax call i have just added a if condition.
Hope it might help you
Thanks

WATIR : how to set a checkbox inside a label

How can I check that checkbox using WATIR
<label title="Active-DC Cloud Management" class="custom-checkbox ng-scope folderSelector">
<span class="customCheckBox icn" ng-disabled="cDisabled">
<input class="ng-pristine ng-valid" ng-model="model" ng-change="changeCallback({$event:$event})" ng-disabled="cDisabled" type="checkbox">
</span> Active-DC Cloud Management<!-- ngIf: cFoldertype == 'ASP' || cFoldertype == 'VCE' || cFoldertype == 'CPL' -->
</label>
I have tried using the following but that doesn't work
#browser.label(:text,'Active-DC Cloud Management').parent.click
Here is more of the HTMl code
<li class="ng-scope" ng-repeat="subfolder in subfolder.subFolders" ng-class="{expandButton:subfolder.hasSubFolders,plus:subfolder.hasSubFolders, disabled:subfolder.folderAccess == 'NONE', selected:selectedFolderIdsArray.indexOf(subfolder.folderId) !== -1}" id="1001665955" ftpath="HOME\Order_12329753" ftname="Order_12329753" ftlevel="2" fttype="ORDER" ftaccess="VIEW">
<a name="&lpos=my : 263" href="javascript:void(0)" ng-click="toggleSelectFolder(subfolder.folderId,subfolder.fullFolderPath)" style="padding-left: 28px" data-this-tree="thisTree" complete-folder-stack="completeFolderStack" folder-data-ftype="subfolder.folderType">
<span class="expandCollapseIcon ng-hide" style="left: 15px" ng-show="subfolder.hasSubFolders" ng-click="expander($event,subfolder.folderAccess); ajaxLoad($event,subfolder)"> </span>
<label class="custom-checkbox ng-scope folderSelector">
<span class="customCheckBox icn" ng-disabled="cDisabled">
<input class="ng-valid ng-dirty" ng-model="model" ng-change="changeCallback({$event:$event})" ng-disabled="cDisabled" type="checkbox"></span>Order_12329753<!-- ngIf: cFoldertype == 'ASP' || cFoldertype == 'VCE' || cFoldertype == 'CPL' --></label></a>
<ul class="subfolder"><!-- ngRepeat: subfolder in subfolder.subFolders --></ul></li>
OK i figured this part out it seems like the div that contains all this code is set to be disabled (not invisible) so because of that I can not use the regular functions associated with the checkbox element but I can use the fire_event method of the browser to click on the checkbox b.input(:xpath,"//label[#title='Active-DC Cloud Management']/span/input").fire_event :click

Resources