Friday, February 2, 2018

Codification Web Part

Hi,

We had a requirement as below

1/ Upload the item to the target document library
2/ After adding the item in the list, the value should be auto incremented under the Chrono Column
3/ Upload the document in the target document library
4/ After uploading the document, the value should be auto incremented under the Chrono Column
5/ In the Chrono Config list of the root site, the updated value should be visible under Chrono Increment Value column w.r.t target library GUID
6/The Chrono field should be hidden in the target document library Editform.aspx
7/The Chrono field should be hidden in the target library Editform.aspx
8/After filling mandatory properties, click Save on the upload pop up dialog
9/The value under Codification should come up as per the format specified under FormatDigit column of MC2CodificationConfigList in root site

For this the below java script has been developed

<script language="javascript" type="text/javascript" src="/sites/MC2Mig-DevSite/Style%20Library/js/jquery.min.js"> 
</script>
<script language="javascript" type="text/javascript" src="/sites/MC2Mig-DevSite/Style%20Library/js/sputility.js"> 
</script>
<script language="javascript" type="text/javascript">
//Chrono Variables
var oList, oListItem, oConfigList, oConfigListcount, count = 0, autoincrementcount = 0;
var MC2ChronoConfigList = 'MC2ChronoConfigList';
var ChronoIncrementValue = 'ChronoIncrementValue';
var ChronoFieldColumnName = 'ChronoFieldColumnName';

//Codification Variables
var oCodificationConfigList,oCodificationList
var MC2CodificationConfigList = 'MC2CodificationConfigList';
var SourcePrefixColumnName = 'SourcePrefix';
var SourcePostfixColumnName = 'SourcePostfix';
//var MC2ChronoConfigList = 'MC2ChronoConfigList';
var TargetColumnName='TargetColumn';
var Codification='Codification';
var strChronoColumnValue;
var strSourcePrefixValue;
var strSourcePostfixValue;
var strTargetColumnValue;
var strChronoUpdatedValue;

var strFormatDigitValue;

$(document).ready(function () {
    try { 
                                //alert('entered into ready function');
                                //Get the Chrono Field Auto Increment column details to hide
        getChronoColumnandHide(_spPageContextInfo.siteAbsoluteUrl, "{" + WPQ2FormCtx.ListAttributes.Id + "}");                
                               
                                if(WPQ2FormCtx.FormControlMode == 2)
                                {
                                                //SPUtility.HideSPField('Codification');
                                                //SPUtility.HideSPField(Codification);
                                                getCodificationColumnandHide(_spPageContextInfo.siteAbsoluteUrl, "{" + WPQ2FormCtx.ListAttributes.Id + "}");                   
                                }
    }
    catch (ex) {
        console.log(ex);
    }
});
function getCodificationColumnandHide(webUrl, listGUID) {
    try {
                                //alert('getCodificationColumnandHide');
        var fullUrl = webUrl + "/_api/web/lists/getByTitle('" + MC2CodificationConfigList + "')/items?$select=" + TargetColumnName + "&$filter= Title eq '" + listGUID + "'";
                                //alert(fullUrl);
        $.ajax({
            url: fullUrl,
            type: "GET",
            headers: {
                "accept": "application/json;odata=verbose",
                "content-type": "application/json;odata=verbose",
            },
            success: onQueryConfigCodificationSucceeded,
            error: onQueryConfigCodificationFailed
        });
    }
    catch (ex) {
        console.log(ex);
    }
}
function onQueryConfigCodificationSucceeded(data) {
    if (data.d.results.length != 0) {
                //console.log(data.d.results[0].TargetColumn);                 
                                //alert(data);
        SPUtility.GetSPField(data.d.results[0].TargetColumn).Hide();
    }
}
function onQueryConfigCodificationFailed() {
    alert("An error has occurred.");
}
function getChronoColumnandHide(webUrl, listGUID) {
    try {
        var fullUrl = webUrl + "/_api/web/lists/getByTitle('" + MC2ChronoConfigList + "')/items?$select=" + ChronoFieldColumnName + "&$filter= Title eq '" + listGUID + "'";
        $.ajax({
            url: fullUrl,
            type: "GET",
            headers: {
                "accept": "application/json;odata=verbose",
                "content-type": "application/json;odata=verbose",
            },
            success: onQueryConfigChronoSucceeded,
            error: onQueryConfigChronoFailed
        });
    }
    catch (ex) {
        console.log(ex);
    }
}
function onQueryConfigChronoSucceeded(data) {
    if (data.d.results.length != 0) {
        SPUtility.GetSPField(data.d.results[0].ChronoFieldColumnName).Hide();
    }
}
function onQueryConfigChronoFailed() {
    alert("An error has occurred.");
}

// PreSaveAction Operation
// success: The function to execute if the call is sucessfull
// failure: The function to execute if the call fails
function PreSaveAction() {
    try {
        //WPQ2FormCtx.FormControlMode = 2 - Denotes current form is Edit Form
        //WPQ2FormCtx.FormControlMode = 3 - Denotes current form is New Form
        //WPQ2FormCtx.ListAttributes.ListTemplateType == 101 - Denotes current list is of type Document Library
        //WPQ2FormCtx.ListAttributes.ListTemplateType == 100 - Denotes current list is of type Generic List
                               

        if (WPQ2FormCtx.ListAttributes.ListTemplateType == 101) {                                
            GetMC2ChronoConfigListData()
                                                GetMC2CodificationConfigListData()
        }
        else if (WPQ2FormCtx.ListAttributes.ListTemplateType == 100) {
            if (WPQ2FormCtx.FormControlMode == 3) {
                GetMC2ChronoConfigListData()
            }
            else {               
                return true;
            }
        }
    }
    catch (ex) {
        console.log(ex);
    }

}
function GetMC2CodificationConfigListData()
{

//Get Client Context and Web object. 
    clientContext = new SP.ClientContext.get_current();
    var oWeb = clientContext.get_web();
    oCodificationConfigList = clientContext.get_site().get_rootWeb().get_lists().getByTitle(MC2CodificationConfigList);
    //CamlQuery to fetch records w.r.t List Guid
    var camlQuery = new SP.CamlQuery();
    var listGUID = "{" + WPQ2FormCtx.ListAttributes.Id + "}";
                //alert(listGUID);
    camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'Title\'/>' + '<Value Type=\'Text\'>' + listGUID + '</Value></Eq></Where></Query><RowLimit>10</RowLimit></View>');
    oCodificationConfigListcollListItemColl = oCodificationConfigList.getItems(camlQuery);
    clientContext.load(oCodificationConfigListcollListItemColl);
    clientContext.load(oCodificationConfigList);
    clientContext.executeQueryAsync(onQueryCodificationReadSucceeded, onQueryCodificationReadFailed);

}
function onQueryCodificationReadSucceeded(sender, args) {
    if (oCodificationConfigListcollListItemColl.get_count() != 0) {
                               
        var oCodificationConfigListItem = oCodificationConfigListcollListItemColl.get_item(0);                            
        var strTitle = oCodificationConfigListItem.get_item('Title');                  
                                strSourcePrefixValue=oCodificationConfigListItem.get_item(SourcePrefixColumnName);
                                strSourcePostfixValue=oCodificationConfigListItem.get_item(SourcePostfixColumnName);
                                strTargetColumnValue=oCodificationConfigListItem.get_item(TargetColumnName);
                                strFormatDigitValue=oCodificationConfigListItem.get_item('FormatDigit');                           
                                getChronoColumnValue(_spPageContextInfo.siteAbsoluteUrl, "{" + WPQ2FormCtx.ListAttributes.Id + "}");                                      
                               
        oCodificationConfigListItem.update();
        clientContext.load(oCodificationConfigList);
        clientContext.executeQueryAsync(OnCodificationSuccess, OnCodificationFailure)
                               
    }
  
}

function getChronoColumnValue(webUrl, listGUID) {
    try {
                                //alert('entered into getChronoColumnValue');
                   var fullUrl = webUrl + "/_api/web/lists/getByTitle('" + MC2ChronoConfigList + "')/items?$select=" + ChronoIncrementValue + "&$filter= Title eq '" + listGUID + "'";                    
                               
        $.ajax({
                                                async: false,                      
            url: fullUrl,
            type: "GET",
            headers: {
                "accept": "application/json;odata=verbose",
                "content-type": "application/json;odata=verbose",
            },
            success: onQueryGetConfigChronoSucceeded,
            error: onQueryGetConfigChronoFailed
        });                 
    }
    catch (ex) {
        console.log(ex);
    }
}
function onQueryGetConfigChronoSucceeded(data) {
    if (data.d.results.length != 0) {               
                                strChronoUpdatedValue = data.d.results[0].ChronoIncrementValue;                                                                       
    }
}

function onQueryGetConfigChronoFailed() {
    alert("An error has occurred.");
}

function OnCodificationSuccess(sender, args) {

if (!String.prototype.repeat) {
  String.prototype.repeat = function(count) {
    'use strict';
    if (this == null) {
      throw new TypeError('can\'t convert ' + this + ' to object');
    }
    var str = '' + this;
    count = +count;
    if (count != count) {
      count = 0;
    }
    if (count < 0) {
      throw new RangeError('repeat count must be non-negative');
    }
    if (count == Infinity) {
      throw new RangeError('repeat count must be less than infinity');
    }
    count = Math.floor(count);
    if (str.length == 0 || count == 0) {
      return '';
    }
    // Ensuring count is a 31-bit integer allows us to heavily optimize the
    // main part. But anyway, most current (August 2014) browsers can't handle
    // strings 1 << 28 chars or longer, so:
    if (str.length * count >= 1 << 28) {
      throw new RangeError('repeat count must not overflow maximum string size');
    }
    var rpt = '';
    for (var i = 0; i < count; i++) {
      rpt += str;
    }
    return rpt;
  }
}  
               
                var strCodificationSourcePrefixValue=SPUtility.GetSPField(strSourcePrefixValue).GetValue();       
                var strCodificationSourcePostfixValue=SPUtility.GetSPField(strSourcePostfixValue).GetValue();   
               
                var chronosubstring=strFormatDigitValue.match("C(.*)d");
                var newchronosubstring = chronosubstring[1];
               
                var getchronoformatdigit=newchronosubstring.substring(newchronosubstring.lastIndexOf(":")+1,newchronosubstring.lastIndexOf("."));
                //alert(getchronoformatdigit);
               
                strFormatDigitValue = strFormatDigitValue.replace("{SourcePrefix}",strCodificationSourcePrefixValue)
                strFormatDigitValue = strFormatDigitValue.replace("{SourcePostfix}",strCodificationSourcePostfixValue);
               
                //var getChronoFormatDigitIndex=strFormatDigitValue.indexOf(":")+1;  
                //var getchronoformatdigit=strFormatDigitValue.charAt(getChronoFormatDigitIndex);   
                var chronoformatvalue= String("0".repeat(getchronoformatdigit) + strChronoUpdatedValue).slice(-getchronoformatdigit);                 
                strFormatDigitValue = strFormatDigitValue.replace("{Chrono:"+getchronoformatdigit+".d}",chronoformatvalue);
               
                SPUtility.GetSPField(strTargetColumnValue).SetValue(strFormatDigitValue);
               
                form.SubmitClientForm();
}
function OnCodificationFailure(sender, args) {
    console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
function onQueryCodificationReadFailed(sender, args) {
    alert('An error has occurred. ' + args.get_message() + '\n' + args.get_stackTrace());

}

function GetMC2ChronoConfigListData() {
    //Get Client Context and Web object. 
    clientContext = new SP.ClientContext.get_current();
    var oWeb = clientContext.get_web();
    oConfigList = clientContext.get_site().get_rootWeb().get_lists().getByTitle(MC2ChronoConfigList);
    //CamlQuery to fetch records w.r.t List Guid
    var camlQuery = new SP.CamlQuery();
    var listGUID = "{" + WPQ2FormCtx.ListAttributes.Id + "}";
    camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'Title\'/>' + '<Value Type=\'Text\'>' + listGUID + '</Value></Eq></Where></Query><RowLimit>10</RowLimit></View>');
    oConfigListcollListItemColl = oConfigList.getItems(camlQuery);
    clientContext.load(oConfigListcollListItemColl);
    clientContext.load(oConfigList);
    clientContext.executeQueryAsync(onQueryReadSucceeded, onQueryReadFailed);
}

// Auto Increment Operation
// success: The function to execute if the call is sucessfull
// failure: The function to execute if the call fails
//Method to Compare List Guid from Config List and update Auto Increment Value
function onQueryReadSucceeded(sender, args) {

    if (oConfigListcollListItemColl.get_count() != 0) {
        var oConfigListItem = oConfigListcollListItemColl.get_item(0);
        var strTitle = oConfigListItem.get_item('Title');
        var strChronoIncrementValue = oConfigListItem.get_item(ChronoIncrementValue);
       var strChronoFieldColumnName = oConfigListItem.get_item(ChronoFieldColumnName);
        var currValue = SPUtility.GetSPField(strChronoFieldColumnName).GetValue();
        if (!currValue) {
            SPUtility.GetSPField(strChronoFieldColumnName).SetValue(strChronoIncrementValue + 1)
            oConfigListItem.set_item(ChronoIncrementValue, strChronoIncrementValue + 1);
            oConfigListItem.update();
            clientContext.load(oConfigList);
            clientContext.executeQueryAsync(OnSuccess, OnFailure)
        }
        else
        {
            //form.SubmitClientForm();
        }
    }
    else {
        alert("An error has occurred.");
    }
}
function onQueryReadFailed(sender, args) {
    alert('An error has occurred. ' + args.get_message() + '\n' + args.get_stackTrace());

}

function OnSuccess(sender, args) {
    //form.SubmitClientForm();
}
function OnFailure(sender, args) {
    console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>
Output

Chrono Configuration List






Target Document Library

No comments:

Post a Comment