限制可以使用JavaScript在SharePoint 2013列表中输入的项目数

问题描述

我正在尝试制作一个用于事件注册的网页。我有一个页面连接到SharePoint上的列表,我想使用JS来限制人数限制为50个人。

我已经尝试过此解决方案,但是它不起作用: How to Limit the number of items that can be entered in a SharePoint List?

解决方法

我认为js解决方案不是最好的方法,只有在某些情况下才会触发js解决方案。
我建议您创建一个事件接收器(Item Adding,Item Updating)以限制列表中的数量。

public override void ItemAdding(SPItemEventProperties properties)
        {
            base.ItemAdding(properties);
            if (properties.List.ItemCount >= 50)
            {
                properties.Cancel = true;
                properties.ErrorMessage = "Contain too much item";
                properties.Status = SPEventReceiverStatus.CancelWithError;
            }                                
        }

How to: Create an event receiver

,

使用OnPreRender功能。您将必须阅读整个列表,然后不显示表单而是显示一条消息。

但是您可以不使用CSR,而是让SharePoint为您完成一半的工作。

过去的一个快速,简单的风琴补丁是隐藏NewForm内容。

在NewForm.aspx页面上,添加ListView WebPart,使其列出所有项目 将WebPart布局属性的Zone-Index更改为1,以使其在NewForm下显示 添加另一个WebPart,使用内容编辑器WebPart及其内容:

<script>
    SP.SOD.executeFunc('sp.js',null,function () {//execute after pageload
        var items = document.getElementsByClassName('ms-itmhover');//all displayed listitems
        if (items.length > 10) {//maximum number of items
            var form = document.getElementsByClassName('ms-formtable')[0];//new form
            while (form.tagName !== 'DIV') {//go up to the enclosing DIV
                form = form.parentNode;
            }
            form.innerHTML = '<h1>Numbers of records has exceeded the permitted limit: ' + items.length + '</h1>';
        } else {//optional: hide the View with all the items
            var itemlist = items[0];//first item
            while (itemlist.tagName !== 'DIV') {//go up to enclosing DIV
                itemlist = itemlist.parentNode;
            }
            itemlist.style.display = 'none';
        }
    });
</script>

提示:将javascript放在单独的文件中,然后将内容编辑器Web部件链接到它。.使其更易于编辑...您仍然必须包含