0

I am working with a SharePoint hosted add on that has a JavaScript component that I would like to use to update some of the choice values for one of the Site Columns I created. Everything I see indicates I should have access to a spChoiceField.Choices.Add(value), or spChoiceField.AddChoice(value), or spChoiceField.set_choices(value) but none of these are valid for me.

I am working with code that looks like:

if (clientContext != undefined && clientContext != null) {

        var web = clientContext.get_web();
        fieldTitle = "TQM Requesting:";
        fieldChoice = clientContext.castTo(web.get_availableFields().getByTitle(fieldTitle), SP.FieldChoice);
        TQMtoAdd = TQMToInsert.value;
        clientContext.load(fieldChoice);

I expect fieldChoice to provide one of the add functions but it does not.

I checked the following articles: How to update Choice column in SharePoint Update multiple choice field in sharepoint using rest api Sharepoint choice field

Thank you, Duncan

Duncan
  • 21
  • 4

1 Answers1

0

Tested script in my local to update choice field of host web in SharePoint hosted add-in.

<%-- The following 4 lines are ASP.NET directives needed when using SharePoint components --%>

<%@ Page Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" MasterPageFile="~masterurl/default.master" Language="C#" %>

<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<%-- The markup and script in the following Content element will be placed in the <head> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
    <SharePoint:ScriptLink Name="sp.js" runat="server" OnDemand="true" LoadAfterUI="true" Localizable="false" />
    <meta name="WebPartPageExpansion" content="full" />

    <!-- Add your CSS styles to the following file -->
    <link rel="Stylesheet" type="text/css" href="../Content/App.css" />

    <!-- Add your JavaScript to the following file -->

    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script>

    <script type="text/javascript" src="../Scripts/App.js"></script>
    <script type="text/javascript">
        var appWebContext;
        var listResult;
        var hostweburl;

        $(document).ready(function () {
            UpdateChoice();
        });

        function UpdateChoice() {
            appWebContext = new SP.ClientContext.get_current();
            hostweburl = decodeURIComponent($.getUrlVar("SPHostUrl"));
            var hostwebContext = new SP.AppContextSite(appWebContext, hostweburl);
            var web = hostwebContext.get_web();
            var fieldTitle = "MyChoice";
            var fieldChoice = appWebContext.castTo(web.get_availableFields().getByTitle(fieldTitle), SP.FieldChoice);
            appWebContext.load(fieldChoice);
            appWebContext.executeQueryAsync(function () {
                var newValues = "NewOption";//strStatusValues.split(",");
                var currentChoices = fieldChoice.get_choices();
                //for (var i = 0; i < newValues.length; i++) {
                //    currentChoices.push(newValues[i]);
                //}
                currentChoices.push(newValues);
                fieldChoice.set_choices(currentChoices);
                fieldChoice.updateAndPushChanges();
                debugger;
                appWebContext.executeQueryAsync(function () {
                    console.log("Added new choice values to the column");
                }, function (sender, args) {
                    deferred.reject(args.get_message());
                });
            },
                function (sender, args) {
                    deferred.reject(args.get_message());
                });
        }


        // jQuery plugin for fetching querystring parameters  
        jQuery.extend({
            getUrlVars: function () {
                var vars = [], hash;
                var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
                for (var i = 0; i < hashes.length; i++) {
                    hash = hashes[i].split('=');
                    vars.push(hash[0]);
                    vars[hash[0]] = hash[1];
                }
                return vars;
            },
            getUrlVar: function (name) {
                return jQuery.getUrlVars()[name];
            }
        });
    </script>
</asp:Content>

<%-- The markup in the following Content element will be placed in the TitleArea of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
    Page Title
</asp:Content>

<%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">

    <div>
        <p id="message">
            <!-- The following content will be replaced with the user name when you run the app - see App.js -->
            initializing...
        </p>
    </div>

</asp:Content>
Lee
  • 5,305
  • 1
  • 6
  • 12
  • No Choices variable definition in my script, this is full code(App.js generated by project template, I changed nothing) – Lee Mar 11 '20 at 01:30
  • This is what I meant my original comment to say. I had to add var deferred = new $.Deferred(); to make this work. I would like to have the code in my Add-in.js. I added the above to the aspx file and then added the below to my add-in.js (all code above no space for it in a comment). var currentChoices = fieldChoice.get_choices(); and this fails with the property or field Choices has not been initialized. I tried adding var Choices just above but that didn't work. What am I missing? – Duncan Mar 11 '20 at 17:27
  • When I created a page, it did not include the code you show above. This is JavaScript for a C# project that is SharePoint hosted. – Duncan Mar 11 '20 at 17:34
  • It looks like I have to do something like var fieldChoice = new SP.FieldChoice();; After I do that later in the code I can call fieldChoice.set_choices(choiceId);. The problem is var fieldChoice = new SP.FieldChoice(); throws an exception at runtime: JavaScript runtime error: Sys.ArgumentNullException: Value cannot be null. Parameter name: context. Although I don't have it working yet, I am a lot closer. – Duncan Mar 12 '20 at 18:38
  • Here's what you do: -Write statements to lookup the field you want to modify -Let clientContext.executeQueryAsync execute -In the success function of clientContext.executeQueryAsync you will have the set_choice function. -The success function does the update then you make another call to clientContext.executeQueryAsync to update the field. – Duncan Mar 23 '20 at 18:59