Thursday, August 30, 2018

Language translator in JavaScript

Hi Folks,

I got a requirement to translate SharePoint list form to multiple languages. I tested with translating from English to Portuguese and German. We can add further languages later. I took use of the link to implement the translation. It is good but I faced issues in translating the text in buttons as for buttons, it is of 'input' type and we need to translate the values stored in those input controls. Also, I've to use a SharePoint list which will have the translations based on respective word in list form. So I've to make changes to the translate.js file referred in the above link to extend the functionality.

Please see below for original and translated form.
Original Form

Translated Form


The JavaScript written in the page is mentioned here:
<script type="text/javascript" src="../../SiteAssets/Scripts/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="../../SiteAssets/Scripts/jquery.translate.js"></script>
<script type="text/javascript" src="../../SiteAssets/Scripts/Dictionary.js"></script>
<script type="text/javascript">

$(function() {

$(".js-category").find("label").each(function(){
var text = $(this).text();
$(this).empty().append( $("<span></span>").addClass("trn").text(text) );
});
$(".js-category").find("select option").each(function(){
$(this).addClass("trn");
});
$(".js-category2").find("label").each(function(){
var text = $(this).text();
$(this).empty().append($("<span></span>").addClass("trn").text(text));
});
$(".js-category3").find("label").each(function(){
var text = $(this).text();
$(this).empty().append( $("<span></span>").addClass("trn").text(text));
});
$(".btnSaveCancl").find("input[type=button]").each(function(){
$(this).addClass("trn");
})
$("nobr").each(function(){
var text = $(this).text();
$(this).empty().append($("<span></span>").addClass("trn").text(text));
//alert(text);
});

});
</script>




The link suggested to add <span class="trn">Your_Text</span> to translate the text. It could able to translate the field labels but not the text which is generated dynamically in my SharePoint fields. So I had to add class to the td's and add JavaScript to add the span dynamically. Please check below.


The jquery.translate.js file referred externally is mentioned below.
/**
 * @file jquery.translate.js
 * @brief jQuery plugin to translate text in the client side.
 * @author Manuel Fernandes
 * @site
 * @version 0.9
 * @license MIT license <http://www.opensource.org/licenses/MIT>
 *
 * translate.js is a jQuery plugin to translate text in the client side.
 *
 */

(function($){
  $.fn.translate = function(options) {

    var that = this; //a reference to ourselves
    var settings = {
      css: "trn",
      lang: "en"/*,
      t: {
        "translate": {
          pt: "tradução",
          br: "tradução"
        }
      }*/
    };
    settings = $.extend(settings, options || {});
    if (settings.css.lastIndexOf(".", 0) !== 0)   //doesn't start with '.'
      settings.css = "." + settings.css;
       
    var t = settings.t;

    //public methods
    this.lang = function(l) {
      if (l) {
        settings.lang = l;
        this.translate(settings);  //translate everything
      }
        
      return settings.lang;
    };


    this.get = function(index) {
      var res = index;
 var _l = settings.lang;
      try {
        //res = t[index][settings.lang]; //takes object
        
        for(var item in t[index]){ //takes array of objects
        if( t[index][item].hasOwnProperty(_l) ){ 
        res = t[index][item][_l];
        break;
        }
        }     
      }
      catch (err) {
        //not found, return index
        return index;
      }
      
      if (res)
        return res;
      else
        return index;
    };

    this.g = this.get;


    
    //main
    this.find(settings.css).each(function(i) {
      var $this = $(this);

      var trn_key = $this.attr("data-trn-key");
      if (!trn_key) {
        trn_key = ($this.is('input') && $this.attr('type')==='button') ? $this.val() : $this.html();
        $this.attr("data-trn-key", trn_key);   //store key for next time
      }
if($this.is('input') && $this.attr('type')==='button'){
$this.val(that.get(trn_key));
}
else{
 $this.html(that.get(trn_key));
}
    
    });
    
    
return this;

  };
})(jQuery);



For button, I had to modify the code with these steps.

This helped me to create a basic prototype for translation.

I created Dictionary.js to read translations from a SharePoint list and perform translation to the SharePoint list form.

var dict = '{';
var _t;
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', RetrieveListItems);

function RetrieveListItems(){
var clientContext = SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('Translation');
var caml = new SP.CamlQuery();
caml.set_viewXml("<View />");
listItemCollection = oList.getItems(caml);
clientContext.load(listItemCollection);
clientContext.executeQueryAsync(onRequestSucceeded, onRequestFailed);
}

function onRequestSucceeded(){
var count = listItemCollection.get_count();
//alert(count);
var listEnumerator = listItemCollection.getEnumerator();
while(listEnumerator.moveNext()){
var listItem = listEnumerator.get_current();
var key = listItem.get_item('Title');
var val = listItem.get_item('Value');
var ger = listItem.get_item('German');
//alert(key+' , '+val);
var item_dict = '"'+key+'":[{"pt":"'+val+'"},{"en":"'+key+'"},{"ge":"'+ger+'"}],';
dict = dict + item_dict;
//alert(dict);
}
dict = dict.substring(0, dict.length-1) + '}';
var newList = JSON.parse(dict);
_t = $('body').translate({t: newList});
console.log(dict);
 $(".lang_selector").click(function(ev) {
 
    var lang = $(this).attr("data-value");
    //alert(lang);
    _t.lang(lang);

    console.log(lang);
    ev.preventDefault();
  });

}

function onRequestFailed(sender, args){
alert('Error: ' + args.get_message());
}



The new jQuery.translate.js takes an array of objects unlike the previous object as we couldn't able to create dynamic dictionary and had to create string array in specific format. Then we parse it as JSON and transferred the object array for translation.




Thanks,
Kunal

Tuesday, August 28, 2018

Update multi-value lookup fields from source to destination lists.

Hi Folks,

I would like to share my experience on updating the multi-value lookup field values from source list to multi-value lookup field in destination list.
I tried several things but one thing is sure, we cannot achieve it using SharePoint 2013 workflow 'Update List item' step. I had to include SharePoint 2010 WF within SharePoint 2013 WF. Also, I need to keep current item's lookup field type as 'string' to make it work.


'Update IT Systems' is SharePoint 2010 WF which I started within SharePoint 2013 WF. Please see below.

It resolved my issue. The big part is none of the blogs in google have provided a working solution. So, I am writing this blog to save some lives :-).

Thanks,
Kunal

Friday, December 22, 2017

Customize the Printable view of a SharePoint list form

Hi Folks,

I got a task to customize the print view of 'DispForm.aspx'. I've utilized '@print media' query to achieve the functionality.I created a custom CSS file to add the '@print media' query.

The CSS file look as below.
#logo img{
display:none;
 }
 h2
 {
font-weight:bold;
 }
h3
{
font-weight:bold;
}
#tabHead
{
display:none;
}
#tabFooter img{
display:none;
}

@media print 
{
 nobr
 {
  font-weight:bolder;
  font-size:22px;
  font-family:Arial;
 }
 .ms-formbody
 {
font-size:22px;
font-family:Arial;
 }
 #logo img
 {
display:block;
height:80px;
direction:ltr;
top:auto;
 }
 .ms-standardheader
 { 
background-position:center;
text-align:left;
 }
 #tabPos > tbody:nth-child(2)
 {
padding-right:15px;
`}
 #tabPos
 {
text-align:left;
border:2;
width:80%;
 }
 #WebPartWPQ2 > table > tbody > tr:nth-child(3) > td
 {
 }
 .hideField
 {
display:none;
 }
 #WebPartWPQ2 > table > tbody > tr:nth-child(4) > td > table
 {
display:none;
 }
 #tabHead
 {
display:table-cell;
font-size:24px;
font-family:Arial;
 }
 #tabFooter img
 {
display:block;
 }
}

The print view would be displayed as shown below.












It helped me a lot and we can use it for future purpose.

Thanks,

JS Link use to display image hyperlink to List view column

Hi All,

I had a task to display an image hyperlink for the list view column. By clicking the image it will navigate to a page which is styled in print view of page.

At first, I added a single line of text field - PrintForm. Then I create a custom standard view- Print View. 'PrintForm' will be available in 'PrintView.aspx'.
I edit the page at first and then edit the web part which contains the web part.
I wrote a small JS code to achieve the functionality.

SP.SOD.executeFunc("clienttemplates.js", "SPClientTemplates", function() {

SPClientTemplates.TemplateManager.RegisterTemplateOverrides({
  Templates: {
Fields: {
           'PrintForm': {'View':function(ctx) {         
           return String.format("<a href='<CustomizedDisplayForm>.aspx?ID={0}' target='_blank'><img src='<ImageUrl>' width='42' height='42'></a>",  ctx.CurrentItem.ID);
}}

        }//Fields
  }//Templates
});
})


Once I completed the JS code, I appended the path of .js file to JS link in Miscellaneous section. After I saved the changes, the view would like as shown below.






Thanks for reading my post, I'll write another for print section.

Monday, September 18, 2017

PowerShell Error :- The local farm is not accessible.

Hi All,

I got a task to read all the users from SharePoint 2010 site. I used PowerShell Script to load the SharePoint DLLs and PowerShell script to read all the user profile information.

But, unfortunately the I got the below error.

I did some research and got to know that I don't have access to Shell Admin. It needs to be done explicitly. You can do it by yourself if you have Farm admin access.
SharePoint creates a shell admin security role in the database which is configurable through powershell
that's all that there is to it, you only need security admin to assign it
you never need database owner for any SharePoint work.

I used the below PowerShell script to add myself to Shell Admin.
$db = Get-SPDatabase | Where {$_.Name -eq “SharePoint_ConfigDB”}
Add-SPShellAdmin “domain\user_to_add” -database $db  

After the script got executed, I could able to run the PowerShell script to load user profile information.

The below link can help you with more information.


Thanks,
Kunal


Saturday, May 13, 2017

Running PowerShell Scripts in MOSS 2007 Server

Hi Folks,

I worked on a Proof of Concept to read all the user's usernames and their email addresses from a MOSS 2007 site. I've gone through many blogs where it mentioned to install Microsoft PowerShell 1.0. But believe me, it can work even with 'Windows PowerShell ISE' available in Start >> All Programs >> Accessories >> Windows PowerShell >> Windows PowerShell ISE. You need to run the scripts in the MOSS 2007 Server where your MOSS 2007 site is hosted.

I prefer you to read the below blog to set up PowerShell in MOSS 2007 Server.

https://nickgrattan.wordpress.com/2007/09/03/preparing-powershell-for-sharepoint-and-moss-2007/

You need to load file Microsoft.PowerShell_profile.ps1 before running the below script UserProfiles.ps1

[string]$FileName = ".\UsersList.csv"
$FileHeader = '"UserName", "Email"'
Add-Content -path $FileName -value $FileHeader
$site = New-Object Microsoft.SharePoint.SPSite("http://localhost/sites/intranet")
$groups = $site.RootWeb.sitegroups
foreach ($grp in $groups) {
foreach ($user in $grp.users) {
$UserEntry = '"'+ $user.name +'" ,+ "'+ $user.Email+'"'
Add-Content -path $FileName -value $UserEntry
} }
$site.Dispose()

This script also writes Usernames and Email Addresses to a CSV file.

The below mentioned link helped me to write the above script.
http://techtrainingnotes.blogspot.in/2010/12/sharepoint-powershell-script-to-list.html


Thanks,

Thursday, February 23, 2017

Countdown Web part

Add Add-ins for SharePoint

To add this add-in to your site, you'll need to have the latest version of SharePoint installed. Get the newest version of SharePoint.
1. Go to the SharePoint site where you want to install this add-in.
The URL might look like this: http://mycompany/myteam

2. Click the Settings icon at the top right corner of your site, and then click Add an add-in.
Settings

3. In the Find an add-in search box, paste the following tag and then click Search.
WA104379311

4. Click the text that tells you to check out the result in the SharePoint Store.

Link: https://store.office.com/help/addsharepointapps.aspx?ai=WA104379311