2

I get this solution, but I have a need of turn some fields read-only but a function of verifying executes after all functions and do not work correctly, any idea about what I can do?

function isMember(groupName){

document.write("<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>"); 
$.ajax({
    url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups/getByName('"+groupName+"')/Users?$filter=Id eq " + _spPageContextInfo.userId,
    method: "GET",
headers: { "Accept": "application/json; odata=verbose"},
success: function (data) {
    alert('I am a member of the group' + groupName);
    return true;

},
error: function (data) {
    return false;

},
    asyn:false,
});

}

I try this code

function IsCurrentUserMemberOfGroup(){
    var grpName="myGroup";
    var userInGroup;
    var currentContext = new SP.ClientContext.get_current();
    var currentWeb = currentContext.get_web();

    var currentUser = currentContext.get_web().get_currentUser();
    currentContext.load(currentUser);

    var allGroups = currentWeb.get_siteGroups();
    currentContext.load(allGroups);

    var group = allGroups.getByName(grpName);
    currentContext.load(group);

    var groupUsers = group.get_users();
    currentContext.load(groupUsers);

    currentContext.executeQueryAsync(OnSuccess, OnFailure);

    function OnSuccess(sender, args)
     {

        var groupUserEnumerator = groupUsers.getEnumerator();
        while (groupUserEnumerator.moveNext())
        {
            var groupUser = groupUserEnumerator.get_current();
            if (groupUser.get_id() == currentUser.get_id())
            {
                userInGroup = true;
                break;
            }
        }
        if (userInGroup)
        {
            console.log("user exists in the group");

            (function () { 

                //script to make your fields read only goes here
                var readonlyFiledContext = {}; 
                readonlyFiledContext.Templates = {}; 
                readonlyFiledContext.Templates.Fields = { 
                    // Apply the new rendering for Age field on Edit forms 
                    "Descricao": { 
                        "EditForm": readonlyFieldTemplate 
                    }, 
                    "Codigo": { 
                        "EditForm": readonlyFieldTemplate 
                    }, 
                    "Lote": { 
                        "EditForm": readonlyFieldTemplate 
                    } 
                }; 



                SPClientTemplates.TemplateManager.RegisterTemplateOverrides(readonlyFiledContext); 
                console.log("fim do read only");
            })();


        }

        else
        {
            console.log("user doestn't exist in the group");


        }

    }

    function OnFailure(sender, args)
    {

    }

}

bof codes works and this code is my function to make the fields read-only

(function () { 

//isMember("Microbiologia"); console.log('entrou no ready only');

console.log(teste); // Create object that have the context information about the field that we want to change it's output render
var readonlyFiledContext = {}; readonlyFiledContext.Templates = {}; readonlyFiledContext.Templates.Fields = { // Apply the new rendering for Age field on Edit forms "Descricao": { "EditForm": readonlyFieldTemplate }, "Codigo": { "EditForm": readonlyFieldTemplate }, "Lote": { "EditForm": readonlyFieldTemplate } }; SPClientTemplates.TemplateManager.RegisterTemplateOverrides(readonlyFiledContext); console.log('fim do ready only');

})();

// This function provides the rendering logic function readonlyFieldTemplate(ctx) {

//Reuse ready sharepoint javascript libraries 
switch (ctx.CurrentFieldSchema.FieldType) { 
    case "Text": 
    case "Number": 
    case "Integer": 
    case "Currency": 
    case "Choice": 
    case "Computed": 
        return SPField_FormDisplay_Default(ctx); 

    case "MultiChoice": 
        prepareMultiChoiceFieldValue(ctx); 
        return SPField_FormDisplay_Default(ctx); 

    case "Boolean": 
        return SPField_FormDisplay_DefaultNoEncode(ctx); 

    case "Note": 
        prepareNoteFieldValue(ctx); 
        return SPFieldNote_Display(ctx); 

    case "File": 
        return SPFieldFile_Display(ctx); 

    case "Lookup": 
    case "LookupMulti": 
            return SPFieldLookup_Display(ctx);            

    case "URL": 
        return RenderFieldValueDefault(ctx); 

    case "User": 
        prepareUserFieldValue(ctx); 
        return SPFieldUser_Display(ctx); 

    case "UserMulti": 
        prepareUserFieldValue(ctx); 
        return SPFieldUserMulti_Display(ctx); 

    case "DateTime": 
        return SPFieldDateTime_Display(ctx); 

    case "Attachments": 
        return SPFieldAttachments_Default(ctx); 

    case "TaxonomyFieldType": 
        //Re-use ready sharepoint inside sp.ui.taxonomy.js javascript libraries 
        return SP.UI.Taxonomy.TaxonomyFieldTemplate.renderDisplayControl(ctx); 
} 

}

//User control need specific formatted value to render content correctly function prepareUserFieldValue(ctx) { console.log('prepareUserFieldValue');

var item = ctx["CurrentFieldValue"]; 
var userField = item[ctx.CurrentFieldSchema.Name]; 
var fieldValue = ""; 

for (var i = 0; i < userField.length; i++) { 
    fieldValue += userField[i].EntityData.SPUserID + SPClientTemplates.Utility.UserLookupDelimitString + userField[i].DisplayText; 

    if ((i + 1) != userField.length) { 
        fieldValue += SPClientTemplates.Utility.UserLookupDelimitString 
    } 
} 

ctx["CurrentFieldValue"] = fieldValue; 

}

//Choice control need specific formatted value to render content correctly function prepareMultiChoiceFieldValue(ctx) {

if (ctx["CurrentFieldValue"]) { 
    var fieldValue = ctx["CurrentFieldValue"]; 

    var find = ';#'; 
    var regExpObj = new RegExp(find, 'g'); 

    fieldValue = fieldValue.replace(regExpObj, '; '); 
    fieldValue = fieldValue.replace(/^; /g, ''); 
    fieldValue = fieldValue.replace(/; $/g, ''); 

    ctx["CurrentFieldValue"] = fieldValue; 
} 

}

//Note control need specific formatted value to render content correctly function prepareNoteFieldValue(ctx) {

if (ctx["CurrentFieldValue"]) { 
    var fieldValue = ctx["CurrentFieldValue"]; 
    fieldValue = "<div>" + fieldValue.replace(/\n/g, '<br />'); + "</div>"; 

    ctx["CurrentFieldValue"] = fieldValue; 
} 

}

1

If you rely on CSR or _spPageContextInfo, you are always late.

Because those need a shitload of SP JavaScript libraries to be loaded.

Best way is to add a UserCustomAction Scriptlink, and call http://mysharepointsite/_api/SP.UserProfiles.PeopleManager/GetMyProperties

remember.. you need to call /contextinfo first to get a valid request-digest

That does not require any SP s* loaded

And ofcourse ditch jQuery.. you don't need to load a 90KB library to execute an XHR call.. learn proper JavaScript.. since IE9 there are no issues with browsers anymore.. and no need for jQuery at all.

You will still run into trouble occasionaly if you depend on the info, because SharePoint APIs are dead slow...

Just call the end-point a random number times to test..
I have worst cases where the response takes over a second

So its best to store the response in LocalStorage, work what that, and then async verify the user data with an API call

  • Worst cases can take over 90 seconds – Alexey Krasheninnikov May 20 '17 at 7:00
  • oops, I don't understand why we rebel against SharePoint then. Worst case I got was over 5 seconds, but I did not dare to post that in fear of getting flack from SP lovers – Danny '365CSI' Engelman May 20 '17 at 8:55
1

Consider using webparts targeted to groups (Edit web part properties, advanced, target audience), it might help

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.