Modify list view column titles in a view without changing the list columns
-
04-10-2020 - |
質問
I have a page that contains list view web part. I want to rename the column titles.
I have used the following JS script, however it only shows if I click on it. Also, the id of the list view title changes sometimes.
Is there a way on how to implement this successfully?
<script type="text/javascript">
//This script is developed by Mohammad Yusuf Hussain # http://mohammadyusufhussain-sharepoint.blogspot.in/
_spBodyOnLoadFunctionNames.push("ChangeColumnName"); // Call ChangeColumnName function on PageLoad
function ChangeColumnName()
{
RenameColumn('diid8SortAuthor', 'Author'); //Provide Column ID and New Column name
}
function RenameColumn(colID, NewHeader) {
try {
document.getElementById(colID).innerHTML = NewHeader; //Change Header Name
document.getElementById(colID).title = "Sort by " + NewHeader; // Change Tooltip value
}
catch (err) {
alert('Invalid Column ID:' + colID);
}
}
UPDATE - JS function to loop through column titles:
function modifyColumns(renderCtx)
{
var arrayLength= renderCtx.ListSchema.Field.length;
for (var i=0; i < arrayLength;i++)
{
if(renderCtx.ListSchema.Field[i] == 'order_number')
{
var newTitle= "New Title";
var linkTitleField = renderCtx.ListSchema.Field[i];
linkTitleField.DisplayName = newTitle;
}
}
}
解決
First I am assuming that you're using SharePoint 2013.
I would suggest you to use SharePoint's Client Side Rendering Framework. I would suggest this blog to understand how to apply CSR.
The code which you can write to modify column names is as below (I am currently modifying "Title"):
(function () {
function preTaskFormRenderer(renderCtx) {
modifyColumns(renderCtx);
}
function modifyColumns(renderCtx)
{
var arrayLength= renderCtx.ListSchema.Field.length;
for (var i=0; i < arrayLength;i++)
{
if(renderCtx.ListSchema.Field[i].DisplayName == 'order_number')
{
var newTitle= "New Title";
var linkTitleField = renderCtx.ListSchema.Field[i];
linkTitleField.DisplayName = newTitle;
}
}
}
function registerRenderer()
{
var ctxForm = {};
ctxForm.Templates = {};
ctxForm.OnPreRender = preTaskFormRenderer;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ctxForm);
}
ExecuteOrDelayUntilScriptLoaded(registerRenderer, 'clienttemplates.js');
})();
You can also for loop to find position of a particular field. var linkTitleField = renderCtx.ListSchema.Field[0]; Here "0" refers to the position of the field. As i mentioned above you can iterate over the fields to find the position of the desired column.