Thursday, 30 June 2016

SharePoint 2013 List Form Validation and List Control Events by using Jquery

The purpose of this writings is to generate jquery events on the basis of id of a particular list field. Our first target should be to select and get the id of a form field as shown below:
Select the control to get the Id

People Picker/User Field Focus Out/Changed Event Using Jquery


Catch focus out event of a user field as follows:



$("#ctl00_SPWebPartManager1_g_840570ae_f359_466e_b37c_b99ae98c9690_ff171_ctl00_ctl00_UserField").focusout(function()

{
    /* To get the first people picker in the form */

var eEntityData
 =$('#ctl00_SPWebPartManager1_g_57601f17_1a6d_471e_8c5e_d12b25ea3114_ff31_ctl00_ctl00_UserField_containerCell').find('div').eq(1) 

if (eEntityData.length > 0 ) 


      {   
          $('.hrm-depatment').show(100);

      }

}


Check Radio Button Checked Event


Do Something for a radio button checked option:

if ($('#ctl00_SPWebPartManager1_g_68a0d33a_a74a_4692_9dd9_d2fa635d4771_ff121_ctl00_ctl00').is(":checked")

||  $('#ctl00_SPWebPartManager1_g_68a0d33a_a74a_4692_9dd9_d2fa635d4771_ff121_ctl00_ctl01').is(":checked"))                

  
   {
        $('.OtherCompany').show(100);
   }    


Check DropDown Selected Indexed Changed Event


Dropdown changed event in jquery can be done using the corresponding column name:


 $("select[title^='Employer']").change(function()

   {
           if ($(this).val() == "Shovon")

   {
                            

                             $('.divTitle').show(100);
                             $('.divLevel').show(100);
                     }
    }



Catch Text Changed Event of a Input Text Field in List Form

It is as simple as drop-down but only using the id this time:


$('#ctl00_SPWebPartManager1_g_68a0d33a_a74a_4692_9dd9_d2fa635d4771_ff221_ctl00_ctl00').change(function()

     {                              
               $('.answer4-class').show(100);                                            
     });


The same thing can be done by using the field name of the text field:


$("[title^='Question4']").change(function()



    {
          $('.answer4-class').show(100); 
    }


Thats all for today. Happy SharePointing...............................:)



Monday, 13 June 2016

Use PreSaveAction method for conditional client side validation using a list form SharePoint 2013


It is possible to check validation of list fields before the save button is clicked on a list form:

Suppose, We have a list form like below:


If the Save button is pressed, a method named PreSaveAction() is always executed by default. You can just write a function named as PreSaveAction in a .js file and link the file to the desired list form.

You can place all your validation code in the method as shown in the section below. These validations are client side validation using jquery.

function PreSaveAction()
{
    //--List Field HRBP 
    if($('#ctl00_SPWebPartManager1_g_840570ae_f359_466e_b37c_b99ae98c9690_ff21_ctl00_ctl00_UserField').text().trim() =="")
    {
$('#vld-hrbp').show();
$('#vld-hrbp').css('color','red');
return false;
    }
    else
    {
    $('#vld-hrbp').hide();
    }
     
    //---List Field Hiring Manager
    if($('#ctl00_SPWebPartManager1_g_840570ae_f359_466e_b37c_b99ae98c9690_ff31_ctl00_ctl00_UserField').text().trim() == "")
         {
      $('#vld-hrmanager').show();
      $('#vld-hrmanager').css('color','red');
      return false;
         }
    else
         {
    $('#vld-hrmanager').hide();
$('#vld-hiring-depatment').hide()
        }
}


Happy SharePointing........................:)

Wednesday, 28 October 2015

Set Display Name of fields of a SharePoint List in SharePoint 2013



There may be necessity to change the display name of a field of SharePoint list in order to handle localization issue. The following code snippets illustrates how to do that in C#.





Suppose we have list called PLinks. 




    public static void SetDisplayNamePLinkListFields(ClientContext context)

        {

            Web web = context.Web;



            List lstPlinks = web.Lists.GetByTitle("PLinks");

            context.Load(lstPlinks);
            context.ExecuteQuery();


            // Get Field Reference or Internal Name

           Field fieldBackgroundImageLocation  =
           lstPlinks.Fields.GetByInternalNameOrTitle("BackgroundImageLocation");


           // Set Display Name

           fieldBackgroundImageLocation.Title ="Background Image Location" ;


           fieldBackgroundImageLocation.Update();




            Field fieldDescription = lstPlinks.Fields.GetByInternalNameOrTitle("Description");

            fieldDescription.Title ="Description of Image" ;
            fieldDescription.Update();


            Field fieldLinkLocation = lstPlinks.Fields.GetByInternalNameOrTitle("LinkLocation");

            fieldLinkLocation.Title ="Link Location";
            fieldLinkLocation.Update();


            Field fieldLaunchBehavior =
            lstPlinks.Fields.GetByInternalNameOrTitle("LaunchBehavior"); 
            fieldLaunchBehavior.Title ="Launch Behavior" ;
            fieldLaunchBehavior.Update();


            Field fieldDisplayOrder = lstPlinks.Fields.GetByInternalNameOrTitle("DisplayOrder");

            fieldDisplayOrder.Title ="Display Order" ;
            fieldDisplayOrder.Update();



            lstPlinks.Update();



        } 


Happy SharePointing....................:)

Sunday, 25 October 2015

Programmatically check if a field is already existed in a SharePoint list or not using CSOM


In the method below, it is checked that if a particular field is already created/existed in a SharePoint 
list  or not. The return type of the list is bool. It returns true if the field is existed otherwise returns false.


 public static bool ContainsField(List list, string fieldName)
        {
            try
            {
                var ctx = list.Context;
                var result = ctx.LoadQuery(list.Fields.Where(f => f.InternalName == fieldName));

                ctx.ExecuteQuery();

                return result.Any();
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }


Happy SharePointing.....................:)

Check if a SharePoint List is already created or not in a site collection in CSOM


The following methods determines whether list is already created or not in a site collection :



public static bool CheckIfListCreated(ClientContext context, string listName, ref string message)
        {

            try
            {
                ListCollection listCollection = context.Web.Lists;
             
                context.Load(listCollection, lists => lists.Include(list => list.Title).Where(list => list.Title == listName));
                context.ExecuteQuery();

                if (listCollection.Count > 0)
                {
                    message += listName + " " + string.Format("{0}", "Lists already exist.");
                    return true;

                }
                else
                {
                    message += string.Empty;
                    return false;
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }


Happy SharePointing..........................:)

Get all list items using CSOM in SharePoint 2013


There are several ways to get all the list items in CSOM. In the following method all the list items are retrieved using CSOM.


 private void GetAllListItems(ClientContext context, string listName)
        {
            try
            {

                Web web = context.Web;
                ListCollection lists = web.Lists;

                List selectedList = lists.GetByTitle(listName);

                context.Load<ListCollection>(lists);
                context.Load<List>(selectedList);

                context.ExecuteQuery();

                CamlQuery camlQuery = new CamlQuery();
                camlQuery.ViewXml = @"<View><Query></Query></View>";

                Microsoft.SharePoint.Client.ListItemCollection listItems = selectedList.GetItems(camlQuery);

                if (listItems.Count > 0)
                {
                    context.Load<Microsoft.SharePoint.Client.ListItemCollection>(listItems);
                    context.ExecuteQuery();
                }

            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

Happy SharePointing...................:)

Get Attachment URL of a SharePoint list item using CSOM


Suppose, you have a SharePoint list that stores images and its link  URL. The image may also be attached to the list item. In order to get the attachment url we can use the following method or you can modify it as your own purposes:




 public static List<string> GetAttachemntUrls(ClientContext context, Guid listId, int itemId)
        {
            List<string> urls = new List<string>();
            try
            {
                context.Load(context.Web, w => w.Lists);

                List list = context.Web.Lists.GetById(listId);
                context.Load(list, l => l.RootFolder);

                Folder rootFolder = list.RootFolder;
                context.Load(rootFolder, rf => rf.Folders);

                FolderCollection folders = rootFolder.Folders;
                context.Load(folders);

                context.ExecuteQuery();

                foreach (Folder folder in folders)
                {
                    if (folder.Name == "Attachments")
                    {
                        FolderCollection attachmentFolders = folder.Folders;
                        context.Load(attachmentFolders);
                        context.ExecuteQuery();

                        foreach (Folder itemFolder in attachmentFolders)
                        {
                            if (itemFolder.Name == itemId.ToString())
                            {
                                FileCollection files = itemFolder.Files;
                                context.Load(files);
                                context.ExecuteQuery();

                                foreach (File file in files)
                                {
                                    urls.Add(file.ServerRelativeUrl);
                                }
                                break;
                            }
                        }
                        break;
                    }
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
            return urls;
        }


Happy SharePointing.....................:)