Modify HitCounter script to Add to Favourites button

Home Forums Requests Modify HitCounter script to Add to Favourites button

Viewing 6 reply threads
  • Author
    Posts
    • #21664
      Brett
      Participant

        Hi Alexander,
        I’m trying to use your HitCounterforSharePoint solution as a Add to Favorites button for SP2013.
        This is for a document library, while viewing the displayform.aspx of the document, a person can click the Star image to add to their favorites rather than give it a star rating. Only 1x star is shown.
        The HitCounter list is their Favorites list, showing the Documents they Bookmarked.
        2x requests if you have time to assist please:
        1: I’ve got everything working except the part to unfavorite the document.
        Are you able to provide the extra javascript to remove the star rating from the HitCounter list?

        2: Also, can this solution be used in a calculated column in a list view?
        I did read in the comments that it captures the URL, so not sure if that will work or how much revamp would be needed to make it work?

        I understand SP2013 has built in Rating column feature but I believe there isn’t a list to then view all your favorites, which your solution does.

        Any help with this would be great.
        Thank you.

      • #21706
        Alexander Bautz
        Keymaster

          Hi,
          You cannot use a calculated column in list view because the support for using HTML calculated columns (by specifying the output as number) no longer works (in O365 at least). Also, the list item is identified by the URL and you don’t have access to this in a calculated column.

          I don’t think the hit counter solution is a good start and think you should make it a bit simpler. I have written this little example to show a button in DispForm or EditForm.

          1: Add a list with DisplayName “Favorites” in your site. Only the Title field is used so you don’t have to add any new fields to this list.

          2: Add a HTML section to one of your tabs with this snippet:

          <div id="favBtnPlaceholder"></div>

          3: Add this to your Custom JS:

          function getIsFavorite(){
              var currDocRes, favRes, b = [];
              currDocRes = spjs.utility.getItemByID({"listName":_spPageContextInfo.pageListId,"id":spjs.dffs.data.thisItemID,"viewFields":["ID","EncodedAbsUrl"]});
              if(currDocRes !== null){
                  favRes = spjs.utility.queryItems({"listName":"Favorites","query":"<Where><And><Eq><FieldRef Name='Author' LookupId='TRUE' /><Value Type='User'>"+_spPageContextInfo.userId+"</Value></Eq><Eq><FieldRef Name='Title' /><Value Type='Text'>"+currDocRes.EncodedAbsUrl+"</Value></Eq></And></Where>", "viewFields":["ID"]});
                  if(favRes.count === 0){
                      b.push("<input type='button' style='background-color:green;color:white;;' value='Add to favorites' onclick='toggleDocFav(false,\""+currDocRes.EncodedAbsUrl+"\")'>");
                  }else{
                      b.push("<input type='button' style='background-color:yellow;' value='Remove from favorites' onclick='toggleDocFav(\""+favRes.items[0].ID+"\",\""+currDocRes.EncodedAbsUrl+"\")'>");
                  }
              }
              jQuery("#favBtnPlaceholder").html(b.join(""));
          }
          // Call function on load:
          getIsFavorite();
          
          function toggleDocFav(id,url){
              var res;
              if(!id){
                  // add to fav
                  res = spjs.utility.addItem({"listName":"Favorites","data":{"Title":url}});
                  if(res.success){
                      alert("Successfully added as favorite");
                      getIsFavorite();
                  }
              }else{
                  res = spjs.utility.deleteItem({"listName":"Favorites","id":id});
                  if(res.success){
                      alert("Successfully removed from favorite");
                      getIsFavorite();
                  }
              }
          }

          I hope this gets you in the right direction.

          Best regards,
          Alexander

        • #21809
          Brett
          Participant

            HI Alexander,
            Your script works perfectly.
            Many thanks for your time and effort.

          • #21816
            Alexander Bautz
            Keymaster

              Thanks for the feedback – I’m glad it worked.

              Alexander

              • #34413
                Brett
                Participant

                  Hi Alexander,

                  I’m looking at using this Add to Favorite/Bookmark solution to be used in a list.
                  Right now it’s set for a document library, so the value in the Title column shows as: https://sharepointserver.com.au/sites/training/Lists/Courses/71_.000 (71 is the ID)

                  The scenario is a list of training courses, which an employee can choose to add them to their My Learning list.
                  They can either click a button on the Course Display Form or a click a button next to each item in the List View.

                  1: Are you able to modify the code above to push the Course fields (ID, Title, Description, Category, link to course) to the My Learning list?

                  2: If it can’t be done from a list view, I’ll try to wire up a vLookup using the Parent ID and Author as a search query.

                  I looked at your Workflow button but I’m using SP2016 with Nintex workflows, so it’s very different.

                  Thanks for your time,

                  Brett

                • #34430
                  Alexander Bautz
                  Keymaster

                    Writing more values to the list is just a matter of changing the “data” part like this:

                     res = spjs.utility.addItem({"listName":"Favorites","data":{"Title":url, "another_field": "another_value"}});

                    You can use getFieldValue(“another_field”) instead of “another_value” in the snippet above to get the value from a field in the current item.

                    Please note that the format is different for different field types. If you can tell me which type the fields are in the “My learning list” I can give you and example of how you can write the data object.

                    Alexander

                • #34435
                  Brett
                  Participant

                    Hi Alexander,
                    So with ID, and Title:
                    The other field types would be Description = multi-line text column(HTML) and
                    Link to Course = hyperlink or picture (Format URL as Hyperlink).
                    Thanks.

                    • #34437
                      Brett
                      Participant

                        I got it, before the line: res = spjs.utility.addItem, I added the following:

                        var parentcourseID = getFieldValue("ID");

                        Then changed that line to:

                        res = spjs.utility.addItem({"listName":"Favourites","data":{"Title":url,"CourseID":parentcourseID}});

                        The Courses list ID now shows in the Favourites list.
                        I’ll try to figure out the other columns as well.
                        Thanks Alexander.

                    • #34682
                      Brett
                      Participant

                        Hi Alexander,

                        I’ve finally got this code working from a button in the List View.
                        Taken me about 3 weeks to reverse engineer each line to figure out how it worked, well worth it.
                        Just wondering if you have time to make some last adjustments?
                        1: The buttons reload each time an item is added or removed. Are you able to make it change the single button only?
                        2: For some reason, my Test User needs at least Contribute permission to the Courses list for the buttons to render, if user has Read permissions, error in console: Uncaught TypeError: jQspjs(…).filterNode is not a function.

                        Code for Calc Column: *Note the ID is copied to CoursesID via workflow.

                        ="<img src='/_layouts/images/BLANK.GIF' onload=""getIsFavorite('"&CourseID&"')"" ><span id='favBtnPlaceholder"&CourseID&"'></span>"

                        I’ve changed the “Favorites” list to “Shortlist”.
                        Also to make the button ID unique, I added the courseID number to the #favBtnPlaceholder.
                        Code for CEWP:

                        
                        
                        <a href="/sites/server/training/SPJS/DFFS/plugins/jquery.js">/sites/server/training/SPJS/DFFS/plugins/jquery.js</a>
                        <a href="/sites/server/training/SPJS/DFFS/plugins/SPJS-utility.js">/sites/server/training/SPJS/DFFS/plugins/SPJS-utility.js</a>
                        
                        <script type="text/javascript"> 
                        // Current issues:
                        // all buttons load each time an item is added to shortlist
                        // user must have contribute access to Courses list to generate buttons.
                        
                        function getIsFavorite(courseID){
                          var currDocRes, favRes, b = [];
                        
                        //grabs column variables from Courses list
                         currDocRes = spjs.utility.getItemByID({
                        		"listName":"Courses",
                        		"id":courseID,
                        		"viewFields":["ID","Title","Group","Series","TextURL"]
                        		});
                        
                          if(currDocRes !== null){ //checks if exisiting item in Shortlist
                                favRes = spjs.utility.queryItems({
                        			"listName":"Shortlist",
                        			"query":"<Where><And><Eq><FieldRef Name='Author' LookupId='TRUE' /><Value Type='User'>"+_spPageContextInfo.userId+"</Value></Eq><Eq><FieldRef Name='Title' /><Value Type='Text'>"+currDocRes.Title+"</Value></Eq></And></Where>",
                        			"viewFields":["ID"]		
                        			});
                                if(favRes.count === 0){
                                b.push("<input type='button' style='background-color:green;color:white;cursor: pointer' value='Add to Shortlist' onclick='toggleDocFav(false,\""+currDocRes.ID+"\",\""+currDocRes.Title+"\",\""+currDocRes.Group+"\",\""+currDocRes.Series+"\",\""+currDocRes.TextURL+"\")'>");       
                                }else{
                                    b.push("<input type='button' style='background-color:yellow;cursor: pointer' value='Remove from Shortlist' onclick='toggleDocFav(\""+favRes.items[0].ID+"\",\""+currDocRes.Title+"\")'>");
                                }
                            }
                            jQuery("#favBtnPlaceholder"+courseID).html(b.join(""));
                        }
                        
                        function toggleDocFav(shortlistid,courseID,parentTitle,parentGroup,parentSeries,parentURL,parentDescription){
                            var res;
                                  
                            if(!shortlistid){
                                // add to Shortlist                
                                res = spjs.utility.addItem({
                                "listName":"Shortlist",
                                "data":{
                                	"CourseID": courseID,
                                	"Title": parentTitle,
                                	"Group": parentGroup,
                                	"Series": parentSeries,
                                	"Link": parentURL
                                	}
                                });  
                           	
                                if(res.success){
                                  //  alert("Successfully added as favourite");
                                      // Refresh Shortlist web part              
                                    __doPostBack("ctl00$ctl39$g_388e590e_26cf_4a7d_8a6b_07c09678368a$ctl03","cancel");return false;
                                    getIsFavorite();           
                                }
                            }else{
                                res = spjs.utility.deleteItem({
                                "listName":"Shortlist",
                                "id":faveid
                                });
                            
                                if(res.success){
                                   // alert("Successfully removed from favourite");
                                           // Refresh Shortlist web part    
                                  __doPostBack("ctl00$ctl39$g_388e590e_26cf_4a7d_8a6b_07c09678368a$ctl03","cancel");return false;       
                                    getIsFavorite();                        
                                }
                            }
                        }
                        </script>

                        Let me know if any further details needed.
                        Thanks.

                      • #34711
                        Alexander Bautz
                        Keymaster

                          Hi,
                          I think the problem with the refresh is caused by the list view refreshing when you make changes because you use connected list view web parts.

                          If however the entire page refreshes it might help to add “;return false” behind the onclick of your button like this:

                          <input type='button' onclick='yourFunction(...);return false;' value='btn_label' />

                          Regarding the need for contribute permissions: are you sure your users have read access to where the scripts are located?

                          Alexander

                          • #34717
                            Brett
                            Participant

                              Hi Alexander, thanks for the reply.
                              It looks like the manual refresh trigger for the Shortlist reloads both web-parts.
                              Basically, my goal is to get it functioning like this page, to click the button with no page refresh. https://www.chisholm.edu.au/career-fields/it-and-cybersecurity

                              So after some research I found how to refresh a list row: https://learning.xylos.com/en/blog/ajax-refresh-for-item-rows-in-sharepoint-2013-view

                              
                              
                              // Set Ajax refresh context
                                var evtAjax = {
                                  currentCtx: ctx,
                                  csrAjaxRefresh: true
                                };
                                // Initiate Ajax Refresh on the list
                                AJAXRefreshView(evtAjax, SP.UI.DialogResult.OK);    
                                      }

                              So once added to the if(res.success) line, the Shortlist refreshes perfectly but the button does not.
                              So I just need to figure out how to refresh the button when clicked.

                              Also, the permission issue is resolved, it just wasn’t loading the scripts correctly with Read access, needed to Shift-F5 the page a few times for the buttons to load.

                              Thanks.

                              • This reply was modified 3 years, 2 months ago by Brett.
                        Viewing 6 reply threads
                        • You must be logged in to reply to this topic.