SharePoint 2013 list column title modification with javascript - javascript

I want to modify SharePoint 2013 list column title in views with javascript. There is a code I found here at stackoverflow, but I want to reference the column with the display name / internal name, not with the column position.
(function () {
function preTaskFormRenderer(renderCtx) {
modifyHeaderData(renderCtx);
}
function modifyHeaderData(renderCtx)
{
var viewTitle = renderCtx.viewTitle;
var linkTitleField = renderCtx.ListSchema.Field[1];
linkTitleField.DisplayName = viewTitle + ':' + linkTitleField.DisplayName;
}
function registerRenderer()
{
var ctxForm = {};
ctxForm.Templates = {};
ctxForm.OnPreRender = preTaskFormRenderer;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ctxForm);
}
ExecuteOrDelayUntilScriptLoaded(registerRenderer, 'clienttemplates.js');
})();

Example:
SP.SOD.executeFunc("clienttemplates.js", "SPClientTemplates", function() {
SPClientTemplates.TemplateManager.RegisterTemplateOverrides({
OnPreRender: function(ctx) {
var field = getFieldByDisplayName(ctx,"Task Name");
if(field)
field.DisplayName = "Task Name:::";
}
});
});
function getFieldByDisplayName(ctx,name)
{
var result = ctx.ListSchema.Field.filter(function(f){return f.DisplayName == name;} ); //find field by display name
return result.length > 0 ? result[0] : null;
}
Result

Related

refresh drop down list after button click in web app

I have a web app with one drop down list and 2 buttons. The drop down list get values from a sheet. The buttons write back in the sheet. The script I have works fine with that:
<script>
$(function() {
$('#txt1').val('');
google.script.run
.withSuccessHandler(updateSelect)
.getSelectOptions();
});
function updateSelect(opt)
{
var select = document.getElementById("sel1");
select.options.length = 0;
for(var i=0;i<opt.length;i++)
{
select.options[i] = new Option(opt[i],opt[i]);
}
}
function listS() {
const selectElem = document.getElementById('sel1')
const index = selectElem.selectedIndex;
if (index > -1) {
const e = document.getElementById("sel1");
const value = e.options[index].value;
const body = { index: index, value: value };
google.script.run.withSuccessHandler(yourCallBack).yourServerSideFunc(body);
}
}
document.getElementById("but1").addEventListener("click",listS);
function yourCallBack(response) {
}
</script>
In Java script:
function getSelectOptions()
{
var ss=SpreadsheetApp.openById('1onuWoUKh1XmvEAmKktwJekD782BFIru-MDA0omqzHjw');
var sh=ss.getSheetByName('Database');
var rg=sh.getRange(2,1,sh.getLastRow()-1,8);
var vA=rg.getValues();
var useremail = Session.getActiveUser().getEmail();
var opt=[];
for(var i=0;i<vA.length;i++)
{
if(vA[i][1] == "Pending Approval"){
if(vA[i][7]+"#xxx.com" == useremail || vA[i][7]+"#xxx.com" == useremail) {
opt.push(vA[i][3]+" REQ ID: "+vA[i][0]);
}
}
};
if (opt.length == 0) {opt.push("You do not have pending requests")};
return opt;
}
function doGet() {
var output = HtmlService.createHtmlOutputFromFile('list');
return output;
}
function yourServerSideFunc(body) {
var value = body["value"];
var ss = SpreadsheetApp.openById('1onuWoUKh1XmvEAmKktwJekD782BFIru-MDA0omqzHjw');
var sh = ss.getSheetByName('Database');
var rg=sh.getRange(1,1,sh.getLastRow()-1,4);
var vA=rg.getValues();
var str = "Approved";
for(var i=0;i<vA.length;i++)
{
if(vA[i][3]+" REQ ID: "+vA[i][0] == value) {
sh.getRange(i+1, 2).setValue(str);
}
};
return ContentService.createTextOutput(JSON.stringify({message: "ok"})).setMimeType(ContentService.MimeType.JSON);
Now I am trying to regenerate the drop down list values after the button is clicked. I tried to add
var output = HtmlService.createHtmlOutputFromFile('list');
return output;
in yourServerSideFunc(body) function to regenerate the HTML but does not work. I have tried to force a HTML refresh, but also did not work.
How can I easily re-trigger the generation of the drop down list items? Worst case scenario it is ok to refresh the whole page, but it should be simple to regenerate the drop down list since I have already the code for it.
I ended up with this work around.
function listS() {
const selectElem = document.getElementById('sel1')
const index = selectElem.selectedIndex;
if (index > -1) {
const e = document.getElementById("sel1");
const value = e.options[index].value;
const body = { index: index, value: value };
google.script.run.withSuccessHandler(yourCallBack).yourServerSideFunc(body);
//ADDED:
var select = document.getElementById("sel1");
select.options[index] = new Option("Approved! Please refresh","Approved! Please refresh");
selectElem.selectedIndex = index;
}
}
It does not really meet the original goal to refresh the list from the sheet. It would be great if someone else posted a solution to call the server function. I tried to add google.script.run.doGet() and similar, but it seems that it does not call the server side functions properly.

How can I get color from CalendarEvent object on google apps script?

I want to get the color(red) below the picture.
enter image description here
I use next code, but I don't know next step.
run main function.
var mainCalendarName = 'main';
function main() {
var calendar = getCalendar();
if (calendar == null) {
return;
}
var now = new Date();
var calendarEventArray = calendar.getEventsForDay(now);
Logger.log('current color = ' + calendarEventArray[0].getColor()); // not use!!!
//log 'current color = #FF0000'
}
function getCalendar() {
var calendarList = CalendarApp.getAllCalendars();
for (i in calendarList) {
if (mainCalendarName === calendarList[i].getName()) {
return calendarList[i];
}
}
return null;
}
First of all you need to enable the Advanced Google Services.
Please see here description how do that.
Then the following code will do the job
function main(){
var now = new Date();
var events = Calendar.Events.list("main", {
timeMin: now.toISOString(),
singleEvents: true,
orderBy: 'startTime',
maxResults: 10
});
for (var i = 0; i < events.items.length; i++) {
Logger.log(events.items[i].colorId); //Here the color of the specific event
}
}

Filter a child picklist in CRM 2011

I'm trying to convert javascript code from CRM 4.0 to CRM 2011.
I'm having problems with a picklist filter.
My function is on the onchange of the parent picklist. It works the first time but the second it erase everything from my child picklist.
This is the part where I suppose to reset the picklist
if(!oSubPicklist.originalPicklistValues)
{
oSubPicklist.originalPicklistValues = oSubPicklist.getOptions();
}
else
{
oSubPicklist.getOptions = oSubPicklist.originalPicklistValues;
oSubPicklist.setOptions = oSubPicklist.originalPicklistValues;
}
And this is the part where i remove all the option not related:
oTempArray is an array with the options that i want to keep. If a check the "oSubPicklist.getOptions.length" the value is the same that my original picklist.
for (var i=oSubPicklist.getOptions.length; i >= 0;i--)
{
if(oTempArray[i] != true)
{
Xrm.Page.getControl("new_product").removeOption(i);
}
}
Ideas?
Edit: I solved declaring a global var with the originalPickList in the onLoad event and:
oSubPicklist.clearOptions();
for (var i=0; i< oSubPicklist.originalPicklistValues.length; i++)
{
for (var j=0; j< oDesiredOptions.length; j++)
{
if (i == oDesiredOptions[j])
{oSubPicklist.addOption(oSubPicklist.originalPicklistValues[i]);}
}
}
Your code is not very clear to me: May be you could paste all your function code for better understanding but:
This is how you get the options from PickList in CRM 2011
var myOptionSet = Xrm.Page.ui.controls.get("new_product") //get Control
var optionsSet = myOptionSet .getAttribute().getOptions(); //get Options
preferredTimeOptionSet.clearOptions(); //Clear all options
//Create a new Option
var opt1 = new Option();
opt1.text = "one";
opt1.value = 1;
//Add Option
myOptionSet.addOption(opt1);
//Remove Option
myOptionSet.removeOption(1);
Good Example here
Here is another way to do Parent/Child picklists:
function dynamicDropdown(parent, child) {
filterPicklist(parent, child);
}
function parentListFilter(parent, id) {
var filter = "";
if (getParentCode(parent) != "") {
filter = getParentCode(parent);
} else {
// No [ ] match
}
return filter;
}
function filterPicklist(parent, child) {
var parentList = Xrm.Page.getAttribute(parent).getValue();
var childListControlAttrib = Xrm.Page.getAttribute(child);
var childListOptions = childListControlAttrib.getOptions();
var childListControl = Xrm.Page.getControl(child);
var codeToFilterListOn = parentListFilter(parent, parentList);
if (codeToFilterListOn != "") {
childListControl.clearOptions();
for (var optionIndex in childListOptions) {
var option = childListOptions[optionIndex];
// Ignore xx and check for Match
if (option.text.substring(0, 2) != "xx" && option.text.indexOf(codeToFilterListOn) > -1) {
childListControl.addOption(option);
}
}
} else {
// Didn't match, show all?
}
}
function getParentCode(parent) {
//Get Parent Code Dynamically from inside [ ]
var filter = "";
var parentValue = Xrm.Page.getAttribute(parent).getText();
if (parentValue && parentValue.indexOf("]") > -1) {
var parentCode = parentValue.substring(parentValue.indexOf("[") + 1, parentValue.indexOf("]"));
if (parentCode) {
filter = parentCode + " | ";
} else {}
}
return filter;
}
See more here: Parent/Child

How to dymically update object on input change?

I have a input tab that I want to update dynamically. When the user changes the value of the input, the new value should replace the old value of the object inside the array.
I am way off the mark here. Can somebody help me out.
function Skills () {
var Skills = this;
this.skill = new Array();
this.skill[0] = {
id: '1_skill_field',
value: 'Insert Skill',
//change function to be used when user changes the value.
change:function (input) {
Skills.skill[parseInt(input.id)["value"]=$("#"+input.id).val();
}
}
var create_section_field = function () {
var section_field = $('<div class="section_fields"></div>');
section_field.appendTo('#skill');
}
var create_fields = function () {
var input_field = $('<div class="input_fields"></div>');
input_field.appendTo('#skill .section_fields');
var skill_field=$('<input>', {
name: '1_skill_field',
id: Skills.skill[0]["id"],
value: Skills.skill[0]["value"],
type: 'text',
//onChange uses function to change saved value of object inside array
onChange: Skills.skill[0].change(this)
});
skill_field.appendTo($('#skill .input_fields'));
}
}
i made what you were doing...here take a look:
http://jsfiddle.net/V4HLz/1/
it was kinda fun. :D
var type = $('#type'),
input = $('#input'),
btn = $('#update'),
show = $('#out'),
stats = $('.skills');
var value, sType, skills={};
btn.click(function(){
value = parseFloat(input.val().trim());
sType = type.val();
if (!value || !sType) return;
skills.update(sType,value);
updateInput();
});
type.change(updateInput);
function updateInput() {
input.val(skills.data[type.val()]);
}
skills.update = function(t,v){ this.data[t] = v; };
skills.data = {
eating:0,
fighting:0,
flying:0,
reg:0
};
show.click(function(){
$.each( skills.data, function(k,v){
stats.find('#'+k).children('span').text(v);
});
});

javascript on action error

after changing the select box it must collect checked check box ids and the submit it
$("#action").change(function(){
if(($(this).val())!='0'){
var data = { 'req_ids[]' : []};
var doit = $("#action").val();
$(".checkboxes:checked").each(function(){
data['req_ids[]'].push($(this).attr('id'));
});
var size = Object.size(data['req_ids[]']);
if(size>0){
$.post("workplan-requests.php?action=update&do="+doit, data);
$("tr.checked").remove();
}
$("#action").val('0');
}
});
but when i select my action in select box by changing it,
it show this error:
TypeError: Object.size is not a function
var size = Object.size(data['req_ids[]']);
i know this error is because the java script run whole code at same time but how can i do this with out problem!?
it should be
var size = data['req_ids[]'].length;
Also try
$("#action").change(function () {
if (($(this).val()) != '0') {
var data = {};
data['req_ids[]'] = $(".checkboxes:checked").map(function () {
return this.id
}).get();
var size = data['req_ids[]'].length;
if (size > 0) {
var doit = $("#action").val();
$.post("workplan-requests.php?action=update&do=" + doit, data);
$("tr.checked").remove();
}
$("#action").val('0');
}
});

Categories