Creating whole new view based on current user's group sharepoint 2013 - javascript

I am trying to generate a view based on the current user's group name. Group Name I am gathering from the custom list.
My question is how to apply the gathered group name to 'Group Name' column as a view parameter.
The only solution I figured:
I have created a view with a parameter.
I have added an HTML Form Web Part into the same page and connected it to the list view (sending the value to the parameter via web part connection). Then with a window.onload function I gather the current user's group name and pass this value via Form Postback function. But since the Postback function triggers full page reload, it falls into the endless loop of form submission > page reload.
Another way I have tried is attaching a click event listener to the BY MY GROUPS tab and it works perfectly, but the only disadvantage is that the page reloads each time user clicks on this tab, which I would like to avoid.
So the solution that I need is a way to post the form without a page reload.
Another option suggested here is to use CSR (client side rendering), but that has its own problems:
This code does not work as it is supposed to. In the console it shows me correct items, but the view appears untouchable.
Even if it worked, the other column values are still viewable in the column filter, as in this screenshot:
So, it seems that CSR just hides items from the view (and they are still available). In other words its behavior is different from, for example, a CAML query.
Or am I getting it wrong and there's something wrong with my code?
Below you can find my CSR code:
<script type='text/javascript'>
(function() {
function listPreRender(renderCtx) {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {
var currUserID = _spPageContextInfo.userId;
var cx = new SP.ClientContext('/sites/support');
var list = cx.get_web().get_lists().getByTitle('Group Members');
var items = list.getItems(SP.CamlQuery.createAllItemsQuery());
cx.load(items, 'Include(_x006e_x50,DepID)');
cx.executeQueryAsync(
function() {
var i = items.get_count();
while (i--) {
var item = items.getItemAtIndex(i);
var userID = item.get_item('_x006e_x50').get_lookupId();
var group = item.get_item('DepID').get_lookupValue();
if (currUserID === userID) {
var rows = renderCtx.ListData.Row;
var customView = [];
var i = rows.length;
while (i--) {
var show = rows[i]['Group_x0020_Name'] === group;
if (show) {
customView.push(rows[i]);
}
}
renderCtx.ListData.Row = customView;
renderCtx.ListData.LastRow = customView.length;
console.log(JSON.stringify(renderCtx.ListData.Row));
break;
}
}
},
function() {
alert('Something went wrong. Please contact developer')
}
);
});
}
function registerListRenderer() {
var context = {};
context.Templates = {};
context.OnPreRender = listPreRender;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(context);
}
ExecuteOrDelayUntilScriptLoaded(registerListRenderer, 'clienttemplates.js');
})();
</script>

Related

Deleted images still being shown

For some reason, my website still showing images that were already deleted from the specified folder and I have no idea why that's happening and how to solve that.
Process: When the button to delete all admins is pressed, it calls a PHP function that truncate the tables administration, adminimg and login, delete all images from a folder related to id's on table administration with unlink(), and create a registry on administration table with id=1(auto_increment) and name="abc".
Problem: I have a jQuery function that display a specific admin information on textboxes, verify the value in the textbox for the adminID, and display the image associated to that id. After executing the process above, when i call the jQuery function, it display correctly the id=1 and name="abc" but shows the deleted image associated to the admin with id=1 before truncate the tables.
jQuery function (if necessary)
$(".btneditadmin").click( e =>{
let textvalues = displayDataAdmin(e);
let id = $("input[name*='idadmin']");
let name = $("input[name*='nameadmin']");
id.val(textvalues[0]);
nome.val(textvalues[1]);
var img_url = 'Images/Administration/admin'+$("#idadmin").val()+'.jpg';
$("#admin-image").attr('src',img_url);
});
function displayDataAdmin(e) {
let id = 0;
const td = $("#tbody tr td");
let textvalues = [];
for (const value of td){
if(value.dataset.id == e.target.dataset.id){
textvalues[id++] = value.textContent;
}
}
return textvalues;
}
If you're sure that image isn't there anymore then it's caching issue and something like this would take care of it
let img_url = 'Images/Administration/admin'+$("#idadmin").val()+'.jpg';
img_url += '?' + new Date().getTime() ; // cache killer
$("#admin-image").attr('src', img_url);
However, you're calling that function no matter what so I would suggest a onload/error check
​$('#admin-image').load(function(){ // when loaded successfully
console.log('success');
}).error(function(){ // when theres an error
$(this).remove()
// or you could replace it with a default image
$(this).attr('src', '/images/default.jpg');
});​​​​​

Multiplication of two input table element values on html form row not working (Google Webapp)

I am trying to create an order form as a table, where a user enters a quantity required for a product in a row and the corresponding value is calculated by multiplying the user entry by the price held in another element of the same row of the table.
The form is loaded as a WebApp via Google and uses an Apps Script to retrieve the table values from a Google Sheet. The form loads OK with the data as expected but I just can't get the calculation part to work.
If I click the "place Order" button at the bottom of the form, the numberUsed values are included as parameters in the URL so it looks as though the values are updating in those elements but I haven't been able to access them to do the calculation and display it in the element called "value".
I am a novice programmer so I am sure it is something basic I am doing wrong (or not doing). I have created a JSBin https://jsbin.com/siwerat/edit?html,js,console,output and I have tried several variations of code derived from other answers and videos over the last couple of weeks without success so any help will be much appreciated.
//var numRows;
document.addEventListener('DOMContentLoaded', function() {
//new
var elems = document.querySelectorAll('cart');
var instances = M.FormSelect.init(elems);
// end new
document.getElementByname("cart").addEventListener("submit", getValues); //used to submit form - needs validation
//document.getElementByName("numberUsed").addEventListener("oninput",getValues);//used to submit form - needs validation
});
function test(event) {
"use strict";
event.preventDefault();
console.log("getValues function triggered");
}
function getValues() {
event.preventDefault();
var rows = document.querySelectorAll("package-row");
rows.forEach(function(currentRow) {
var numberUsed = Number(currentRow.querySelector('#numberUsed').value);
var price = Number(currentRow.querySelector('#price').value);
//var inPackage = Number(currentRow.querySelector('#inPackage').value);
var inPackage = 1;
var revenue = 1;
document.querySelectorAll('numberUsed');
if (numberUsed == "") {
if (isNaN(inPackage) || isNaN(price)) {
return;
}
revenue = price * inPackage;
} else {
if (isNaN(numberUsed) || isNaN(price)) {
return;
}
revenue = price * numberUsed;
}
var value = revenue * 5;
//currentRow.querySelector("#revenue").innerHTML = revenue;
currentRow.querySelector("#value").innerHTML = value;
});
}
Thanks Rafa for the guidance. After further reading/analysis I have got it working. The Event bubbling video by Learn Google Spreadsheets: [https://www.youtube.com/watch?v=fYpGe5ngujk][1] and an article on EncodeDNA.com (Dynamically create HTML table and Button using Javascript) helped narrow down the issues I had to get a solution.

How to populate jqGrid filter toolbar and search when the page loads (ASP.net webforms)

Currently, I'm trying to populate the filterToolbar with values taken in from a cookie. If there is cookie data for the filters, I want it to fill the respective textboxes and filter the jqGrid for that data.
I'm using ASP.net webforms, so most of my data is initialized already. How/where could I add javascript in order to get this going?
I actually figured out what I was doing.
So what I ended up doing as a solution was adding a timeout function in the document.ready function
$(document).ready(function () {
// some code
setTimeout(function () {
$('#Jqgrid1')[0].triggerToolbar();
}, 500)
//some code
}
My guess is that I couldn't use the $('#grid')[0].toggleToolbar() to force it because whenever I tried to use it, it was before the whole grid was finish setting up.
In the ASP webform, I had several functions registered.
<cc1:JQGrid ID="Jqgrid1" runat="server"
Height="630"
SearchDialogSettings-Draggable="true"
EnableViewState="false"
AutoWidth="True" >
<ClientSideEvents
LoadComplete="Jqgrid1_LoadComplete"
GridInitialized="initGrid"
/>
<%-- grid code --%>
</cc1:JQGrid>
The LoadComplete is executed after the grid is loaded. I tried doing triggering my toolbar there, but didn't work. My guess is, again, it was too early in the grid execution to use the triggerToolbar() function.
The same went for the GridInitialized events (even though both events would seem to imply to me that the grid is done doing its thing... but whatever...)
The way that I read my cookies in was actually in the GridInitialized event handler.
function initGrid() {
var myJqGrid = $(this);
var valueName = 'GridFilters';
var myCookie = document.cookie;
var gridFilterString;
var gridFilterArray;
var currentFilter;
var myCookie_arr;
var myDic = {};
if (myCookie.indexOf(valueName) > -1) { // don't even bother if the cookie isn't there...
myCookie_arr = myCookie.split("; "); // looking for the cookie I need
// read cookies into an array
for (var i = 0; i < myCookie_arr.length; i++)
{
parts = myCookie_arr[i].split("=");
first = parts.shift(); // remove cookie name
myDic[first.trim()] = parts.join("=").trim(); // handles multiple equality expressions in one cookie
}
if (myDic.hasOwnProperty("GridFilters"))
gridFilterString = myDic["GridFilters"];
if (gridFilterString != "NONE") {
myFiltersDic = {}
myFiltersArr = gridFilterString.split("&")
for (var i = 0; i < myFiltersArr.length; i++) {
parts = myFiltersArr[i].split("=");
myFiltersDic[parts[0].trim()] = parts[1].trim();
}
myParams = $(this).jqGrid("getGridParam", "postData");
var filters = []
for (keys in myFiltersDic) {
$('#gs_' + keys.trim()).val(myFiltersDic[keys].trim());
}
$.cookie('m_blnSearchIsHidden', "0", "/");
if (!isLoaded)
{
$(this)[0].toggleToolbar();
}
isLoaded = true;
}
}
}

On page reload, check boxes get selected and then disappear automatically within a second

I have a problem with a function that i'm writing.
Basically, I'm simulating a landing page. The landing page will contain a querystring. What I'm doing is to deserialize it on a button click and show(to check) the checkboxes defined in the querystring in the HTML.
Below is the click function which contains two functions.
The first one "simulateLandingPage" performs the url change.
The second one called "selectFacetsAutomatically" deserializes the "landingUrl" path and checks automatically the checkboxes in the HTML page according to what is defined in the querystring.
The problem that I'm encountering is that when I click on the "reload-page" button everything works but the checkboxes get selected just for a second and then disappear automatically quickly without any reason. Hence the page won't show the selected checkboxes in the end but just this weird thing.
Can anyone help? I'm pretty new to this and i'm stuck.
Thanks a lot!
$(".reload-page").click(function() {
var landingUrl = "size:4,10,16|base_colour:1,4|brand:53,3392,12767";
simulateLandingPage(landingUrl);
selectFacetsAutomatically(landingUrl);
return false;
});
function simulateLandingPage(landingUrl){
window.location.href = "refinements.html?refine="+ encodeURIComponent(landingUrl);
return false;
}
function selectFacetsAutomatically(landingUrl){
var facetGroup = [];
var selectedFacets = [];
var facetType;
//split string when it finds the pipe symbol
$.each(decodeURIComponent(landingUrl).split(/\|/), function (i, val) {
selectedFacets.push(val);
console.log("val", selectedFacets[i].split(/\:/)[1].split(/\,/));
facetType = selectedFacets[i].split(/\:/)[0];
facetGroup = selectedFacets[i].split(/\:/)[1].split(/\,/);
$.each(facetGroup, function(i,val){
var facetToBeSelected = facetType + "_" + val;
$('[data-id='+facetType+']').find("#"+facetToBeSelected).prop('checked', true);
});
});
return false;
}

Differing one button from another on a prototype object jquery

first, the prototype:
function Notification (title, message, id) {
var $title = this.title = title;
var $message = this.message = message;
var $id = this.id = title;
/* ---------------creating HTML prototype */
var $mainDiv = $("<div></div>").appendTo($("#wrapper"));
$mainDiv.attr('id', $id);
$mainDiv.addClass('main-div');
var $dismissButton = $("<button>X</button>").appendTo($mainDiv);
$dismissButton.attr('id', 'dismissButton');
var $pTitle = $("<h2></h2>").appendTo($mainDiv);
$pTitle.attr('id', 'title');
$pTitle.text($title);
var $para = $("<p></p>").appendTo($mainDiv);
$para.attr('id', 'message');
$para.text($message);
var $ul = $("<ul></ul>").appendTo($mainDiv);
var $li1 = $("<li></li>").appendTo($ul);
$li1.attr('id', 'okButton');
var $button = $("<button>Ok</button>").appendTo($li1);
$button.addClass('buttons');
/* ---------------Dismissing notifications */
$("#dismissButton").click(function() {
document.getElementById($id).remove();
});
};
So, the prototype is made using new Notification(*arguments here*) and there we get a box with a notification widget. so far so good.
when i press the X button (id dismissbutton) it should remove the box, and it does.
However. if i use the new notification several times i get several boxes (with different ids for the $mainDiv) with their dismiss buttons not working. the upmost widget box's dismiss button is the only one that works, and it deleted all the other boxes as well.
I need to seperate them and have the dismiss button working for each box seperately.
thanks in advance :)
The problem here is that you are creating multiple elements with the same ID (which is invalid HTML by the way).
Every time your run
var $dismissButton = $("<button>X</button>").appendTo($mainDiv);
$dismissButton.attr('id', 'dismissButton')
A new "dismiss button" is being created, which has the same ID (dismissButton) with the previous "dismiss buttons" (if any).
The other thing is that every time you run
$("#dismissButton").click(function() {
document.getElementById($id).remove();
});
You instruct only the first "dismiss button" to remove the element identified by the ID $id when clicked.
In my opinion the best way to fix this is by using references to the elements themselves and not IDs.
So I would make the creation of the dismiss button like this;
var $dismissButton = $("<button>X</button>").appendTo($mainDiv);
And determine its click callback like this
$dismissButton.on('click', function () {
$mainDiv.remove();
});
This should work fine for you.
Last, but not least I would avoid giving the same ID to any elements, since it produces invalid HTML code. You are doing so in the following lines
$dismissButton.attr('id', 'dismissButton');
$pTitle.attr('id', 'title');
$para.attr('id', 'message');
$li1.attr('id', 'okButton');

Categories

Resources