如何为Umbraco中的下拉列表分配默认值?

问题描述 投票:1回答:2

我已经基于内置下拉列表创建了自定义数据类型,但无法弄清楚如何为列表指定默认值。默认值始终为空:

enter image description here

umbraco umbraco7
2个回答
3
投票

默认下拉列表不支持默认值

有两种方法可以达到你想要的效果

  1. 创建自己的下拉数据类型(或使用其他人制作的插件 - 我不确定哪一个支持它,但可能看看nuPickers) 因为它是你定制的,你可以控制它。更多关于如何创建一个结帐doc Tutorial - Creating a property editor
  2. 使用web api处理程序拦截获取内容值的调用 - 如果属性为空,则设置默认值(null)

下面是一些未经测试的代码:

首先创建web api处理程序

public class SetDropdownDefaultHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync
            (HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var response = await base.SendAsync(request, cancellationToken);

        var url = request?.RequestUri?.AbsolutePath.ToLower;

        // only process when a create (getempty) or editing a specific content (getbyid) 
        if (url == "/umbraco/backoffice/umbracoapi/content/getempty"
            || url == "/umbraco/backoffice/umbracoapi/content/getbyid")
        {
            var content = (ObjectContent)response.Content;
            var data = content?.Value as PagedResult<ContentItemBasic<ContentPropertyBasic, IContent>>;

            if (data?.Items != null)
            {
                var tempResult = data?.Items?.ToList();

                foreach (var item in tempResult)
                {
                    foreach (var prop in item?.Properties?.Where(p => p?.Editor == "Umbraco.DropDown"))
                    {
                        var propStr = prop.Value?.ToString();
                        if (!propStr.IsNullOrWhiteSpace())
                        {
                            // set your default value if it is empty
                            prop.Value = "your default option prevalue id";
                        }
                    }
                }

                data.Items = tempResult;
            }
        }

        return response;
    }
}

然后在启动事件中注册它

public class UmbracoEvent : ApplicationEventHandler
{
  protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
  {
    GlobalConfiguration.Configuration.MessageHandlers.Add(new SetDropdownDefaultHandler());
  }
}

你的问题也许你不知道你的prevalueid - 你可以在db中查找它,或者你可以使用数据类型服务来获取数据类型prevalues然后决定将其作为默认值


1
投票

请查看:fieldTypes文件夹中的FieldType.DropDownList。

替换:<option value=""></option>

附:

var settings = Model.AdditionalSettings; <option value="">@settings["DefaultValue"]</option>

然后确保在给定表单的Umbraco Forms后台的下拉列表中设置默认值属性

enter image description here enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.