当在内容或页面编辑器中创建产品项时,我需要根据创建产品项的文件夹路径更改产品项的图像字段源。
如果我在/home/bicycles
下创建一个产品,我需要产品项目图像字段自动更改为/sitecore/media library/Images/bicycles
如果我在/home/cars
下创建一个产品,我需要产品项目图像字段自动更改为/sitecore/media library/Images/cars
如果我在/home/scooters
下创建一个产品,我需要产品项目图像字段自动更改为/sitecore/media library/Images/scooters
数据模板中该图像字段源的默认设置是/sitecore/media library/Images/bicycles
我该怎么做呢?
一个选项是创建一个扩展默认图像字段类型的自定义Content Editor字段。
首先创建一个继承自Sitecore.Shell.Applications.ContentEditor.Image
的类。然后重写OnPreRender
方法,根据您的位置标准/要求确定和设置图像字段的Source
属性。
有关更多信息,请参阅下面代码中的注释。
public class ContextAwareImageField : Sitecore.Shell.Applications.ContentEditor.Image
{
/// <summary>
/// The ItemID proprety is set by the Content Editor via reflection
/// </summary>
public string ItemID { get; set; }
/// <summary>
/// Override the OnPreRender method.
/// The base OnPreRender method assigns a value to the Source viewstate property and we need to overwrite it.
/// </summary>
/// <param name="e"></param>
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
Source = GetSource();
}
protected virtual string GetSource()
{
//retrieve and return the computed source value if it has already been set
var contextSource = GetViewStateString("ContextSource");
if (!string.IsNullOrWhiteSpace(contextSource))
return contextSource;
//retrieve the context item (the item containing the image field)
var contextItem = Sitecore.Context.ContentDatabase.GetItem(ItemID);
if (contextItem == null)
return string.Empty;
//determine the source to be used by the media browser
//in this case we're just checking based on parent path, but any logic could be inserted
contextSource = "/sitecore/media library/Images";
switch (contextItem.Parent.Paths.FullPath.ToLowerInvariant())
{
case "/sitecore/content/home/bicycles":
contextSource = "/sitecore/media library/Images/Bicycles";
break;
case "/sitecore/content/home/cars":
contextSource = "/sitecore/media library/Images/Cars";
break;
case "/sitecore/content/home/scooters":
contextSource = "/sitecore/media library/Images/Scooters";
break;
}
//store the computed source value in view bag for later retrieval
SetViewStateString("ContextSource", contextSource);
//return the computed source value
return contextSource;
}
}
接下来,执行以下步骤:
以管理员权限登录Sitecore桌面,通过右下角的数据库图标切换到Core数据库
在Core数据库中,打开Content Editor,然后导航到
/sitecore/system/Field Types/Simple Types
。在这里您将发现一个表示Image字段类型的项。复制Image字段类型项,并将复制的项重命名为相关的内容(例如Context Aware Image)。
编辑重复项
- 在Assembly字段中,提供包含自定义图像字段类(例如
MyClient.MySite.dll
)的汇编文件的名称 在Class字段中,提供自定义图像字段类的名称,包括命名空间(例如
MyClient.MySite.CustomFields.ContextAwareImageField
)- 在Assembly字段中,提供包含自定义图像字段类(例如
删除Control字段中的值
Save your changes
切换回主数据库
打开内容编辑器,然后导航到应该包含新图像字段的模板。
在模板中创建一个新字段,并在 type 下拉列表中选择新的自定义字段类型。或者,更改现有图像字段的类型
在内容树中,根据上面的模板导航到一个项目,并单击Browse按钮以查看所包含的图像字段。媒体浏览器对话框应该默认为自定义字段中逻辑指定的源位置。
- 注意:如果你使用的Sitecore版本包含一个基于speakbased的媒体浏览器对话框,你将不得不切换到树视图在对话框中(右上角的图标),以便看到您的自定义字段指定的源位置。