0

I currently have a JavaScript that calculates the current activity of a radioisotope; however, it only displays the value (it does not actually set the field equal to the value). How can I go about actually setting the value?

Picture of list showing the value.

enter image description here

Picture via F12, showing the value is empty.

enter image description here

My JavaScript code (implemented via JS Link).

function one(){

var statusFieldCtx = {};
statusFieldCtx.Templates = {};
statusFieldCtx.Templates.Fields = {
    "biui": {"View": StatusFieldViewTemplate}
};

SPClientTemplates.TemplateManager.RegisterTemplateOverrides(statusFieldCtx);

    function StatusFieldViewTemplate(ctx) {

    var T = {};
    var EQ = {};
    var Isotope   = ctx.CurrentItem["Title"];
    var CalibDate = ctx.CurrentItem["nj0z"];
    var CalibAct  = ctx.CurrentItem["j3yb"];
    var CurrAct   = ctx.CurrentItem["biui"];
    var LeakTest  = ctx.CurrentItem["bzwi"];

    switch (Isotope) {

        case "C-14":
            T = 5700;
            EQ = 10.0;
            break;

        case "Cs-137":
            T = 30.08;
            EQ = 0.01;
            break;

    }

    statusValue = CalibAct * Math.exp(  Math.LN2*((1+new Date(CalibDate).getTime() - new Date().getTime()))/(1000*3600*24*365.25*T)  )

    if (statusValue < EQ) {

                return "<div style='background-color:green;color:white'>" + statusValue.toFixed(5) + "</div>";

    }

    else {

        return "<div style='background-color:white;color:black'>" + statusValue.toFixed(5) + "</div>";

    }

    }
};
  • 1
    You mean you want to write that value back to the list item? – Dylan Cristy Nov 21 '19 at 21:02
  • Yes. I can currently get it to display the correct value via the current JavaScript (Current Activity = "biui"), but when I go to view the item details, it shows no value (empty). – Shinobii Nov 21 '19 at 21:10
1

The code example you provided is an example of a Client Side Rendering override, so it makes sense that no data is being sent back to the server - CSR overrides only affect what is rendered on the client side (i.e. what is displayed in the browser).

In order to write back to the list from Javascript running in the browser, you will have to use the SharePoint REST API. There are various ways you can make REST calls from Javascript, an easy way is to use jQuery ajax(), so I'll show an example of that, but there are other libraries you can use.

You'll need to know a few things first though:

  • The internal name of the field you want to update (which you know: "biui")
  • The value you want to write (which you know from your caluclation)
  • The name of the list (easy to get)
  • The ID of the list item you want to update (easy to get from inside your override function)
  • The list item entity type name. This is a bit trickier to get. You can get it by making a REST call to yoursite/_api/web/lists/getbytitle('Your List Name') and finding the ListItemEntityTypeFullName property on the list object that gets returned to you, or you can guess at it because it follows a pattern: SP.Data.YourListNameListItem. So if your list is called "Isotope Activity", you would use SP.Data.Isotope_x0020_ActivityListItem. (Keep in mind that if you have the word "List" as part of the list name, then there's going to be a double "List" in the entity name: "Isotope Activity List" becomes SP.Data.Isotope_x0020_Activity_x0020_ListListItem.) (Oh yeah, btw, spaces are encoded as _x0020_.)

So here's what you would do: figure out how to load jQuery so you can use it. [Hint: you can load more than one script file in JSLink by separating the paths to the files with a pipe (|) delimiter. They load in order so jQuery will have to come before your script.]

Then, inside your "StatusFieldViewTemplate" function, maybe somewhere near the end, you would call another function to update the list item, and pass it the status value you want to save and the ID of the list item you want to update, so maybe something like

updateStatusValue(statusValue.toFixed(5), ctx.CurentItem["ID"])

Then, outside your "one" main function, define the update function:

function updateStatusValue(statusValue, itemID) {
    // build your little data package that has the data to update.
    // this is where you need the entity type name.
    var spListItem = {
        "__metadata": {
            "type": "SP.Data.YourListNameListItem"
        },
        "biui": statusValue
    };

    // build the url you are going to post to.
    // this is where you need the item ID.  you can also take
    // advantage of a built in helper object provided by sharepoint
    var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Your List Name')/items(" + itemID + ")";

    // make the REST call
    $.ajax({
        url: url,
        method: "POST",
        data: JSON.stringify(spListItem),
        headers: {
            "X-RequestDigest": $("#__REQUESTDIGEST").val(), // this gets a security token from the sharepoint page
            "accept": "application/json;odata=verbose",
            "content-type": "application/json;odata=verbose",
            "IF-MATCH": "*",
            "X-HTTP-Method": "MERGE" // this tells it to update an existing item
        }
    }).done(function (data) {
        // you can log the response to the console to see what it looks like
        console.log(data);
        // but we don't really care too much.  if we made it into this function
        // then we can assume the update succeeded
        alert("yay!");
    }).fail(function (error) {
        console.log(error);
        alert("uh-oh, update failed");
    });
}

There's tons of other resources out there about how to use the REST API, just google "sharepoint rest api".

|improve this answer|||||
  • This makes sense, I figured it had to do with the client side rendering (I am still quite new to this programming). I will give this a shot today / early tomorrow! Thanks for the detailed response, I will let you know how it goes. – Shinobii Nov 21 '19 at 22:35
  • I am running into an issue with the $ sign. I get ReferenceError: $ is not defined, which stems from the $.ajax portion of code. – Shinobii Nov 25 '19 at 18:42
  • Do I need to load a jQuery library or something? Sorry again if this is trivial to you! Sorry, you CLEARLY stated I have to load jQuery! I will do that. Sorry, read over that part initially. – Shinobii Nov 25 '19 at 18:56
  • Quick update. I got jQuery running. Now I am just trying to get the var url correct. I keep getting 404 Not Found. I'll keep playing around and see what happens. – Shinobii Nov 25 '19 at 20:36
  • 1
    @Shinobii excellent! Glad you got it to work, and were able to learn. Sorry I wasn't checking in regularly to see you had left some other comments. – Dylan Cristy Nov 25 '19 at 21:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.