Orchardcore custom settings

From CrestApps/CrestApps.AgentSkills · View interactive version

Orchardcore custom settings is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for creating admin-defined custom site settings in Orchard Core using the CustomSettings stereotype. Covers settings content types in code or recipes, the per-section ManageCustomSettings permission, GetCustomSettingsAsync, Liquid access through Site.Properties and the PermittedSiteProperties

How to use this skill

Skill file

Orchard Core Custom Settings - Prompt Templates

Create Custom Site Settings

You are an Orchard Core expert. Generate code and configuration for creating site-wide settings sections using the CustomSettings stereotype.

Guidelines

Enabling Custom Settings

{
  "steps": [
    {
      "name": "Feature",
      "enable": [
        "OrchardCore.CustomSettings"
      ],
      "disable": []
    }
  ]
}

Creating a Custom Settings Type via Code

Step 1: Define the Content Part
public sealed class {{SettingsPartName}} : ContentPart
{
    public string {{PropertyName}} { get; set; }

    public bool {{BoolPropertyName}} { get; set; }
}
Step 2: Register the Content Type with the CustomSettings Stereotype
public sealed class Migrations : DataMigration
{
    private readonly IContentDefinitionManager _contentDefinitionManager;

    public Migrations(IContentDefinitionManager contentDefinitionManager)
    {
        _contentDefinitionManager = contentDefinitionManager;
    }

    public async Task<int> CreateAsync()
    {
        await _contentDefinitionManager.AlterTypeDefinitionAsync("{{SettingsTypeName}}", type => type
            .DisplayedAs("{{Settings Display Name}}")
            .Stereotype("CustomSettings")
            .WithPart("{{SettingsPartName}}", part => part
                .WithPosition("0")
            )
        );

        return 1;
    }
}
Step 3: Register Services in Startup
[RequireFeatures("OrchardCore.CustomSettings")]
public sealed class Startup : StartupBase
{
    public override void ConfigureServices(IServiceCollection services)
    {
        services.AddContentPart<{{SettingsPartName}}>()
            .UseDisplayDriver<{{SettingsPartName}}DisplayDriver>();

        services.AddDataMigration<Migrations>();
    }
}

Registering a typed part only supplies its CLR model. Add a display driver when its CLR properties need an editor:

public sealed class {{SettingsPartName}}DisplayDriver : ContentPartDisplayDriver<{{SettingsPartName}}>
{
    public override IDisplayResult Edit({{SettingsPartName}} part, BuildPartEditorContext context)
        => Initialize<{{SettingsPartName}}ViewModel, {{SettingsPartName}}>("{{SettingsPartName}}_Edit", static (model, part) =>
        {
            model.{{PropertyName}} = part.{{PropertyName}};
            model.{{BoolPropertyName}} = part.{{BoolPropertyName}};
        }, part);

    public override async Task<IDisplayResult> UpdateAsync({{SettingsPartName}} part, UpdatePartEditorContext context)
    {
        var model = new {{SettingsPartName}}ViewModel();

        await context.Updater.TryUpdateModelAsync(model, Prefix);

        part.{{PropertyName}} = model.{{PropertyName}};
        part.{{BoolPropertyName}} = model.{{BoolPropertyName}};

        return Edit(part, context);
    }
}

public class {{SettingsPartName}}ViewModel
{
    public string {{PropertyName}} { get; set; }

    public bool {{BoolPropertyName}} { get; set; }
}

Content fields attached to the part (Media, Html, Link, ...) are rendered by their own drivers; no extra driver code is needed for them.

Accessing Custom Settings in Code

public sealed class MyService
{
    private readonly ISiteService _siteService;

    public MyService(ISiteService siteService)
    {
        _siteService = siteService;
    }

    public async Task<{{SettingsPartName}}> GetSettingsAsync()
    {
        ContentItem settingsItem = await _siteService.GetCustomSettingsAsync("{{SettingsTypeName}}");

        return settingsItem.GetOrCreate<{{SettingsPartName}}>();
    }
}

Without the extension method:

var siteSettings = await _siteService.GetSiteSettingsAsync();
var settingsItem = siteSettings.GetOrCreate<ContentItem>("{{SettingsTypeName}}");

GetCustomSettingsAsync() returns the cached instance; do not modify it. To change a section in code, use LoadSiteSettingsAsync(), update site.Properties["{{SettingsTypeName}}"], and call UpdateSiteSettingsAsync().

Custom settings types can be edited in the admin by anyone with the EditContentTypes permission, so treat their schema as part of your deployment and avoid relying on parts that administrators can remove.

Accessing Custom Settings in Controllers

public sealed class MyController : Controller
{
    private readonly ISiteService _siteService;

    public MyController(ISiteService siteService)
    {
        _siteService = siteService;
    }

    public async Task<IActionResult> Index()
    {
        var settingsItem = await _siteService.GetCustomSettingsAsync("{{SettingsTypeName}}");
        var settings = settingsItem.GetOrCreate<{{SettingsPartName}}>();

        return View(settings);
    }
}

Accessing Custom Settings in Liquid

First allow the section names (application or tenant configuration):

{
  "OrchardCore": {
    "Liquid": {
      "PermittedSiteProperties": [
        "{{SettingsTypeName}}",
        "BlogSettings"
      ]
    }
  }
}

Then read them by type name and part name:

{{ Site.Properties.{{SettingsTypeName}}.{{SettingsPartName}}.{{PropertyName}} }}

HTML stored in a custom settings section is persisted exactly as authored and is only sanitized when rendered through its display shape. When outputting raw HTML from Liquid, sanitize it explicitly:

{{ Site.Properties.BlogSettings.HtmlBodyPart.Html | sanitize_html | raw }}

Liquid syntax inside that HTML is not executed. Add a LiquidPart (or a LiquidField) to the section when editors need templated content.

Permissions

  1. Navigate to Security → Roles and edit a role.
  2. Under the OrchardCore.CustomSettings group, check Manage Custom Settings - {Display Name}.

The permission name is ManageCustomSettings_{TypeName}; grant it to the roles that must see and save the section.

Custom Settings with Content Fields

public sealed class Migrations : DataMigration
{
    private readonly IContentDefinitionManager _contentDefinitionManager;

    public Migrations(IContentDefinitionManager contentDefinitionManager)
    {
        _contentDefinitionManager = contentDefinitionManager;
    }

    public async Task<int> CreateAsync()
    {
        await _contentDefinitionManager.AlterTypeDefinitionAsync("BrandingSettings", type => type
            .DisplayedAs("Branding Settings")
            .Stereotype("CustomSettings")
            .WithPart("BrandingSettings", part => part
                .WithPosition("0")
            )
        );

        await _contentDefinitionManager.AlterPartDefinitionAsync("BrandingSettings", part => part
            .WithField("Logo", field => field
                .OfType("MediaField")
                .WithDisplayName("Site Logo")
                .WithPosition("0")
            )
            .WithField("FooterText", field => field
                .OfType("HtmlField")
                .WithDisplayName("Footer Text")
                .WithPosition("1")
                .WithEditor("Wysiwyg")
            )
            .WithField("SocialLink", field => field
                .OfType("LinkField")
                .WithDisplayName("Social Media Link")
                .WithPosition("2")
            )
        );

        return 1;
    }
}
{% assign branding = Site.Properties.BrandingSettings.BrandingSettings %}
{{ branding.FooterText.Html | sanitize_html | raw }}
<a href="{{ branding.SocialLink.Url }}">{{ branding.SocialLink.Text }}</a>

(Requires "BrandingSettings" in PermittedSiteProperties.)

Configuring Custom Settings via Recipe

The custom-settings step copies each named entry into the site Properties:

{
  "steps": [
    {
      "name": "custom-settings",
      "{{SettingsTypeName}}": {
        "ContentItemId": "[js:uuid()]",
        "ContentType": "{{SettingsTypeName}}",
        "{{SettingsPartName}}": {
          "{{PropertyName}}": "{{value}}",
          "{{BoolPropertyName}}": true
        }
      }
    }
  ]
}

Creating a Custom Settings Content Type via Recipe

{
  "steps": [
    {
      "name": "ContentDefinition",
      "ContentTypes": [
        {
          "Name": "{{SettingsTypeName}}",
          "DisplayName": "{{Settings Display Name}}",
          "Settings": {
            "ContentTypeSettings": {
              "Stereotype": "CustomSettings"
            }
          },
          "ContentTypePartDefinitionRecords": [
            {
              "PartName": "{{SettingsPartName}}",
              "Name": "{{SettingsPartName}}",
              "Settings": {
                "ContentTypePartSettings": {
                  "Position": "0"
                }
              }
            }
          ]
        }
      ]
    }
  ]
}

Deployment

The Custom Settings deployment step (in the Settings category, requires OrchardCore.Deployment) exports all sections, or the selected SettingsTypeNames, as a custom-settings recipe step. Only sections the exporting user may manage are exported.

Upgrading from 3.x

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.