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


 

Hope you have liked my previous blog (Part I) about creating a copy of existing list item and then open the newly created item in edit window. We have seen how to perform the task using SharePoint Designer and JQuery.

You might be wondering, why we need to have custom code to do the same task which we can do easily by using SharePoint designer.

The answer is, the previous solution using SharePoint designer have few cons:

i. We have to create individual copy item work-flow for each list.

ii. After completing the copy item, Work-Flow status column will be added automatically in the list.

iii. We have to create custom action in each list.

To overcome these cons, we can create a custom solution, and deploy to the site as a feature, thus when the feature is activated, it will create custom action to every list in the site and enable the copy item functionality.

Steps:

1) Create an empty element:

   1: <?xml version="1.0" encoding="utf-8"?>

   2: <Elements xmlns="http://schemas.microsoft.com/sharepoint/">

   3:   <CustomAction

   4:      Description="Copy current item"

   5:      Title="Copy Item"

   6:      Id="{4EC6120C-799A-458C-AD6E-16CD72414A73}"

   7:      RegistrationType="List"

   8:      RegistrationId="100"

   9:      Rights="AddListItems"

  10:      Sequence="0"

  11:      ShowInLists="True"

  12:      Location="EditControlBlock">       

  13:     <UrlAction Url="javascript:SP.UI.ModalDialog.showModalDialog({url:'{SiteUrl}/_layouts/StateReportCopyItem/CustomEdit.aspx?ID={ItemId}&amp;List={ListId}',dialogReturnValueCallback: Function.createDelegate( null, ApplicationPageCloseCallback)})" ></UrlAction>

  14:   </CustomAction>

  15:   <CustomAction

  16:      Description="Copy current item"

  17:      Title="Copy Item"

  18:      Id="{C0011AC0-8B9C-4E4F-B30A-5FE6AAB36F16}"

  19:      RegistrationType="List"

  20:      RegistrationId="100"  

  21:      Rights="AddListItems"

  22:      Location="CommandUI.Ribbon">

  23:     <CommandUIExtension>

  24:       <CommandUIDefinitions>

  25:         <CommandUIDefinition Location="Ribbon.ListItem.Actions.Controls._children">

  26:           <Button

  27:               Id="Ribbon.ListItem.Actions.CopyItemRibbonCutomActionButton"

  28:               Alt="Copy Item"

  29:               Command="Invoke_CopyItemRibbonCutomActionButton"

  30:               Image32by32="{SiteUrl}/PublishingImages/Copy-Image.PNG"

  31:               Image16by16="{SiteUrl}/PublishingImages/Copy-Image.PNG"

  32:               LabelText="Copy Item"

  33:               TemplateAlias="o1" />

  34:         </CommandUIDefinition>                

  35:       </CommandUIDefinitions>

  36:       <CommandUIHandlers>

  37:         <CommandUIHandler

  38:           Command="Invoke_CopyItemRibbonCutomActionButton"

  39:           CommandAction="javascript:SP.UI.ModalDialog.showModalDialog({url:'{SiteUrl}/_layouts/StateReportCopyItem/CustomEdit.aspx?ID={SelectedItemId}&amp;List={ListId}',dialogReturnValueCallback: Function.createDelegate(null, ApplicationPageCloseCallback)});"          

  40:           EnabledScript="javascript:function singleEnable() 

  41:                         { 

  42:                           var items = SP.ListOperation.Selection.getSelectedItems(); 

  43:                           var ci = CountDictionary(items); 

  44:                           return (ci == 1); 

  45:                         } 

  46:                         singleEnable();" />

  47:       </CommandUIHandlers>

  48:     </CommandUIExtension>    

  49:   </CustomAction>

  50: </Elements>

2) Create an Application Page, say EditNewItem.aspx and write the following code in EditNewItem.aspx.cs:

   1: public partial class EditNewItem : LayoutsPageBase

   2:     {

   3:         private string baseURL = SPContext.Current.Site.Url;

   4:         private Guid ListId = Guid.Empty;

   5:         private int ListItemId;

   6:  

   7:         protected void Page_Load(object sender, EventArgs e)

   8:         {

   9:             if (!Page.IsPostBack)

  10:             {   

  11:                 ListItemId = Convert.ToInt32(Request.QueryString.GetValues("ID")[0]);

  12:                 ListId = new Guid(Request.QueryString.GetValues("List")[0].ToString());

  13:  

  14:                 CopyCurrentItem();

  15:             }

  16:         }

  17:  

  18:         private void CopyCurrentItem()

  19:         {

  20:             try

  21:             {

  22:                 SPSecurity.RunWithElevatedPrivileges(delegate()

  23:                 {

  24:                     using (SPSite site = new SPSite(baseURL))

  25:                     {

  26:                         using (SPWeb web = site.OpenWeb("/"))

  27:                         {

  28:                             SPList currentList = web.Lists.GetList(ListId, true);

  29:                             SPListItem sourceItem = currentList.GetItemById(ListItemId);

  30:  

  31:                             web.AllowUnsafeUpdates = true;

  32:  

  33:                             SPListItem targetItem = currentList.Items.Add();

  34:                             foreach (SPField f in sourceItem.Fields)

  35:                             {

  36:                                 //Copy all except attachments.

  37:                                 if (!f.ReadOnlyField && f.InternalName != "Attachments"

  38:                                     && null != sourceItem[f.InternalName])

  39:                                 {

  40:                                     targetItem[f.InternalName] = sourceItem[f.InternalName];

  41:                                 }

  42:                             }

  43:                             //Copy attachments

  44:                             foreach (string fileName in sourceItem.Attachments)

  45:                             {

  46:                                 SPFile file = sourceItem.ParentList.ParentWeb.GetFile(sourceItem.Attachments.UrlPrefix + fileName);

  47:                                 byte[] imageData = file.OpenBinary();

  48:                                 targetItem.Attachments.Add(fileName, imageData);

  49:                             }

  50:  

  51:                             targetItem.Update();

  52:  

  53:                 //Create url for editing the newly created item

  54:                             Uri newItemUrl = new Uri(baseURL + currentList.DefaultEditFormUrl + "?ID=" + targetItem.ID);

  55:                             

  56:                 //Close the current modal window and open the newly created item in edit form in modal window.

  57:                             Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup('" + newItemUrl.AbsoluteUri + ";" + targetItem.ID + ";" + currentList.Title + "');</script>");                            

  58:                         }

  59:                     }

  60:                 });

  61:             }

  62:             catch

  63:             {

  64:                 throw;

  65:             }

  66:         }

  67:     }

3) In .js file add the following JQuery code:

   1: //Closeback event called while closing the application pagefunction ApplicationPageCloseCallback(result, returnValue)

   2: {

   3:     //Store the List Name and newly created item id

   4:     var inputData = returnValue.split(';');

   5:     NewItemId = inputData[1];

   6:     StoreListName = inputData[2];

   7:     //Open EditForm.aspx for editing the newly created item.

   8:     SP.UI.ModalDialog.showModalDialog({url:inputData[0], dialogReturnValueCallback: Function.createDelegate( null, DeleteCloseCallback)});

   9: }

  10:  

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

  12: function DeleteCloseCallback(result, returnValue)

  13: { 

  14:     //if user clicks on save button

  15:     if(result==1)

  16:     {    

  17:         //save the changes, close the modal window and refresh the list.    

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

  19:     }

  20:     //if user clicks on cancel button

  21:     else 

  22:     {

  23:         //delete the newly created item        

  24:         DeleteItem();

  25:     }      

  26: }

  27:  

  28: function DeleteItem()

  29: {        

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

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

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

  33:            return

  34:     }

  35:         

  36:     if(window.frameElement)

  37:     {

  38:         //close the modal window

  39:         window.frameElement.cancelPopUp();

  40:     }

  41:     

  42:     jQuery().SPServices({

  43:         operation: "UpdateListItems",

  44:         async:true,

  45:         listName: StoreListName,

  46:         batchCmd: "Delete",

  47:         ID: NewItemId,

  48:         completefunc: function (xData, Status) {

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

  50:         }

  51:     });

  52: }

 

Deploy the feature and see its working like a charm….

 

Cheers,

Abhijit Sil

Advertisements

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

  1. Anthony January 16, 2014 at 10:02 pm #

    Hi Abhijit
    This is exactly what I need. Unfortunately I’m new to SharePoint though. Should I use SharePoint Designer 2013 or Visual Studio to create the Empty Element etc? I am working on an existing SharePoint site – not a VS project. I can open it in Designer, but it is not apparent to me how to process with your instructions.
    Thank you
    Anthony

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: