Archive | Custom Ribbon Actions RSS for this section

Sharepoint 2013 App Custom Action

This post is about how to create a Custom Action using a SharePoint 2013 app project.

In this sample I’ll use a Menu action, that will be available to list items in Page Library based lists.

This menu action will update a field in the target list item.

Start creating a SharePoint 2013 app Visual Studio 2013 project, SharePoint Hosted.

Then add a new item of type “Menu Item Custom Action”:

AppRA1

Select “List Template” and “Page Library”:

AppRA2

Select your action name and target page:

AppRA3

Your Menu Action elements.xml file should be like:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction Id="56b2571e-1ae7-48e8-be14-2652fc86bc79.Action1"
                RegistrationType="List"
                RegistrationId="850"
                Location="EditControlBlock"
                Sequence="10001"
                Title="Action1">
    <!--
    Update the Url below to the page you want the custom action to use.
    Start the URL with the token ~remoteAppUrl if the page is in the
    associated web project, use ~appWebUrl if page is in the app project.
    -->
    <UrlAction Url="~appWebUrl/Pages/Default.aspx?{StandardTokens}&amp;SPListItemId={ItemId}&amp;SPListId={ListId}" />
  </CustomAction>
</Elements>

In app Menu Action or Ribbon Action you can’t add javascript code to your Command Action (like in this post), so you need to define the  behaviour of your action in the navigation page.
My Default.aspx file includes the App.js file, I edited this file and add the following code:

 'use strict';

var list;
 var parentWeb;
 var currentItem;

$(document).ready(function () {

var hostweburl = GetSiteUrl();

var clientContext = new SP.ClientContext.get_current();
 var parentCtx = new SP.AppContextSite(clientContext, hostweburl)
 var parentWeb = parentCtx.get_web();
 clientContext.load(parentWeb);
 list = parentWeb.get_lists().getById(GetListId());
 clientContext.load(list);
 currentItem = list.getItemById(GetItemId());
 clientContext.load(currentItem);
 if (currentItem != null) {
 currentItem.set_item('Category', 'Cat1');
 currentItem.update();
 }
 clientContext.executeQueryAsync(onListLoadSucceeded,
 onRequestFailed);
 });

function onListLoadSucceeded() {
 $('#message').text('Done');
 }

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

function getParameterByName(name) {
 var name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
 var regexS = "[\\?&]" + name + "=([^&#]*)";
 var regex = new RegExp(regexS);
 var results = regex.exec(window.location.href);
 if (results == null)
 {
 return "";
 }
 else
 {
 return decodeURIComponent(results[1].replace(/\ /g, " "));
 }
 }

function GetListId() {
 return getParameterByName("SPListId");
 }

function GetSiteUrl() {
 return getParameterByName("SPHostUrl");
 }

function GetItemId() {
 return getParameterByName("SPListItemId");
 }
 

After deployed my solution, I can see and execute my Custom Action:

AppRA4

Advertisements

Sharepoint 2013 Open a Modal Dialog from a Custom Ribbon Action

This post is a sequence from this one (https://raquelalineblog.wordpress.com/2013/05/28/sharepoint-2013-custom-ribbon-action-to-update-a-list-item-field/).

In this post I’ll show how to call a modal dialog and get a value from that to update a list item field value.

The first thing was to create a mapped folder in my SharePoint 2013 project, to Layouts folder.

Then I add a new application page, where I have a text area to get data from user, an Ok button and a Cancel button.
My application page is this:

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GetCategory.aspx.cs" Inherits="SharePointCustomMenuAction.Layouts.SharePointCustomMenuAction.MoveDocs" DynamicMasterPageFile="~masterurl/default.master" %>

<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">

</asp:Content>

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">

     <Sharepoint:ScriptLink ID="ScriptLink1" Name="sp.ui.dialog.js" LoadAfterUI="true" Localizable="false" runat="server"></Sharepoint:ScriptLink>
     <script type="text/javascript" language="javascript">

            function onCancel(sender, args) {
                SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, '');
            }

            function onOk(sender, args) {
                SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, document.getElementById('txtCategory').value);
            }
    </script>
    <form id="aspnetForm" action="">

        <p>
            <label id="label1">Enter Category Value</label>
        </p>
        <p>
            <textarea id="txtCategory" rows="1" cols="10"></textarea>

        </p>
        <p>
            <button  id="Ok" value="Ok" onclick="onOk();">Ok</button>&nbsp;&nbsp;<button id="Cancel" value="Cancel" onclick="onCancel();">Cancel</button>
        </p>
    </form>
</asp:Content>

<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
Get Category
</asp:Content>

<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
Get Category
</asp:Content>

I changed my Custom Action’s elements.xml file to call the modal dialog and get the result and value.

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/"> 
    <CustomAction
    Id="Ribbon.Library.Actions.AddAButton"
    Location="CommandUI.Ribbon"
    RegistrationId="101"
    RegistrationType="List"
    Title="MoveDocs Ribbon Button">
    <CommandUIExtension>
      <CommandUIDefinitions>
        <CommandUIDefinition
          Location="Ribbon.Library.Share.Controls._children">
          <Button Id="Ribbon.Library.Share.NewRibbonButton"
            Command="MoveDocsButtonCommand"
            LabelText="UpdateCategory"
            TemplateAlias="o2" />
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <CommandUIHandler
          Command="MoveDocsButtonCommand"
          CommandAction="javascript:
            var context;
            var notifyId;
            var currentItem;
        
          function onQuerySucceededUpdate (sender, args) {
              alert('item updated');
          }    

          function onQueryFailedUpdate(sender, args) {
            alert('Error occured' + args.get_message());
          }  
          
          function UpdateCategory(val)
          {
             context = SP.ClientContext.get_current();
             var web = context.get_web();
             context.load(web, 'Title');  
             var currentlibid = SP.ListOperation.Selection.getSelectedList();
             var currentLib = web.get_lists().getById(currentlibid);
             var selectedItems = SP.ListOperation.Selection.getSelectedItems(context);
             for(var i in selectedItems)
              {
                currentItem = currentLib.getItemById(selectedItems[i].id);
                context.load(currentItem);
                if(currentItem != null) {
                  currentItem.set_item('Category', val);
                  currentItem.update();
                }
                context.executeQueryAsync(Function.createDelegate(this, onQuerySucceededUpdate), Function.createDelegate(this, onQueryFailedUpdate));
              }//End for
          }//End UpdateCategory


          var dlg=SP.UI.ModalDialog.showModalDialog({url: '{SiteUrl}/_Layouts/SharePointCustomMenuAction/GetCategory.aspx', dialogReturnValueCallback:function(res, val) {       
                if(res=='1')
                  {
                    UpdateCategory(val);
                  }
                else
                {
                  alert('Operação Cancelada');
                }
               }
              });
          
          
           
"/>
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>
  
  <Module Name="CustomAction">
  </Module>
</Elements>

Sharepoint 2013 Custom Ribbon Action To Update a List Item Field

In this post I’ll show how to develop a Custom Ribbon Action, that iterates through selected document library (with a custom column named Category) items and updates  a field value (category).

I want to do another post to  get the value from a modal dialog, but for now, the updated value will be hard coded.

I started creating a SharePoint 2013 empty project in Visual Studio 2012 (selected the deployment as a farm solution, but could also be sandbox).

Add a new module to my project called “CustomAction”, and add the following code, to elements.xml file:

 

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/"> 
    <CustomAction
    Id="Ribbon.Library.Actions.AddAButton"
    Location="CommandUI.Ribbon"
    RegistrationId="101"
    RegistrationType="List"
    Title="MoveDocs Ribbon Button">
    <CommandUIExtension>
      <CommandUIDefinitions>
        <CommandUIDefinition
          Location="Ribbon.Library.Share.Controls._children">
          <Button Id="Ribbon.Library.Share.NewRibbonButton"
            Command="MoveDocsButtonCommand"
            LabelText="UpdateCategory"
            TemplateAlias="o2" />
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <CommandUIHandler
          Command="MoveDocsButtonCommand"
          CommandAction="javascript:
            var context;
            var currentItem ;
          
        
          function onQuerySucceededUpdate (sender, args) {
              alert('item updated');
          }    

          function onQueryFailedUpdate(sender, args) {
            alert('Error occured' + args.get_message());
          }  
          
          function UpdateCategory(val)
          {
            context = SP.ClientContext.get_current();
            var web = context.get_web();
             context.load(web);
             var currentlibid = SP.ListOperation.Selection.getSelectedList();
             var currentLib = web.get_lists().getById(currentlibid);
             var selectedItems = SP.ListOperation.Selection.getSelectedItems(context);
             for(var i in selectedItems)
              {
                currentItem = currentLib.getItemById(selectedItems[i].id);
                context.load(currentItem);
                if(currentItem != null) {
                  currentItem.set_item('Category', val);
                  currentItem.update();
                }
                context.executeQueryAsync(Function.createDelegate(this, onQuerySucceededUpdate), Function.createDelegate(this, onQueryFailedUpdate));
              }// End for
          
          }//End UpdateCategory

          
          UpdateCategory('Cat1');
           
"/>
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>
  
  <Module Name="CustomAction">
  </Module>
</Elements>