Post

Развертывание списков и библиотек с помощью SPFx-решений

SharePoint Framework позволяет создавать артефакты, такие как поля, типы содержимого, экземпляры списков/библиотек и другие с помощью клиентских решений (SPFx).

В этом посте я покаже пару примеров того, как разворачивать экземпляры списков/библиотек.

Создание веб-части

Создание новой веб-части

Создание новой веб-части

Не разрешайте администраторам тенанта развертывание решения на все коллекции сайтов. Это не работает в случае, когда решение содержит ресурсы.

Elements Manifest

Element manifest is an XML-file that contains one or many elements. Most of the elements you can use described here: SharePoint Features schemas](https://docs.microsoft.com/en-us/sharepoint/dev/schema/sharepoint-features-schemas).

This post is about ListInstance elements based on out-of-the-box templates and custom list schema.

ListInstance

ListInstance element used for creating new list based on existing list template with ot without custom scheme. Common view the ListInstance definition:

<ListInstance 
    FeatureId="00bfea71-de22-43b2-a848-c05709900100" 
    Title="Custom List" 
    TemplateType="100" 
    Url="Lists/spfxList">
</ListInstance>

If you use one of the OOTB list templates you need to set the feature identifier (FeatureId) where the template is defined.

Template References

You can find some of OOTB SharePoint templates with TemplateType and FeatureId properties in the following table:

Name Type TemplateType FeatureId
Custom List List 100 00bfea71-de22-43b2-a848-c05709900100
Document Library Library 101 00bfea71-e717-4e80-aa17-d0c71b360101
Picture Library Library 109 00bfea71-52d4-45b3-b544-b1c71b620109
Wiki Page Library Library 119 00bfea71-c796-4402-9f2f-0eb9a6e71b18
Pages Library Library 850 22a9ef51-737b-4ff2-9346-694633fe4416
Links List 103 00bfea71-2062-426c-90bf-714c59600103
Contacts List 105 00bfea71-7e6d-4186-9ba8-c047ac750105
Holidays List 421 9ad4c2d4-443b-4a94-8534-49a23f20ba3c
Record Library Library 1302 da2e115b-07e4-49d9-bb2c-35e93bb9fca9

Sample

The solution provides only assets, so remove src folder with its contents. And update config\config.json file:

{
  "$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
  "version": "2.0",
  "bundles": {},
  "externals": {},
  "localizedResources": {}
}

Assets do not require bundle, localized resources, or other code.

Lists and Libraries

Create the following files in sharepoint\assets folder (create it if it not exists):

CustomList.xml (the simples and most popular template in SharePoint-based solutions):

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <ListInstance 
        FeatureId="00bfea71-de22-43b2-a848-c05709900100" 
        Url="Lists/spfxCustomList"
        TemplateType="100" 
        Title="spfxCustomList" >
    </ListInstance>
</Elements>

DocumentLibrary.xml (standard SharePoint document library):

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <ListInstance 
        FeatureId="00bfea71-e717-4e80-aa17-d0c71b360101" 
        Url="spfxDocumentLibrary" Title="spfxDocumentLibrary"
        TemplateType="101">
    </ListInstance>
</Elements>

Holidays.xml (list for holiday dates):

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <ListInstance 
        FeatureId="9ad4c2d4-443b-4a94-8534-49a23f20ba3c" 
        Url="Lists/spfxHolidays" Title="spfxHolidays"
        TemplateType="421">
    </ListInstance>
</Elements>

PictureLibrary.xml (library to store pictures):

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <ListInstance 
        FeatureId="00bfea71-52d4-45b3-b544-b1c71b620109" 
        Url="spfxPictureLibrary" Title="spfxPictureLibrary"
        TemplateType="109" >
    </ListInstance>
</Elements>

Use Lists/ prefix in the Url property for list instances. It's not required for library instances.

Custom Schema

The last list in the solution is Wiki Page Library with the custom schema. Create file PictureLibrary.xml with content:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <ListInstance 
        CustomSchema="WikiPageLibrarySchema.xml"
        FeatureId="00bfea71-c796-4402-9f2f-0eb9a6e71b18" 
        Url="spfxWikiPageLibrary" Title="spfxWikiPageLibrary"
        TemplateType="119">
    </ListInstance>
</Elements>

CustomSchema attribute contains a reference to the schema file.

Create file WikiPageLibrarySchema.xml:

<List xmlns:ows="Microsoft SharePoint" 
    Title="SPFx Wiki Pages" 
    Direction="$Resources:Direction;" 
    Url="spfxWikiPageLibrary" 
    BaseType="1" 
    xmlns="http://schemas.microsoft.com/sharepoint/">
    <MetaData>
        <ContentTypes></ContentTypes>
        <Fields></Fields>
        <Views>
            <View BaseViewID="1" 
                Type="HTML" 
                WebPartZoneID="Main" 
                DisplayName="$Resources:core,objectiv_schema_mwsidcamlidC24;" 
                DefaultView="TRUE" 
                SetupPath="pages\viewpage.aspx" 
                Url="spfxCutomView.aspx">
                <Toolbar Type="Standard" />
                <XslLink Default="TRUE">main.xsl</XslLink>
                <JSLink>clienttemplates.js</JSLink>
                <RowLimit Paged="TRUE">30</RowLimit>
                <ViewFields>
                    <FieldRef Name="ID"></FieldRef>
                    <FieldRef Name="LinkTitle"></FieldRef>
                    <FieldRef Name="Created"></FieldRef>
                    <FieldRef Name="Modified"></FieldRef>
                </ViewFields>
                <Query>
                    <OrderBy>
                        <FieldRef Name="Title"></FieldRef>
                    </OrderBy>
                </Query>
            </View>
        </Views>
        <Forms>
            <Form Type="DisplayForm" Url="DispForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
            <Form Type="EditForm" Url="EditForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
            <Form Type="NewForm" Url="NewForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
        </Forms>
    </MetaData>
</List>

As you can see I defined the default view of the wiki page library.

Title property in list definitions (schema) does not override the Title property of ListInstance.

Feature

Firstly released in SharePoint 2007 feature definitions come back in SharePoint Framework. You can define one or many features in the solution. Each solution can contain one or many assets.

To add a feature in the project open config\package-solution.json file and add features section under solution:

{
  "$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
  "solution": {
    "name": "spfx-assets-list-instance-client-side-solution",
    "id": "0b71bd29-c1bc-429d-8c9a-8c9e3775b9fe",
    "version": "1.0.0.0",
    "includeClientSideAssets": true,
    "isDomainIsolated": false,
    "features": [
      {
        "title": "List Instance Demo Feature",
        "description": "blog.vitalyzhukov.ru",
        "id": "2ea1bd20-091e-4024-9b72-f084bdc72bda",
        "version": "1.0.0.0",
        "assets": {
          "elementManifests": [
            "CustomList.xml",
            "DocumentLibrary.xml",
            "Holidays.xml",
            "PictureLibrary.xml",
            "WikiPageLibrary.xml"
          ],
          "elementFiles": [
            "WikiPageLibrarySchema.xml"
          ]
        }
      }
    ]
  },
  "paths": {
    "zippedPackage": "solution/spfx-assets-list-instance.sppkg"
  }
}

Properties of the feature:

  • title - the name of the feature. displayed on the site feature list
  • description - description of the feature. displayed on the site feature list
  • id - unique identifier of the feature
  • version - version of the feature defined as Major.Minor.Build.Revision
  • assets - assets of the feature.

There are three types of feature assets:

  • elementManifests - manifest that contains all the SharePoint artifacts of the feature. You can split your definitions into separate files
  • elementFiles - additional files which used be manifest
  • upgradeActions - definition of actions which must be applied in case of upgrade the existing feature

I defined a single feature and bound the assets to it.

Package

Use the following gulp task to package assets, feature and solution into SharePoint package (.spkg):

gulp package-solution --ship

The package will be placed in the sharepoint\solution folder.

Deploy Solution

Open App Catalog in your SharePoint Online tenant and deploy the solution:

Deploying SPFx solution to SharePoint Online

Deploying SPFx solution to SharePoint Online

Add the App

On SharePoint site go to site contents and add the app:

Adding SPFx app to SharePoint site

Adding SPFx app to SharePoint site

When the app will be deployed (it takes about a minute) you'll see all the lists and libraries defined in the feature.

Assets deployed with SPFx app

Assets deployed with SPFx app

Open spfxWikiPageLibrary which is defined with the custom schema to make sure the default view matches the schema:

Split cell in SharePoint Modern UI

Split cell

Localization

By today it's a gap, there is no way to provide custom resource file for assets or reference built-in SharePoint .resx files.

Summary

What was done:

  1. Created a new SPFx web part with yeoman generator.
  2. Removed src folder and reference to bundle and localized resources. The solution contains only assets, no web part is required.
  3. Added list instance elements and one schema file. I defined a set of different assets.
  4. Bound the assets to the single feature to make them be deployed together.
  5. Deployed the solution and added the app to the SharePoint site.

See Also

Provision SharePoint assets from your SharePoint client-side web part

Source Code

The source code published on GitHub: https://github.com/vzhukov/spfx-assets-list-instance.

Виталий Жуков

Виталий Жуков

SharePoint архитектор, разработчик, тренер, Microsoft MVP (Office Development). Более 15 лет опыта работы с SharePoint, Dynamics CRM, Office 365, и другими продуктами и сервисами Microsoft.

Смотрите также

SharePoint. Drag-and-Drop Загрузчик файлов

SharePoint. Drag-and-Drop Загрузчик файлов

CSOM. Загрузка файлов

CSOM. Загрузка файлов

SharePoint List REST API. Часть 2

SharePoint List REST API. Часть 2

SharePoint Framework. Создание веб-части на Angular

SharePoint Framework. Создание веб-части на Angular

SharePoint List REST API. Часть 1

SharePoint List REST API. Часть 1

Презентация с доклада о SharePoint Framework

Презентация с доклада о SharePoint Framework

SharePoint Framework. Создаем AngularJS 1.x Client WebPart

SharePoint Framework. Создаем AngularJS 1.x Client WebPart

SharePoint. Регистрация CSS и JavaScript с помощью DelegateControl

SharePoint. Регистрация CSS и JavaScript с помощью DelegateControl

SharePoint. Расширяем REST API

SharePoint. Расширяем REST API

SharePoint Excel Services. Создаем кредитный калькулятор

SharePoint Excel Services. Создаем кредитный калькулятор

SharePoint Ribbon API. Использование ToggleButton

SharePoint Ribbon API. Использование ToggleButton

SharePoint 2013. How To: настройка входящей почты для разработчиков

SharePoint 2013. How To: настройка входящей почты для разработчиков

Мифы и правда о Linq to SharePoint

Мифы и правда о Linq to SharePoint

5 особенностей SPSiteDataQuery

5 особенностей SPSiteDataQuery

SharePoint 2013. Введение в SharePoint App. Часть 2

SharePoint 2013. Введение в SharePoint App. Часть 2

SharePoint 2013. Введение в SharePoint App. Часть 1

SharePoint 2013. Введение в SharePoint App. Часть 1

Превью для веб-части в SharePoint 2010/2013

Превью для веб-части в SharePoint 2010/2013

SharePoint 2013. Еще немного о новых контролах

SharePoint 2013. Еще немного о новых контролах

SharePoint 2013. Контрол ClientPeoplePicker

SharePoint 2013. Контрол ClientPeoplePicker

SharePoint 2013. Контрол ImageCrop

SharePoint 2013. Контрол ImageCrop

SharePoint 2013. Тип поля Geolocation

SharePoint 2013. Тип поля Geolocation

Создание типа поля в SharePoint

Создание типа поля в SharePoint

SharePoint 2010. Длительные операции с обновляемым статусом

SharePoint 2010. Длительные операции с обновляемым статусом

Linq to SharePoint. Создаем ContentIterator

Linq to SharePoint. Создаем ContentIterator

Linq to SharePoint. Получение данных из другой коллекции сайтов

Linq to SharePoint. Получение данных из другой коллекции сайтов

Linq to SharePoint. Версионность

Linq to SharePoint. Версионность

SharePoint. Получение URL-адреса иконки для документа

SharePoint. Получение URL-адреса иконки для документа

SharePoint 2010. PostBack для Fluent Ribbon API

SharePoint 2010. PostBack для Fluent Ribbon API

Linq to SharePoint. Блокировка документов

Linq to SharePoint. Блокировка документов

Linq to SharePoint. Паттерн Repository

Linq to SharePoint. Паттерн Repository

Linq to SharePoint. Получение мета-данных списка

Linq to SharePoint. Получение мета-данных списка

Linq to SharePoint. Мапинг полей

Linq to SharePoint. Мапинг полей

Linq to SharePoint. Формирование данных для ProcessBatchData

Linq to SharePoint. Формирование данных для ProcessBatchData

Linq to SharePoint. Сравнение производительности с Camlex.NET

Linq to SharePoint. Сравнение производительности с Camlex.NET

Linq to SharePoint. Часть 5. Поля Choice и MultiChoice

Linq to SharePoint. Часть 5. Поля Choice и MultiChoice

Linq to SharePoint. Часть 4. Dynamic LINQ

Linq to SharePoint. Часть 4. Dynamic LINQ

Linq to SharePoint. Особенности. Часть 3

Linq to SharePoint. Особенности. Часть 3

Linq to SharePoint. Особенности. Часть 2

Linq to SharePoint. Особенности. Часть 2

SharePoint 2010. PeopleEditor. Установка значения

SharePoint 2010. PeopleEditor. Установка значения

SharePoint 2010. Настройка входящей почты для кастомного списка

SharePoint 2010. Настройка входящей почты для кастомного списка

Linq to Sharepoint. Особенности

Linq to Sharepoint. Особенности

EntityFramework. Оптимистические блокировки

EntityFramework. Оптимистические блокировки