Sharepoint InputFormTextBox not working on updatepanel? - sharepoint

I have two panels in update panel. In panel1, there is button. If I click, Panel1 will be visible =false and Panel2 will be visible=true. In Panel2, I placed SharePoint:InPutFormTextBox. It not rendering HTML toolbar and showing like below image.
<SharePoint:InputFormTextBox runat="server" ID="txtSummary" ValidationGroup="CreateCase" Rows="8" Columns="80" RichText="true" RichTextMode="Compatible" AllowHyperlink="true" TextMode="MultiLine" />
http://i700.photobucket.com/albums/ww5/vsrikanth/careersummary-1.jpg

SharePoint rich text fields start out as text areas, and some javascript in the page load event replaces them with a different control if you are using a supported browser.
With an update panel, the page isn't being loaded, so that script never gets called.
Try hiding the section using css/javascript rather than the server side visible property. That generally lets you make whatever changes you need to the form without sharepoint seeing any changes.

<SharePoint:InputFormTextBox ID="tbComment" CssClass="sp-comment-textarea" runat="server" TextMode="MultiLine" RichText="True"></SharePoint:InputFormTextBox>
<%--textbox for temporay focus - trick the IE behavior on partial submit--%>
<input type="text" id="<%= tbComment.ClientID %>_hiddenFocusInput_" style="width: 0px; height: 0px; position: absolute; top: -3000px;" />
<%--tricking code that makes the 'SharePoint:InputFormTextBox' to work correctly in udate panel on partial podtback--%>
<script id="<%= tbComment.ClientID %>_InputFormTextBoxAfterScript" type="text/javascript">
(function () {
// where possible rich textbox only
if (browseris.ie5up && (browseris.win32 || browseris.win64bit) && !IsAccessibilityFeatureEnabled()) {
// find this script element
var me = document.getElementById("<%= tbComment.ClientID %>_InputFormTextBoxAfterScript");
if (me) {
// search for script block of the rich textbox initialization
var scriptElement = me.previousSibling;
while (scriptElement && (scriptElement.nodeType != 1 || scriptElement.tagName.toLowerCase() != "script")) {
scriptElement = scriptElement.previousSibling;
}
// get the content of the found script block
var innerContent = scriptElement.text;
if (typeof innerContent == 'undefined') {
innerContent = scriptElement.innerHTML
}
// get text with function call that initializes the rich textbox
var callInitString = "";
innerContent.toString().replace(/(RTE_ConvertTextAreaToRichEdit\([^\)]+\))/ig, function (p0, p1) { callInitString = p1; });
// register on page load (partial updates also)
Sys.Application.add_load(function (sender, args) {
setTimeout(function () {
// get the toolbar of the rich textbox
var toolbar = $get("<%= tbComment.ClientID %>_toolbar");
// if not found then we should run initialization
if (!toolbar) {
// move focus to the hidden input
$get("<%= tbComment.ClientID %>_hiddenFocusInput_").focus();
// reset some global variables of the SharePoint rich textbox
window.g_aToolBarButtons = null;
window.g_fRTEFirstTimeGenerateCalled = true;
window.g_oExtendedRichTextSupport = null;
parent.g_oExtendedRichTextSupport = null;
// call the initialization code
eval(callInitString);
setTimeout(function () {
// call 'onload' code of the rich textbox
eval("RTE_TextAreaWindow_OnLoad('<%= tbComment.ClientID %>');");
}, 0);
}
}, 0);
});
}
}
})();
</script>

Related

Popup exceptions in line items (SOLine)

How to display popup exceptions instead of the one with a red dot on the row for the line items? I was able to have them in RowInserting for a little bit but after a series of code changes I get the red dot one instead. It even did not create a new row as I wanted but now it does. RowInserting event:
protected virtual void SOLine_RowInserting(PXCache sender, PXRowInsertingEventArgs e)
{
var listMissingOEdesc = new List<int>();
var select = Base.Transactions.Select();
foreach (SOLine row in select)
{
var isOEDesc = IsOEDescEnabled(sender, row);
var rowExt = PXCache<SOLine>.GetExtension<SOLineExt>(row);
if (isOEDesc == true)
if (rowExt.UsrOedesc == null)
listMissingOEdesc.Add(row.SortOrder.Value);
}
if (listMissingOEdesc.Count > 0)
{
throw new PXException("Line items with sort order {0} do not have OE Desc filled out. Cannot add a new line.", string.Join(", ", listMissingOEdesc));
}
else
Base.Actions.PressSave();
}
Thanks!
There is no easy way, if any at all, to display popup exception and prevent the grid from inserting a new row. The way the framework is designed, PXGrid first inserts a new row on the webpage. After that PXGrid sends a callback to the application server either requesting default field values for the new row (if PXGrid's Mode has InitNewRow="True") or sends all values captured from the webpage to the application server, so the new row can be inserted in the PXCache. Whenever an event handler, on the field or row level, gets invoked, the new row will still be visible to the user on the web page. Even if you invoke Ask method on the Transactions data view within one of the event handlers, the new row won't disappear from the webpage.
With all that said, the best and probably the only way to display popup exception and prevent the grid from inserting a new row is by replacing the standard Add New Row button on PXGrid with a custom action, which will first run the validation and display popup exception, if necessary. Otherwise, a new row will be inserted into PXGrid. It's also required to enable or disable the custom NewSOTran action based on the state of the standard PXGrid's Insert button.
public class SOOrderEntryExt : PXGraphExtension<SOOrderEntry>
{
public void SOOrder_RowSelected(PXCache sender, PXRowSelectedEventArgs e)
{
NewSOTran.SetEnabled(Base.Transactions.AllowInsert);
}
public PXAction<SOOrder> NewSOTran;
[PXButton(CommitChanges = true)]
[PXUIField]
protected void newSOTran()
{
var listMissingOEdesc = new List<SOLine>();
var select = Base.Transactions.Select();
foreach (SOLine row in select)
{
var isOEDesc = !string.IsNullOrEmpty(row.TranDesc);
if (isOEDesc == true)
listMissingOEdesc.Add(row);
}
if (listMissingOEdesc.Count > 0)
{
throw new PXException("Cannot add a new line.");
}
var newTran = Base.Transactions.Insert();
Base.Transactions.Cache.ActiveRow = newTran;
}
}
In Aspx there will required 3 major chages:
SyncPositionWithGraph property set to True for PXGrid:
<px:PXGrid ID="grid" runat="server" DataSourceID="ds" Width="100%" TabIndex="100"
SkinID="DetailsInTab" StatusField="Availability" SyncPosition="True" Height="473px"
SyncPositionWithGraph="True" >
the standard AddNew action must be replaced by a custom NewSOTran action:
<ActionBar>
<Actions>
<AddNew ToolBarVisible ="False" />
</Actions>
<CustomItems>
<px:PXToolBarButton CommandName="NewSOTran" CommandSourceID="ds"
DisplayStyle="Image">
<Images Normal="main#AddNew" />
<ActionBar GroupIndex="0" Order="2" />
</px:PXToolBarButton>
...
</CustomItems>
</ActionBar>
AllowAddNew property set to false in the Mode section of PXGrid to prevent the standart Insert button from execution when users use keyboard shortcuts or double-click on PXGrid:
<Mode InitNewRow = "True" AllowFormEdit="True" AllowUpload="True" AllowDragRows="true"
AllowAddNew="false" />
To select new records’ first cell and switch it to the edit mode (unless the first cell is read-only), it's also required to subscribe to the Initialize and ToolsButtonClick client events of PXGrid:
<ClientEvents Initialize="initTransactionsGrid"
ToolsButtonClick="transactionsGriduttonClick" />
and define the following JavaScript functions:
var isInitEvents = false;
function initTransactionsGrid(a, b) {
if (isInitEvents) return;
isInitEvents = true;
a.events.addEventHandler("afterRepaint", editNewSOTran);
}
function editNewSOTran() {
if (lastActiveRowIndex != null) {
var grid = px_alls["grid"];
if (grid.activeRow) {
var activeRowIndex = grid.rows.indexOf(grid.activeRow);
if (activeRowIndex != lastActiveRowIndex) {
grid.activeRow.activateCell(0, false);
grid.beginEdit();
}
}
lastActiveRowIndex = null;
}
}
var lastActiveRowIndex;
function transactionsGriduttonClick(sender, args) {
if (args.button && args.button.commandName == "NewSOTran") {
if (sender.activeRow)
lastActiveRowIndex = sender.rows.indexOf(sender.activeRow);
else
lastActiveRowIndex = -1;
return;
}
lastActiveRowIndex = null;
}
To package custom JavaScript code into customization, in Layout Editor you can drag and drop a Java Script element from the Add Controls tab and copy your entire JavaScript code into the Script property.

Save button with count greasemonkey

i want to add an save button with a counter
i wrote a script but its not work with greasemonkey
<button type="submit" id="save" value="Save">Save</button>
<p>The button was pressed <span id="displayCount">0</span> times.</p>
<script type="text/javascript">
var count = 0;
var button = document.getElementById("save");
var display = document.getElementById("displayCount");
function loadStats(){
if(window.localStorage.getItem('count')){
count = window.localStorage.getItem('count')
display.innerHTML = count;
} else {
window.localStorage.setItem('count', 0)
} //Checks if data has been saved before so Count value doesnt become null.
}
window.localStorage.setItem("on_load_counter", count);
button.onclick = function(){
count++;
window.localStorage.setItem("count", count)
display.innerHTML = count;
}
</script>
You have to add html elements with javascript since Greasemonkey is intended to run scripts over web pages.
See Basic method to Add html content to the page with Greasemonkey?

How to define new icons with winjs commands?

How to use an icon which is not provided by WinJS? For example, use one from here.
The html looks like:
<div data-win-control="WinJS.UI.SplitViewCommand" data-win-options="{ label: 'Home', icon: 'home'}"></div>
The png image should be 20x20 pixels with a transparent background (https://msdn.microsoft.com/en-us/library/windows/apps/hh700483.aspx). The png is set as in javascript:
document.getElementById("thatFancyButton").style.backgroundImage = url('pathOfPNGImage');
so in your case it is (notice \' \' in url()):
<div data-win-control="WinJS.UI.SplitViewCommand" data-win-options="{ label: 'Home', icon: 'url(\'pathOfPng.png\')'}"></div>
You can also set one letter glyphs like icon: '©' and it will show it as icon.
Below is the snippet of the SplitViewCommand icon setting logic:
/// <field type="String" locid="WinJS.UI.SplitViewCommand.icon" helpKeyword="WinJS.UI.SplitViewCommand.icon">
/// Gets or sets the icon of the SplitViewCommand. This value is either one of the values of the AppBarIcon enumeration or the path of a custom PNG file.
/// </field>
icon: {
get: function () {
return this._icon;
},
set: function (value) {
this._icon = (_Icon[value] || value);
// If the icon's a single character, presume a glyph
if (this._icon && this._icon.length === 1) {
// Set the glyph
this._imageSpan.textContent = this._icon;
this._imageSpan.style.backgroundImage = "";
this._imageSpan.style.msHighContrastAdjust = "";
this._imageSpan.style.display = "";
} else if (this._icon && this._icon.length > 1) {
// Must be an image, set that
this._imageSpan.textContent = "";
this._imageSpan.style.backgroundImage = this._icon;
this._imageSpan.style.msHighContrastAdjust = "none";
this._imageSpan.style.display = "";
} else {
this._imageSpan.textContent = "";
this._imageSpan.style.backgroundImage = "";
this._imageSpan.style.msHighContrastAdjust = "";
this._imageSpan.style.display = "none";
}
}
},
If you happen to have errors with the background image size, modify win-commandimage class. I did this fix in styles to fit the image into button correctly:
.win-commandimage {
background-size:contain;
}

onMouseOut effect fired when mouse cursor goes to child div.... I dont want to do that

Here is my code --
<li>
<a id="LoginTxt2" onmouseover="MouseOver(this);" onmouseout="MouseOut(this);" href="#">
<div style="background-color:#CCC;">OLD Text</div>
</a>
</li>
JS--
MouseOver = function(obj){
var id = obj.id;
document.getElementById(id).innerHTML='<div style="background-color:#DDD;">NEW Text</div>';
}
MouseOut = function(obj){
var id = obj.id;
document.getElementById(id).innerHTML="<div style="background-color:#CCC;">OLD Text</div>";
}
when my mouse goes to child div, MouseOut fierd i dont want to do that... plz help
This is the way the event works and there's no way of avoiding the MouseOut() function to be called. What you can do is check, inside the MouseOut() function, if the element you're now hovering is a child element of the outer element:
MouseOut = function(obj, event) {
// this is the original element the event handler was assigned to
var e = event.toElement || event.relatedTarget;
// check for all children levels (checking from bottom up)
while (e && e.parentNode && e.parentNode != window) {
if (e.parentNode == this|| e == this) {
if(e.preventDefault) {
e.preventDefault();
}
return false;
}
e = e.parentNode;
}
var id = obj.id;
document.getElementById(id).innerHTML="<div style="background-color:#CCC;">OLD Text</div>";
}
Note that you need to change the onmouseout declaration to onmouseout="MouseOut(this,event);".
NOTE: solution derived from https://stackoverflow.com/a/13141057/1417546

h:commandButton/h:commandLink does not work on first click, works only on second click

We have an ajax navigation menu which updates a dynamic include. The include files have each their own forms.
<h:form>
<h:commandButton value="Add" action="#{navigator.setUrl('AddUser')}">
<f:ajax render=":propertiesArea" />
</h:commandButton>
</h:form>
<h:panelGroup id="propertiesArea" layout="block">
<ui:include src="#{navigator.selectedLevel.url}" />
</h:panelGroup>
It works correctly, but any command button in the include file doesn't work on first click. It works only on second click and forth.
I found this question commandButton/commandLink/ajax action/listener method not invoked or input value not updated and my problem is described in point 9.
I understand that I need to explicitly include the ID of the <h:form> in the include in the <f:ajax render> to solve it.
<f:ajax render=":propertiesArea :propertiesArea:someFormId" />
In my case, however, the form ID is not known beforehand. Also this form will not be available in the context initally.
Is there any solution to the above scenario?
You can use the following script to fix the Mojarra 2.0/2.1/2.2 bug (note: this doesn't manifest in MyFaces). This script will create the javax.faces.ViewState hidden field for forms which did not retrieve any view state after ajax update.
jsf.ajax.addOnEvent(function(data) {
if (data.status == "success") {
fixViewState(data.responseXML);
}
});
function fixViewState(responseXML) {
var viewState = getViewState(responseXML);
if (viewState) {
for (var i = 0; i < document.forms.length; i++) {
var form = document.forms[i];
if (form.method == "post") {
if (!hasViewState(form)) {
createViewState(form, viewState);
}
}
else { // PrimeFaces also adds them to GET forms!
removeViewState(form);
}
}
}
}
function getViewState(responseXML) {
var updates = responseXML.getElementsByTagName("update");
for (var i = 0; i < updates.length; i++) {
var update = updates[i];
if (update.getAttribute("id").match(/^([\w]+:)?javax\.faces\.ViewState(:[0-9]+)?$/)) {
return update.textContent || update.innerText;
}
}
return null;
}
function hasViewState(form) {
for (var i = 0; i < form.elements.length; i++) {
if (form.elements[i].name == "javax.faces.ViewState") {
return true;
}
}
return false;
}
function createViewState(form, viewState) {
var hidden;
try {
hidden = document.createElement("<input name='javax.faces.ViewState'>"); // IE6-8.
} catch(e) {
hidden = document.createElement("input");
hidden.setAttribute("name", "javax.faces.ViewState");
}
hidden.setAttribute("type", "hidden");
hidden.setAttribute("value", viewState);
hidden.setAttribute("autocomplete", "off");
form.appendChild(hidden);
}
function removeViewState(form) {
for (var i = 0; i < form.elements.length; i++) {
var element = form.elements[i];
if (element.name == "javax.faces.ViewState") {
element.parentNode.removeChild(element);
}
}
}
Just include it as <h:outputScript name="some.js" target="head"> inside the <h:body> of the error page. If you can't guarantee that the page in question uses JSF <f:ajax>, which would trigger auto-inclusion of jsf.js, then you might want to add an additional if (typeof jsf !== 'undefined') check before jsf.ajax.addOnEvent() call, or to explicitly include it by
<h:outputScript library="javax.faces" name="jsf.js" target="head" />
Note that jsf.ajax.addOnEvent only covers standard JSF <f:ajax> and not e.g. PrimeFaces <p:ajax> or <p:commandXxx> as they use under the covers jQuery for the job. To cover PrimeFaces ajax requests as well, add the following:
$(document).ajaxComplete(function(event, xhr, options) {
if (typeof xhr.responseXML != 'undefined') { // It's undefined when plain $.ajax(), $.get(), etc is used instead of PrimeFaces ajax.
fixViewState(xhr.responseXML);
}
}
Update if you're using JSF utility library OmniFaces, it's good to know that the above has since 1.7 become part of OmniFaces. It's just a matter of declaring the following script in the <h:body>. See also the showcase.
<h:body>
<h:outputScript library="omnifaces" name="fixviewstate.js" target="head" />
...
</h:body>
Thanks to BalusC since his answer is really great (as usual :) ). But I have to add that this approach does not work for ajax requests coming from RichFaces 4. They have several issues with ajax and one of them is that the JSF-ajax-handlers are not being invoked. Thus, when doing a rerender on some container holding a form using RichFaces-components, the fixViewState-function is not called and the ViewState is missing then.
In the RichFaces Component Reference, they state how to register callbacks for "their" ajax-requests (in fact they're utilizing jQuery to hook on all ajax-requests).
But using this, I was not able to get the ajax-response which is used by BalusC's script above to get the ViewState.
So based on BalusC's fix, i worked out a very similar one. My script saves all ViewState-values of all forms on the current page in a map before the ajax-request is being processed by the browser. After the update of the DOM, I try to restore all ViewStates which have been saved before (for all forms which are missing the ViewState now).
Move on:
jQuery(document).ready(function() {
jQuery(document).on("ajaxbeforedomupdate", function(args) {
// the callback will be triggered for each received JSF AJAX for the current page
// store the current view-states of all forms in a map
storeViewStates(args.currentTarget.forms);
});
jQuery(document).on("ajaxcomplete", function(args) {
// the callback will be triggered for each completed JSF AJAX for the current page
// restore all view-states of all forms which do not have one
restoreViewStates(args.currentTarget.forms);
});
});
var storedFormViewStates = {};
function storeViewStates(forms) {
storedFormViewStates = {};
for (var formIndex = 0; formIndex < forms.length; formIndex++) {
var form = forms[formIndex];
var formId = form.getAttribute("id");
for (var formChildIndex = 0; formChildIndex < form.children.length; formChildIndex++) {
var formChild = form.children[formChildIndex];
if ((formChild.hasAttribute("name")) && (formChild.getAttribute("name").match(/^([\w]+:)?javax\.faces\.ViewState(:[0-9]+)?$/))) {
storedFormViewStates[formId] = formChild.value;
break;
}
}
}
}
function restoreViewStates(forms) {
for (var formIndexd = 0; formIndexd < forms.length; formIndexd++) {
var form = forms[formIndexd];
var formId = form.getAttribute("id");
var viewStateFound = false;
for (var formChildIndex = 0; formChildIndex < form.children.length; formChildIndex++) {
var formChild = form.children[formChildIndex];
if ((formChild.hasAttribute("name")) && (formChild.getAttribute("name").match(/^([\w]+:)?javax\.faces\.ViewState(:[0-9]+)?$/))) {
viewStateFound = true;
break;
}
}
if ((!viewStateFound) && (storedFormViewStates.hasOwnProperty(formId))) {
createViewState(form, storedFormViewStates[formId]);
}
}
}
function createViewState(form, viewState) {
var hidden;
try {
hidden = document.createElement("<input name='javax.faces.ViewState'>"); // IE6-8.
} catch(e) {
hidden = document.createElement("input");
hidden.setAttribute("name", "javax.faces.ViewState");
}
hidden.setAttribute("type", "hidden");
hidden.setAttribute("value", viewState);
hidden.setAttribute("autocomplete", "off");
form.appendChild(hidden);
}
Since I am not an JavaScript-expert, I guess that this may be improved further. But it definitely works on FF 17, Chromium 24, Chrome 12 and IE 11.
Two additional questions to this approach:
Is it feasible to use the same ViewState-value again? I.e. is JSF assigning the same ViewState-value to each form for every request/response? My approach is based on this assumption (and I have not found any related information).
Does someone expect any problems with this JavaScript-code or already ran into some using any browser?

Resources