Part I: Create New List item by Copy Existing List Item and then edit the newly created List Item


 

Often we came across this requirement to have a feature by which we can create a new item by copy existing list item to new item and then edit the newly created item.

We can approach this functionality in couple of ways, one by using SharePoint Designer and other by creating custom code in C# using Visual Studio.

Using SharePoint Designer and JQuery:

Steps:

1) Create a SharePoint Designer List WorkFlow to copy current item.

clip_image002

2) Add the following references in master page:

   1: <SharePoint:ScriptLink Language="javascript" Name="~SiteCollection/Style Library/jquery-1.4.4.min.js" runat="server"/>

   2: <SharePoint:ScriptLink Language="javascript" Name="~SiteCollection/Style Library/jquery-ui-1.8.min.js" runat="server"/>    

   3: //Add the reference of SPServices js file.    

   4: <SharePoint:ScriptLink Language="javascript" Name="~SiteCollection/Style Library/jquery.SPServices-0.7.2.min.js" runat="server"/>

   5: <SharePoint:ScriptLink Language="javascript" Name="~SiteCollection/Style Library /Project.js" runat="server"/>

3) Add the following JQuery code in .js file:

   1: var StoreListName;

   2: var StoreItemId;

   3: function CopyListItem(listName, itemID)

   4: {

   5:     StoreListName = listName;

   6:     currentItemId = itemID;

   7:     ExecuteOrDelayUntilScriptLoaded(ExecuteCopyListItem, "sp.js");    

   8: }

   9: //Execute Workflow - "Copy_Item WF" and then open the item in Edit Window.

  10: function ExecuteCopyListItem()

  11: {        

  12:     // we need to make sure that SP.ClientContext is loaded

  13:     if (SP.ClientContext == undefined) {

  14:         //setTimeout(function() { CopyListItem(listName, itemID) }, 100);

  15:         setTimeout(function() { ExecuteCopyListItem() }, 100);

  16:         return;

  17:     }    

  18:     var context = SP.ClientContext.get_current();

  19:     var lists =  context.get_web().get_lists();

  20:     var list = lists.getByTitle(StoreListName);

  21:     var item = list.getItemById(currentItemId);

  22:     var file = item.get_file(); 

  23:     context.load(list);

  24:     context.load(item);

  25:     var workflows = list.get_workflowAssociations();

  26:     context.load(workflows);    

  27:     context.executeQueryAsync(onQuerySucceeded, onQueryFailed);    

  28:     //If workflow is loaded successfully

  29:     function onQuerySucceeded() { 

  30:         var enumerator = workflows.getEnumerator();

  31:         while (enumerator.moveNext()) {

  32:               var workflow = enumerator.get_current();              

  33:               var workflowName;

  34:               if(StoreListName == " SomeCustomList")

  35:               {

  36:                   workflowName = "Copy_Item WF";

  37:               }    

  38:               if (workflow.get_name() == workflowName) {

  39:                 var url = 'http://' + window.location.hostname + item.get_item("FileRef"); 

  40:                 var templateId = '{' + workflow.get_id().toString() + '}'; 

  41:                 var workflowParameters = "<root />";                

  42:                 // trigger the workflow

  43:                 jQuery().SPServices({

  44:                   operation:"StartWorkflow",

  45:                   async:true,

  46:                   item:url,

  47:                   templateId:templateId,

  48:                   workflowParameters:workflowParameters,                  

  49:                  completefunc:function(xData, Status) { 

  50:                    var camlQuery = "<Query><Where>";                      

  51:                    camlQuery += "<Eq><FieldRef Name='Editor' /><Value Type='User'>" + userId + "</Value></Eq>";     camlQuery += "</Where><OrderBy><FieldRef Name='Modified' Ascending='FALSE'/></OrderBy></Query>";                  

  52:                   $().SPServices({

  53:                     operation: "GetListItems",

  54:                     async: false,

  55:                     listName: StoreListName,

  56:                     CAMLQuery: camlQuery,

  57:                     CAMLViewFields: "<ViewFields><FieldRef Name='ows_ID'/></ViewFields>",

  58:                     CAMLRowLimit: 1,

  59:                             completefunc: function(xData, Status) {

  60:                                 $(xData.responseXML).find("[nodeName='z:row']").each(function() {

  61:                                      lastId = $(this).attr("ows_ID"); 

  62:                                 });

  63:                            }

  64:                         });                           

  65:                     StoreItemId = lastId;             

  66:                             var modalWindowurl = "http://" + window.location.hostname + "/StateReporting2013/Lists/State%20Advocacy%20Wins/EditForm.aspx?ID=" + lastId;

  67:                             SP.UI.ModalDialog.showModalDialog({url:modalWindowurl, dialogReturnValueCallback: Function.createDelegate( null, DeleteCloseCallback)});

  68:                       }

  69:                 });

  70:                   break;

  71:               }

  72:         }

  73:         return true;

  74:       }

  75:       function onQueryFailed() { 

  76:           alert("Error with Start workflow");           

  77:       }

  78: }

  79: //Refresh the document library after the EditForm window is closed after successfully moving the document to the selected location 

  80: function DeleteCloseCallback(result, returnValue)

  81: { 

  82:     //if user clicks on save button

  83:     if(result==1)

  84:     {        

  85:         SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);            

  86:     }

  87:     //if user clicks on cancel button

  88:     else 

  89:     {        

  90:         DeleteItem();

  91:     }      

  92: }

  93: //Delete the newly created item if user clicks “X” button or “Cancel” button on modal window

  94: function DeleteItem()

  95: {        

  96:     // we need to make sure that SP.ClientContext is loaded

  97:     if (SP.ClientContext == undefined) {

  98:         setTimeout(function() { DeleteItem() }, 100);

  99:            return;

 100:     }        

 101:     if(window.frameElement)

 102:     {

 103:         window.frameElement.cancelPopUp();

 104:     }    

 105:     //delete the list item by using jQuery services.

 106:     jQuery().SPServices({

 107:         operation: "UpdateListItems",

 108:         async:true,

 109:         listName: StoreListName,

 110:         batchCmd: "Delete",

 111:         ID: NewItemId,

 112:         completefunc: function (xData, Status) {

 113:             SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);            

 114:         }

 115:     });

 116: }

4) Create “List Item Menu” from “Custom Action”

clip_image002[10]

Browse the list and see its working:

clip_image004

It executes the work flow and creates a new list item and open the newly created item in edit modal window.

clip_image006

Edit fields like: Title, Category, Keywords etc…and then hit save.

Wolla!!! New item is created and refreshes the list to show the newly created item.

clip_image007

Click here to see how to create custom code to achieve the same functionality.

 

Till then….. enjoy….

 

Cheers,

Abhijit Sil

Advertisements

13 Comments on “Part I: Create New List item by Copy Existing List Item and then edit the newly created List Item”

  1. maru February 18, 2014 at 12:00 am #

    Hi, I’m new to SharePoint. May I know where I can find master and .js file?
    Using SharePoint 2013

  2. Steve March 2, 2014 at 2:26 pm #

    This is awesome… Where can I create this .JS file

  3. Amit April 18, 2014 at 10:38 am #

    Hi,

    I tried to implement this.

    I downloaded jquery-2.0.2.min.js, jquery.SPServices-0.7.2.min.js and jquery-ui.min.js and add these file references on master page. My question from where I can find Project.js and sp.js file.

    Code which you mentioned in steps 3 where I need to put that code in sp.js or Project.js?

    Thanks,
    Amit Chhatbar

    • abhijitsil November 6, 2014 at 2:16 pm #

      Hi Amit,

      Project.js is the js file which i have created for this project.
      You can download the jquery.SPServices-0.7.2.min.js from http://spservices.codeplex.com/releases/view/81401 and upload it in Style Library of your site.

      Thanks,
      Abhijit

      • Amit May 21, 2015 at 7:13 am #

        Abhijit,

        I followed steps mentioned however when I click on Copy Item custom action it does not opening modal dialog. After I check and set “Navigate to URL” option value to “javascript:CopyListItem(“CopyFromExistingItem”,{ItemId});” and clicking OK, If I open it again it is showing me “Initiate workflow” radio button selected instead of “Navigate to URL”.

        Can you please suggest what could be the way to fix it. Why EditForm.aspx page does not opening modal dialog box? Thanks.

        Regards,
        Amit

  4. Subrahmanyam November 5, 2014 at 6:47 am #

    Hi Abhijit,

    I have gone trough all of your steps but for my office 365 site I can’t access the master pages unable to add the links provided in step 2. Is there any alternative to include these scriptlinks?
    while creating the new Item I need to change a column status to Draft is it possible?

    • abhijitsil November 6, 2014 at 2:09 pm #

      Hi Subrahmanyam,

      The alternatives are:

      • If you have access to the Page Layout of the List, you can add the script links in the page layout or
      • you can even add one content editor web part on top of you list and add the script links over there.

      Thanks,
      Abhijit

  5. haseeb January 21, 2015 at 3:42 pm #

    Will this work for SharePoint 2013?

    • abhijitsil January 21, 2015 at 3:51 pm #

      Yes, it should work in SharePoint 2013 also.

  6. veeru July 21, 2015 at 9:55 am #

    were do I get newly created Id or NewItemId . when edit dialogue is opened and modified the form and click on save it is modifying existing record.

    how to create new item when we modify existing item.

  7. Sharad P July 23, 2015 at 5:29 am #

    Hi Abhijit,

    I have tried your solution. I am getting a modal popup but instead of opening new item the existing item is opening. So the EditForm.aspx is saved the changes are saved in the existing item and a blank item is getting created in the list.

    Could you please help me on this.

    Best Regards,
    Sharad

  8. Michael December 14, 2015 at 11:30 am #

    I get the message during Debugging that userID is not defined (line 51). How can this be fixed?

  9. Govind Bhatu August 9, 2016 at 10:53 am #

    Hi Abhijit,

    I am getting below error when operation “StartWorkflow” executes.
    Please help me ASAP if possible.

    soap:Server
    Exception of type ‘Microsoft.SharePoint.SoapServer.SoapServerException’ was thrown.

    Value does not fall within the expected range.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: